================================================================================ # Page: /en/community/index # Source: src/content/en/community/index.mdx ================================================================================ # Community Hub Welcome to the \{xpay✦\} community! We're building the future of autonomous payments together. Join thousands of developers creating the next generation of AI agents and x402-powered applications. ## Join Our Community ### 💬 Discord Server Our Discord is the heart of the \{xpay✦\} community. Get real-time help, share projects, and connect with other developers. **[Join Discord →](https://discord.gg/vukXDGT7n5)** **Channels:** - `#general` - General discussion and announcements - `#developer-help` - Get help with integration issues - `#agent-dev` - Discuss agent development patterns - `#api-monetization` - API provider strategies and tips - `#showcase` - Share your projects and success stories - `#x402-protocol` - Deep technical discussions about x402 - `#feedback` - Provide feedback on \{xpay✦\} products ### 🐙 GitHub Contribute to our open source projects and report issues. **[\{xpay✦\} on GitHub →](https://github.com/xpaysh)** **Key Repositories:** - [xpay-agent-kit](https://github.com/xpaysh/agent-kit) - Core agent development tools - [awesome-x402](https://github.com/xpaysh/awesome-x402) - Curated x402 resources - [x402-local](https://github.com/xpaysh/x402-local) - Local development environment - [xpay-docs](https://github.com/xpaysh/xpay-docs) - This documentation site ### 🐦 Twitter/X Follow us for updates, tips, and community highlights. **[@xpaysh](https://twitter.com/xpaysh)** ### 📺 YouTube Video tutorials, talks, and community spotlights. **[\{xpay✦\} YouTube Channel →](https://youtube.com/@xpaysh)** ## Community Programs ### 🚀 Developer Beta Program Get early access to new features and provide feedback on upcoming releases. **Benefits:** - Early access to new product features - Direct line to our engineering team - Influence product roadmap - Beta testing rewards and swag **[Apply for Beta →](https://forms.gle/xpay-beta)** ### 🏆 Community Champions Recognize outstanding community members who help others and contribute to the ecosystem. **What Champions Do:** - Answer questions in Discord and GitHub - Create tutorials and content - Speak at events and meetups - Contribute to open source projects **Champion Benefits:** - Exclusive Discord badge and role - Early access to features - Direct access to \{xpay✦\} team - Conference speaking opportunities - Annual Champion summit **[Nominate a Champion →](https://forms.gle/xpay-champions)** ### 💡 Bounty Program Earn rewards for contributing to the \{xpay✦\} ecosystem. **Current Bounties:** - **Documentation**: $100-500 for tutorial creation - **Bug Reports**: $25-200 for validated bug reports - **Feature Requests**: $50-300 for detailed feature specifications - **Integration Examples**: $200-1000 for framework integration guides - **Open Source**: $500-2000 for significant open source contributions **[View Active Bounties →](https://github.com/xpaysh/bounties)** ## Events & Meetups ### 🌍 Global Meetups Join local \{xpay✦\} meetups in major cities worldwide. **Upcoming Events:** - **San Francisco** - Monthly agent development meetup - **New York** - API monetization workshop series - **London** - x402 protocol deep dives - **Berlin** - Developer community meetup - **Singapore** - Asia-Pacific x402 summit **[Find a Meetup →](https://meetup.com/xpay-community)** ### 🎤 Conference Talks Catch \{xpay✦\} team and community talks at major conferences: - **AI Engineer Summit** - Agent payment patterns - **API World** - x402 protocol overview - **Web3 Summit** - Future of autonomous payments - **Developer Week** - Building monetized APIs ### 📅 Community Calendar **Weekly Events:** - **Monday Office Hours** - Ask questions to \{xpay✦\} team (Discord) - **Wednesday Workshop** - Technical deep dives (YouTube Live) - **Friday Showcase** - Community project demos (Discord) **Monthly Events:** - **Community Call** - Updates, roadmap, Q&A - **Developer AMA** - Ask anything session - **Partner Spotlight** - Ecosystem partner presentations ## Contributing ### 📝 Documentation Help improve our documentation: - Fix typos and unclear explanations - Add missing examples and use cases - Translate docs to other languages - Create video tutorials **[Contribute to Docs →](https://github.com/xpaysh/xpay-docs/blob/main/CONTRIBUTING.md)** ### 🔧 Open Source Contribute to our open source projects: - **Bug Fixes**: Help squash bugs in our SDKs - **New Features**: Implement requested features - **Performance**: Optimize existing code - **Testing**: Improve test coverage **[Open Source Guide →](/community/contributing)** ### 💬 Community Support Help other developers in the community: - Answer questions in Discord - Provide feedback on GitHub issues - Share your integration experiences - Mentor new developers ## Success Stories ### Featured Community Projects #### AgentGPT x402 Integration **By @developer_alex** "Integrated \{xpay✦\} smart proxy with AgentGPT to prevent runaway costs. Saved $2,400 in the first month by catching an infinite loop bug." [View Project →](https://github.com/developer_alex/agentgpt-\{xpay✦\}) #### AI Content Marketplace **By @sarah_builds** "Built a marketplace where AI models can autonomously buy and sell training data using x402 payments. Generated $10K revenue in first quarter." [Case Study →](https://www.xpay.sh/case-studies/ai-marketplace) #### x402 WordPress Plugin **By @wp_hacker** "Created a WordPress plugin that monetizes blog content with x402 micro-payments. Bloggers earn $0.01 per article view." [Plugin →](https://wordpress.org/plugins/x402-paywall/) ### Community Stats - **5,000+** developers in Discord - **50+** open source contributors - **200+** community projects - **15** countries with local meetups - **$100K+** in community bounties paid ## Code of Conduct We're committed to providing a welcoming and inclusive environment for all community members. **Our Values:** - **Be respectful** - Treat everyone with kindness and respect - **Be helpful** - Share knowledge and help others learn - **Be constructive** - Provide actionable feedback and suggestions - **Be inclusive** - Welcome developers of all backgrounds and skill levels **[Read Full Code of Conduct →](https://github.com/xpaysh/community/blob/main/CODE_OF_CONDUCT.md)** ## Get Help ### Support Channels 1. **Discord** - Real-time help from community 2. **GitHub Issues** - Report bugs and request features 3. **Email Support** - Enterprise and billing support 4. **Office Hours** - Weekly live Q&A sessions ### Documentation - **[Getting Started →](/getting-started)** - Basic setup and first steps - **[API Reference →](/api-reference)** - Complete API documentation - **[Guides →](/guides)** - In-depth tutorials and best practices - **[FAQ →](/community/support#faq)** - Frequently asked questions ### Professional Services Need help with a custom integration? Our partner network offers: - **Integration Consulting** - Expert help with complex implementations - **Custom Development** - Build custom x402 solutions - **Training Workshops** - Team training and onboarding - **Architecture Review** - Review and optimize your x402 architecture **[Find a Partner →](https://www.xpay.sh/partners)** --- Ready to get involved? [Join our Discord →](https://discord.gg/vukXDGT7n5) and introduce yourself in the `#general` channel! ================================================================================ # Page: /en/developer-resources/index # Source: src/content/en/developer-resources/index.mdx ================================================================================ # Developer Resources Everything you need to build with \{xpay✦\} and the x402 protocol. From SDKs and code examples to testing tools and open source projects. ## SDKs & Libraries ### Official \{xpay✦\} SDKs | Package | Description | Install | |---------|-------------|---------| | `@xpaysh/agent-kit` | Complete toolkit for agent developers | `npm install @xpaysh/agent-kit` | | `@xpaysh/agent-kit` | Agent spending protection | `npm install @xpaysh/agent-kit` | | `@xpaysh/agent-kit` | API monetization tools | `npm install @xpaysh/agent-kit` | | `@xpaysh/explorer` | Transaction monitoring | `npm install @xpaysh/explorer` | | `@xpaysh/sdk` | Core x402 utilities | `npm install @xpaysh/sdk` | ### x402 Protocol SDKs | Language | Package | Description | |----------|---------|-------------| | TypeScript | `@x402/sdk` | Official TypeScript SDK | | Python | `x402-python` | Python implementation | | Go | `x402-go` | Go implementation | | Rust | `x402-rust` | Rust implementation | ## Code Examples ### Quick Start Examples ```typescript // Agent with spending limits import { SmartProxy } from '@xpaysh/agent-kit' const smartProxy = new SmartProxy({ maxDailySpend: 100, maxPerRequest: 5 }) const response = await smartProxy.protectedFetch('https://api.openai.com/v1/chat/completions', { method: 'POST', body: JSON.stringify({ model: 'gpt-4', messages: [{ role: 'user', content: 'Hello' }] }) }) ``` ```typescript // API monetization import { XpayPaywall } from '@xpaysh/agent-kit' import express from 'express' const app = express() const paywall = new Paywall({ pricePerRequest: 0.10, receivingWallet: '0x...' }) app.get('/api/premium', paywall.middleware, (req, res) => { res.json({ data: 'Premium content' }) }) ``` ### Framework Integrations #### Next.js ```typescript // pages/api/protected.ts import { NextApiRequest, NextApiResponse } from 'next' import { XpayPaywall } from '@xpaysh/agent-kit' const paywall = new Paywall({ pricePerRequest: 0.05, receivingWallet: process.env.RECEIVING_WALLET }) export default async function handler(req: NextApiRequest, res: NextApiResponse) { const paymentResult = await paywall.verifyPayment(req) if (!paymentResult.success) { return res.status(402).json({ error: 'Payment required', payment: paymentResult.paymentInstructions }) } res.json({ message: 'Access granted' }) } ``` #### LangChain ```typescript import { ChatOpenAI } from 'langchain/chat_models/openai' import { SmartProxy } from '@xpaysh/agent-kit' const smartProxy = new SmartProxy({ maxDailySpend: 50, agentId: 'langchain-agent' }) const chat = new ChatOpenAI({ openAIApiKey: process.env.OPENAI_API_KEY, configuration: { fetch: smartProxy.protectedFetch.bind(smartProxy) } }) ``` #### Vercel Edge Functions ```typescript import { NextRequest } from 'next/server' import { XpayPaywall } from '@xpaysh/agent-kit' export const config = { runtime: 'edge' } const paywall = new Paywall({ pricePerRequest: 0.01, receivingWallet: process.env.RECEIVING_WALLET }) export default async function handler(req: NextRequest) { return await paywall.handleEdgeRequest(req) } ``` ## Open Source Projects \{xpay✦\} actively contributes to the x402 ecosystem with open source tools: ### Core Projects #### [awesome-x402](https://github.com/xpaysh/awesome-x402) **Curated list of x402 resources** - Protocol documentation and tutorials - SDK implementations in multiple languages - Real-world examples and case studies - Community tools and resources #### [x402-agent-kit](https://github.com/xpaysh/x402-agent-kit) **Build x402-paying agents in 5 minutes** - Sample LangChain agent with x402 payments - Mock x402-protected API for testing - Docker compose for instant local development - Integration guides for popular agent frameworks #### [x402-local](https://github.com/xpaysh/x402-local) **Local x402 development environment** - `npx x402-local` for instant setup - Local facilitator simulation - CLI for generating test wallets - Browser extension for payment injection #### [x402-sdk](https://github.com/xpaysh/x402-sdk) **TypeScript-first x402 SDK** - Zero-dependency implementation - Full TypeScript types - React hooks for x402 payments - Excellent documentation and examples ## Development Tools ### CLI Tools #### \{xpay✦\} CLI ```bash # Install globally npm install -g @xpaysh/cli # Create new smart proxy xpaysh smart-proxy create --name "my-agents" # Configure agent limits xpay agent configure my-bot --max-daily 100 --max-request 5 # Monitor spending xpay monitor --agent my-bot --live ``` #### x402 Local Development ```bash # Start local x402 environment npx x402-local start # Generate test wallets with funds npx x402-local wallet create --fund 100 # Mock API with x402 protection npx x402-local mock-api --price 0.05 --port 3001 ``` ### Browser Extensions #### \{xpay✦\} DevTools Browser extension for debugging x402 payments: - Monitor payment flows in real-time - Inspect payment instructions and responses - Test payment scenarios without real funds - Debug agent spending patterns ### Testing Tools #### Payment Simulation ```typescript import { MockX402Server } from '@xpaysh/agent-kit-testing' const mockServer = new MockX402Server({ port: 3001, price: 0.05, currency: 'USDC' }) await mockServer.start() // Test your agent against mock API const response = await agent.callAPI('http://localhost:3001/api/test') ``` #### Spending Simulation ```typescript import { SpendingSimulator } from '@xpaysh/agent-kit-testing' const simulator = new SpendingSimulator({ agent: 'test-agent', maxDailySpend: 100 }) // Simulate various spending patterns await simulator.simulatePattern('steady', { requestsPerHour: 10 }) await simulator.simulatePattern('burst', { peakRequestsPerSecond: 5 }) await simulator.simulatePattern('random', { averageRequestsPerMinute: 2 }) ``` ## Testing & Debugging ### Test Networks | Network | Purpose | USDC Contract | Faucet | |---------|---------|---------------|--------| | Base Sepolia | Testing | `0x036CbD53842c5426634e7929541eC2318f3dCF7e` | [Circle Faucet](https://faucet.circle.com/) | | Ethereum Sepolia | Testing | `0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238` | [Circle Faucet](https://faucet.circle.com/) | | Polygon Amoy | Testing | `0x41e94eb019c0762f9bfcf9fb1e58725bfb0e7582` | [Circle Faucet](https://faucet.circle.com/) | ### Debugging Common Issues #### Payment Verification Failures ```typescript import { X402Debug } from '@xpaysh/sdk' const debug = new X402Debug({ facilitator: 'https://facilitator.xpay.sh', network: 'base-sepolia' }) // Debug payment verification const result = await debug.verifyPayment('payment_123') console.log('Payment status:', result.status) console.log('Failure reason:', result.failureReason) console.log('Transaction hash:', result.txHash) ``` #### Agent Spending Analysis ```typescript import { XpayAnalytics } from '@xpaysh/agent-kit' const analytics = new XpayAnalytics({ apiKey: process.env.XPAY_API_KEY }) // Analyze agent spending patterns const report = await analytics.analyzeAgent('my-bot', { timeframe: '7d', includeFailures: true }) console.log('Total spend:', report.totalSpend) console.log('Average per request:', report.averagePerRequest) console.log('Failure rate:', report.failureRate) ``` ## API References ### REST APIs - **[\{xpay✦\} API Reference](/api-reference)** - Complete API documentation - **[x402 Facilitator API](https://docs.cdp.coinbase.com/x402/reference/)** - Coinbase facilitator API - **[Base Network API](https://docs.base.org/api)** - Base blockchain API ### WebSocket APIs ```typescript import { XpayWebSocket } from '@xpaysh/agent-kit' const ws = new XpayWebSocket({ apiKey: process.env.XPAY_API_KEY, projectId: 'proj_123' }) // Real-time agent spending updates ws.subscribe('agent.spending', (event) => { console.log('Agent spending update:', event) }) ``` ## Community Resources ### Discord Channels Join our Discord server for real-time help: - **#general** - General discussion - **#developer-help** - Get help with integration - **#agent-dev** - Agent development discussion - **#api-monetization** - API provider discussion - **#showcase** - Show off your projects ### GitHub Discussions - **[Feature Requests](https://github.com/xpaysh/agent-kit/discussions/categories/feature-requests)** - **[Help & Support](https://github.com/xpaysh/agent-kit/discussions/categories/help-support)** - **[Show and Tell](https://github.com/xpaysh/agent-kit/discussions/categories/show-and-tell)** --- Need more help? Check out our [community support options →](/community/support) ================================================================================ # Page: /en/developer-resources/integration-patterns # Source: src/content/en/developer-resources/integration-patterns.mdx ================================================================================ # Advanced Integration Patterns Real-world integration patterns for complex Xpay deployments, based on production experience and customer use cases. import { Callout } from 'nextra/components' **Production-Tested**: These patterns are based on real customer deployments and have been battle-tested in production environments. ## Multi-Tenant Agent Management ### SaaS Application Pattern For SaaS applications serving multiple customers, each with their own agents: ```typescript import { SmartProxy } from '@xpaysh/agent-kit' class MultiTenantAgentManager { private smartProxies: Map = new Map() constructor(private config: { defaultLimits: AgentLimits tierConfigs: Record }) {} async initializeTenant(tenantId: string, tier: string = 'basic') { const tierConfig = this.config.tierConfigs[tier] const smartProxy = new SmartProxy({ endpoint: `https://smart-proxy-${tenantId}.xpay.sh`, apiKey: process.env.XPAY_API_KEY!, // Tenant-specific configuration defaultLimits: { dailyLimit: tierConfig.dailyLimit, perCallLimit: tierConfig.perCallLimit, monthlyLimit: tierConfig.monthlyLimit }, // Isolated webhook endpoints webhookEndpoint: `https://api.yourapp.com/webhooks/xpay/${tenantId}`, // Tenant-specific caching cachePrefix: `tenant:${tenantId}` }) this.smartProxies.set(tenantId, smartProxy) return smartProxy } async createAgentForTenant( tenantId: string, userId: string, agentConfig: Partial ): Promise { const smartProxy = this.getSmartProxyForTenant(tenantId) const tier = await this.getTenantTier(tenantId) const tierLimits = this.config.tierConfigs[tier] // Apply tenant-specific limits and branding const agent = await smartProxy.createAgent({ ...agentConfig, id: `${tenantId}-${agentConfig.id}`, userId: `${tenantId}-${userId}`, customerId: tenantId, // Apply tier limits dailyLimit: Math.min(agentConfig.dailyLimit || Infinity, tierLimits.dailyLimit), perCallLimit: Math.min(agentConfig.perCallLimit || Infinity, tierLimits.perCallLimit), monthlyLimit: Math.min(agentConfig.monthlyLimit || Infinity, tierLimits.monthlyLimit), // Tenant-specific metadata metadata: { tenant: tenantId, tier: tier, createdBy: userId } }) // Track tenant usage await this.trackTenantUsage(tenantId, 'agent_created') return agent } async getAgentsForTenant(tenantId: string, userId?: string): Promise { const smartProxy = this.getSmartProxyForTenant(tenantId) const agents = await smartProxy.listAgents({ search: userId ? `${tenantId}-${userId}` : tenantId }) return agents.agents } private getSmartProxyForTenant(tenantId: string): SmartProxy { const smartProxy = this.smartProxies.get(tenantId) if (!smartProxy) { throw new Error(`Tenant ${tenantId} not initialized`) } return smartProxy } private async getTenantTier(tenantId: string): Promise { // Query your database for tenant subscription tier const tenant = await db.query('SELECT tier FROM tenants WHERE id = $1', [tenantId]) return tenant.rows[0]?.tier || 'basic' } private async trackTenantUsage(tenantId: string, event: string) { // Track usage for billing/analytics await analytics.track({ event, tenantId, timestamp: new Date() }) } } // Usage in your SaaS application const agentManager = new MultiTenantAgentManager({ defaultLimits: { dailyLimit: 10, perCallLimit: 0.50, monthlyLimit: 200 }, tierConfigs: { basic: { dailyLimit: 25, perCallLimit: 1, monthlyLimit: 500 }, professional: { dailyLimit: 100, perCallLimit: 5, monthlyLimit: 2000 }, enterprise: { dailyLimit: 1000, perCallLimit: 20, monthlyLimit: 20000 } } }) // Initialize tenant when they sign up app.post('/api/tenants/:tenantId/initialize', async (req, res) => { const { tenantId } = req.params const { tier } = req.body await agentManager.initializeTenant(tenantId, tier) res.json({ success: true }) }) // Create agent for tenant user app.post('/api/tenants/:tenantId/agents', async (req, res) => { const { tenantId } = req.params const { userId, agentConfig } = req.body const agent = await agentManager.createAgentForTenant(tenantId, userId, agentConfig) res.json(agent) }) ``` ## Custom Webhook Processing ### Complex Event Handling Handle multiple event types with sophisticated business logic: ```typescript import crypto from 'crypto' import { EventEmitter } from 'events' class XpayWebhookProcessor extends EventEmitter { private processors: Map = new Map() constructor(private config: { secret: string retryAttempts: number retryDelay: number }) { super() this.setupEventProcessors() } private setupEventProcessors() { // Agent spending warning this.processors.set('agent.spending.warning', new AgentSpendingProcessor()) // Payment confirmation with business logic this.processors.set('transaction.confirmed', new PaymentConfirmationProcessor()) // Fraud detection this.processors.set('agent.unusual_pattern', new FraudDetectionProcessor()) // Customer lifecycle this.processors.set('customer.first_payment', new CustomerOnboardingProcessor()) } async processWebhook(req: express.Request, res: express.Response) { try { // Verify webhook signature const signature = req.headers['x-xpay-signature'] as string const payload = JSON.stringify(req.body) if (!this.verifySignature(payload, signature)) { return res.status(401).json({ error: 'Invalid signature' }) } const { event, data, timestamp } = req.body // Check for replay attacks if (this.isReplayAttack(timestamp)) { return res.status(400).json({ error: 'Request too old' }) } // Process event with appropriate handler const processor = this.processors.get(event) if (processor) { await processor.process(data, event) this.emit('webhook.processed', { event, data }) } else { console.warn(`Unknown webhook event: ${event}`) } res.status(200).json({ received: true }) } catch (error) { console.error('Webhook processing error:', error) res.status(500).json({ error: 'Processing failed' }) // Queue for retry await this.queueForRetry(req.body) } } private verifySignature(payload: string, signature: string): boolean { const expectedSignature = crypto .createHmac('sha256', this.config.secret) .update(payload) .digest('hex') return crypto.timingSafeEqual( Buffer.from(`sha256=${expectedSignature}`), Buffer.from(signature) ) } private isReplayAttack(timestamp: number): boolean { const now = Date.now() const eventTime = new Date(timestamp).getTime() const maxAge = 5 * 60 * 1000 // 5 minutes return (now - eventTime) > maxAge } private async queueForRetry(webhookData: any) { // Use a queue system like Bull or SQS for retry logic await retryQueue.add('webhook-retry', webhookData, { attempts: this.config.retryAttempts, backoff: { type: 'exponential', settings: { delay: this.config.retryDelay } } }) } } // Event processor implementations class AgentSpendingProcessor implements EventProcessor { async process(data: any, event: string) { const { agentId, percentUsed, dailyLimit, currentSpent } = data if (percentUsed >= 90) { // Critical alert - near limit await this.sendCriticalAlert(agentId, percentUsed) // Auto-pause if configured const agent = await getAgent(agentId) if (agent.autoShutoff?.enabled && percentUsed >= agent.autoShutoff.threshold * 100) { await pauseAgent(agentId) } } else if (percentUsed >= 80) { // Warning alert await this.sendWarningAlert(agentId, percentUsed) } // Update internal metrics await updateAgentMetrics(agentId, { lastSpendingWarning: new Date(), percentUsed, currentSpent }) } private async sendCriticalAlert(agentId: string, percentUsed: number) { await notifications.send({ type: 'critical', channel: 'slack', message: `🚨 Agent ${agentId} at ${percentUsed}% of daily limit`, actions: [ { label: 'Pause Agent', action: 'pause_agent', agentId }, { label: 'Increase Limit', action: 'increase_limit', agentId } ] }) } private async sendWarningAlert(agentId: string, percentUsed: number) { await notifications.send({ type: 'warning', channel: 'email', message: `Agent ${agentId} at ${percentUsed}% of daily limit`, template: 'spending_warning' }) } } class PaymentConfirmationProcessor implements EventProcessor { async process(data: any, event: string) { const { transactionId, agentId, amount, endpointId } = data try { // Update transaction status await updateTransactionStatus(transactionId, 'confirmed') // Update agent spending totals await incrementAgentSpending(agentId, amount) // Update endpoint revenue (if applicable) if (endpointId) { await incrementEndpointRevenue(endpointId, amount) } // Trigger business logic await this.processBusinessLogic(data) // Analytics tracking await analytics.track('payment_confirmed', { agentId, amount, endpointId, transactionId }) } catch (error) { console.error('Payment confirmation processing failed:', error) throw error } } private async processBusinessLogic(data: any) { const { agentId, amount, metadata } = data // Check for milestone achievements const agentStats = await getAgentStats(agentId) if (agentStats.totalSpent >= 100 && !agentStats.milestonePaid) { // Agent reached $100 milestone await this.triggerMilestone(agentId, 100) } // Dynamic limit adjustments based on usage pattern if (agentStats.successRate > 0.95 && agentStats.totalCalls > 50) { await this.considerLimitIncrease(agentId) } } private async triggerMilestone(agentId: string, milestone: number) { await db.query(` UPDATE agents SET milestone_paid = $1, updated_at = NOW() WHERE id = $2 `, [milestone, agentId]) // Send congratulations await notifications.send({ type: 'milestone', message: `🎉 Agent ${agentId} reached $${milestone} in total spending!` }) } private async considerLimitIncrease(agentId: string) { // AI-powered limit optimization based on usage patterns const recommendation = await aiOptimizer.recommendLimits(agentId) if (recommendation.confidence > 0.8) { await notifications.send({ type: 'optimization', message: `Consider increasing limits for agent ${agentId}`, recommendation }) } } } ``` ## Batch Transaction Processing ### High-Volume Payment Processing Handle thousands of transactions efficiently: ```typescript interface BatchProcessor { processBatch(transactions: PendingTransaction[]): Promise } class XpayBatchProcessor implements BatchProcessor { private readonly BATCH_SIZE = 100 private readonly CONCURRENT_BATCHES = 5 constructor( private smartProxy: SmartProxy, private config: { retryAttempts: number retryDelay: number successThreshold: number } ) {} async processBatch(transactions: PendingTransaction[]): Promise { const startTime = Date.now() const results: TransactionResult[] = [] // Split into smaller batches for processing const batches = this.chunkArray(transactions, this.BATCH_SIZE) // Process batches concurrently with limit const batchPromises = batches.map((batch, index) => this.processSingleBatch(batch, index) ) const batchResults = await this.executeWithConcurrencyLimit( batchPromises, this.CONCURRENT_BATCHES ) // Aggregate results for (const batchResult of batchResults) { results.push(...batchResult.results) } const summary = this.calculateSummary(results, startTime) // Handle failed transactions if (summary.failedCount > 0) { await this.handleFailedTransactions( results.filter(r => !r.success) ) } return { summary, results, processedAt: new Date() } } private async processSingleBatch( transactions: PendingTransaction[], batchIndex: number ): Promise<{ results: TransactionResult[] }> { const results: TransactionResult[] = [] console.log(`Processing batch ${batchIndex} with ${transactions.length} transactions`) // Prepare batch request for Xpay const batchRequest = transactions.map(tx => ({ agentId: tx.agentId, url: tx.endpoint, options: { method: 'POST', headers: tx.headers, body: JSON.stringify(tx.payload) }, metadata: { transactionId: tx.id, batchIndex, timestamp: Date.now() } })) try { // Execute batch request const batchResults = await this.smartProxy.batchRequests(batchRequest) // Process individual results for (let i = 0; i < batchResults.length; i++) { const result = batchResults[i] const transaction = transactions[i] if (result.success) { results.push({ transactionId: transaction.id, success: true, cost: result.cost, response: result.response, processingTime: Date.now() - transaction.createdAt }) // Update transaction in database await this.updateTransactionStatus(transaction.id, 'confirmed', result.cost) } else { results.push({ transactionId: transaction.id, success: false, error: result.error, retryable: this.isRetryableError(result.error) }) // Mark for retry if appropriate if (this.isRetryableError(result.error)) { await this.scheduleRetry(transaction) } else { await this.updateTransactionStatus(transaction.id, 'failed', 0) } } } } catch (error) { console.error(`Batch ${batchIndex} failed:`, error) // Mark all transactions as failed with retry for (const transaction of transactions) { results.push({ transactionId: transaction.id, success: false, error: error.message, retryable: true }) await this.scheduleRetry(transaction) } } return { results } } private async executeWithConcurrencyLimit( promises: Promise[], limit: number ): Promise { const results: T[] = [] for (let i = 0; i < promises.length; i += limit) { const batch = promises.slice(i, i + limit) const batchResults = await Promise.allSettled(batch) for (const result of batchResults) { if (result.status === 'fulfilled') { results.push(result.value) } else { console.error('Batch promise failed:', result.reason) throw result.reason } } } return results } private calculateSummary(results: TransactionResult[], startTime: number): BatchSummary { const successCount = results.filter(r => r.success).length const failedCount = results.filter(r => !r.success).length const totalCost = results .filter(r => r.success) .reduce((sum, r) => sum + (r.cost || 0), 0) return { totalTransactions: results.length, successCount, failedCount, successRate: successCount / results.length, totalCost, processingTime: Date.now() - startTime, averageTransactionTime: results .filter(r => r.success && r.processingTime) .reduce((sum, r) => sum + r.processingTime!, 0) / successCount } } private async handleFailedTransactions(failed: TransactionResult[]) { const retryable = failed.filter(f => f.retryable) const permanent = failed.filter(f => !f.retryable) if (retryable.length > 0) { console.log(`Scheduling ${retryable.length} transactions for retry`) // These will be picked up by the retry processor } if (permanent.length > 0) { console.log(`${permanent.length} transactions permanently failed`) // Notify administrators of permanent failures await notifications.send({ type: 'error', message: `${permanent.length} transactions permanently failed`, details: permanent.map(f => ({ id: f.transactionId, error: f.error })) }) } } private chunkArray(array: T[], size: number): T[][] { const chunks: T[][] = [] for (let i = 0; i < array.length; i += size) { chunks.push(array.slice(i, i + size)) } return chunks } private isRetryableError(error: any): boolean { if (!error) return false const retryableCodes = [ 'NETWORK_ERROR', 'TIMEOUT', 'RATE_LIMITED', 'SERVICE_UNAVAILABLE', 'TEMPORARY_FAILURE' ] return retryableCodes.includes(error.code) || (error.status >= 500 && error.status < 600) } private async scheduleRetry(transaction: PendingTransaction) { await retryQueue.add('transaction-retry', transaction, { attempts: this.config.retryAttempts, backoff: { type: 'exponential', settings: { delay: this.config.retryDelay } } }) } private async updateTransactionStatus( transactionId: string, status: string, cost: number ) { await db.query(` UPDATE transactions SET status = $1, amount = $2, updated_at = NOW() WHERE id = $3 `, [status, cost, transactionId]) } } // Usage example const batchProcessor = new XpayBatchProcessor(smartProxy, { retryAttempts: 3, retryDelay: 1000, successThreshold: 0.95 }) // Process pending transactions every minute setInterval(async () => { const pendingTransactions = await getPendingTransactions(1000) // Get up to 1000 pending if (pendingTransactions.length > 0) { const result = await batchProcessor.processBatch(pendingTransactions) console.log(`Batch completed: ${result.summary.successCount}/${result.summary.totalTransactions} successful`) if (result.summary.successRate < 0.95) { // Alert if success rate is too low await notifications.send({ type: 'warning', message: `Low batch success rate: ${result.summary.successRate * 100}%` }) } } }, 60000) // Run every minute ``` ## Custom Analytics and Reporting ### Advanced Analytics Pipeline Build sophisticated analytics for agent performance and revenue optimization: ```typescript class XpayAnalyticsEngine { private metricsCollector: MetricsCollector private dataProcessor: DataProcessor private reportGenerator: ReportGenerator constructor( private smartProxy: SmartProxy, private config: AnalyticsConfig ) { this.metricsCollector = new MetricsCollector(smartProxy) this.dataProcessor = new DataProcessor() this.reportGenerator = new ReportGenerator() } async generateCustomerReport(customerId: string, timeframe: string): Promise { // Collect raw data const rawData = await this.metricsCollector.collectCustomerData(customerId, timeframe) // Process and analyze const processedData = await this.dataProcessor.processCustomerData(rawData) // Generate insights const insights = await this.generateCustomerInsights(processedData) // Create report return this.reportGenerator.generateCustomerReport({ customerId, timeframe, data: processedData, insights }) } async generateRevenueOptimizationReport(endpointId: string): Promise { const data = await this.metricsCollector.collectEndpointData(endpointId, '30d') // Analyze pricing elasticity const elasticity = await this.analyzePriceElasticity(data) // Predict optimal pricing const optimalPricing = await this.predictOptimalPricing(data, elasticity) // A/B testing recommendations const testingRecommendations = await this.generateTestingRecommendations(optimalPricing) return { endpointId, currentMetrics: data.summary, elasticity, optimalPricing, testingRecommendations, projectedIncrease: this.calculateProjectedIncrease(data, optimalPricing) } } async predictAgentBehavior(agentId: string): Promise { // Collect historical data const history = await this.metricsCollector.collectAgentHistory(agentId, '90d') // Machine learning prediction const prediction = await this.mlPredictor.predict({ features: this.extractFeatures(history), model: 'agent_behavior_v2' }) return { agentId, predictions: { nextDaySpending: prediction.nextDaySpending, monthlySpending: prediction.monthlySpending, riskScore: prediction.riskScore, optimalLimits: prediction.optimalLimits }, confidence: prediction.confidence, recommendations: this.generateBehaviorRecommendations(prediction) } } private async generateCustomerInsights(data: ProcessedCustomerData): Promise { const insights: CustomerInsights = { spendingTrends: [], anomalies: [], opportunities: [], risks: [] } // Spending trend analysis if (data.spendingGrowthRate > 0.2) { insights.spendingTrends.push({ type: 'growth', description: `Spending increased by ${(data.spendingGrowthRate * 100).toFixed(1)}%`, impact: 'positive' }) } // Anomaly detection for (const anomaly of data.anomalies) { if (anomaly.severity > 0.7) { insights.anomalies.push({ type: anomaly.type, description: anomaly.description, severity: anomaly.severity, recommendedAction: anomaly.recommendedAction }) } } // Optimization opportunities if (data.efficiencyScore < 0.8) { insights.opportunities.push({ type: 'efficiency', description: 'Agent efficiency could be improved', potentialSavings: data.projectedSavings, actionItems: [ 'Review agent configurations', 'Optimize API call patterns', 'Consider batch processing' ] }) } // Risk assessment if (data.riskScore > 0.6) { insights.risks.push({ type: 'spending', description: 'High risk of budget overrun', probability: data.riskScore, mitigation: [ 'Reduce daily limits', 'Enable auto-shutoff', 'Increase monitoring frequency' ] }) } return insights } private async analyzePriceElasticity(data: EndpointData): Promise { // Analyze how demand changes with price const pricePoints = data.historicalPricing const demandData = data.usageByPrice // Calculate elasticity coefficient const elasticity = this.calculateElasticity(pricePoints, demandData) return { coefficient: elasticity, interpretation: this.interpretElasticity(elasticity), confidenceInterval: this.calculateConfidenceInterval(pricePoints, demandData), recommendations: this.generateElasticityRecommendations(elasticity) } } private async predictOptimalPricing( data: EndpointData, elasticity: PriceElasticity ): Promise { // Use revenue maximization algorithm const revenueFunction = (price: number) => { const demand = this.predictDemand(price, elasticity) return price * demand } // Find optimal price point const optimalPrice = this.findOptimalPrice(revenueFunction, data.currentPrice) return { currentPrice: data.currentPrice, optimalPrice, projectedRevenue: revenueFunction(optimalPrice), confidence: this.calculatePricingConfidence(data, elasticity), priceRange: { min: optimalPrice * 0.9, max: optimalPrice * 1.1 } } } // Helper methods for calculations private calculateElasticity(pricePoints: number[], demandData: number[]): number { // Simplified elasticity calculation const priceChanges = pricePoints.slice(1).map((price, i) => (price - pricePoints[i]) / pricePoints[i] ) const demandChanges = demandData.slice(1).map((demand, i) => (demand - demandData[i]) / demandData[i] ) // Calculate average elasticity const elasticities = demandChanges.map((demandChange, i) => demandChange / priceChanges[i] ) return elasticities.reduce((sum, e) => sum + e, 0) / elasticities.length } private interpretElasticity(elasticity: number): string { if (elasticity < -1) return 'elastic' if (elasticity > -1 && elasticity < 0) return 'inelastic' return 'unit_elastic' } private findOptimalPrice(revenueFunction: (price: number) => number, currentPrice: number): number { // Simple optimization using golden section search let a = currentPrice * 0.5 let b = currentPrice * 2 const phi = (1 + Math.sqrt(5)) / 2 // Golden section search iterations for (let i = 0; i < 20; i++) { const c = b - (b - a) / phi const d = a + (b - a) / phi if (revenueFunction(c) > revenueFunction(d)) { b = d } else { a = c } } return (a + b) / 2 } } // Usage example const analytics = new XpayAnalyticsEngine(smartProxy, { enableMachineLearning: true, dataRetentionDays: 365, reportingFrequency: 'daily' }) // Generate daily reports cron.schedule('0 6 * * *', async () => { const customers = await getActiveCustomers() for (const customer of customers) { const report = await analytics.generateCustomerReport(customer.id, '24h') if (report.insights.risks.length > 0) { await notifications.send({ type: 'risk_alert', customerId: customer.id, risks: report.insights.risks }) } } }) // Weekly optimization reports cron.schedule('0 9 * * 1', async () => { const endpoints = await getActiveEndpoints() for (const endpoint of endpoints) { const optimization = await analytics.generateRevenueOptimizationReport(endpoint.id) if (optimization.projectedIncrease > 0.1) { await notifications.send({ type: 'optimization_opportunity', endpointId: endpoint.id, opportunity: optimization }) } } }) ``` ## Integration Testing Patterns ### Comprehensive Testing Strategy ```typescript import { describe, it, beforeEach, afterEach, expect } from '@jest/globals' import { SmartProxy } from '@xpaysh/agent-kit' describe('Xpay Integration Tests', () => { let smartProxy: SmartProxy let testAgent: Agent beforeEach(async () => { // Initialize test smart proxy smartProxy = new SmartProxy({ endpoint: process.env.XPAY_TEST_ENDPOINT!, apiKey: process.env.XPAY_TEST_API_KEY!, // Test-specific configuration timeout: 5000, retries: 1 }) // Create test agent testAgent = await smartProxy.createAgent({ id: `test-agent-${Date.now()}`, name: 'Test Agent', walletAddress: process.env.TEST_WALLET_ADDRESS!, dailyLimit: 10, perCallLimit: 1 }) }) afterEach(async () => { // Cleanup if (testAgent) { await smartProxy.deleteAgent(testAgent.id) } }) describe('Agent Lifecycle', () => { it('should create agent with proper configuration', async () => { expect(testAgent.id).toBeTruthy() expect(testAgent.dailyLimit).toBe(10) expect(testAgent.status).toBe('active') }) it('should update agent limits', async () => { const updated = await smartProxy.updateAgent(testAgent.id, { dailyLimit: 20, perCallLimit: 2 }) expect(updated.dailyLimit).toBe(20) expect(updated.perCallLimit).toBe(2) }) it('should pause and resume agent', async () => { await smartProxy.pauseAgent(testAgent.id) let agent = await smartProxy.getAgent(testAgent.id) expect(agent.status).toBe('paused') await smartProxy.resumeAgent(testAgent.id) agent = await smartProxy.getAgent(testAgent.id) expect(agent.status).toBe('active') }) }) describe('Payment Processing', () => { it('should process successful payment', async () => { const response = await smartProxy.protectedFetch('https://api.example.com/test', { agentId: testAgent.id, method: 'POST', body: JSON.stringify({ test: true }) }) expect(response.ok).toBe(true) // Verify agent spending updated const updatedAgent = await smartProxy.getAgent(testAgent.id) expect(updatedAgent.totalSpent).toBeGreaterThan(0) expect(updatedAgent.totalCalls).toBe(1) }) it('should reject payment when limit exceeded', async () => { // Set very low limit await smartProxy.updateAgent(testAgent.id, { perCallLimit: 0.001 }) await expect( smartProxy.protectedFetch('https://api.example.com/expensive', { agentId: testAgent.id, method: 'POST' }) ).rejects.toThrow('Spending limit exceeded') }) it('should handle batch requests correctly', async () => { const requests = Array.from({ length: 5 }, (_, i) => ({ agentId: testAgent.id, url: `https://api.example.com/test/${i}`, options: { method: 'GET' } })) const results = await smartProxy.batchRequests(requests) expect(results).toHaveLength(5) expect(results.every(r => r.success)).toBe(true) // Verify total spending const updatedAgent = await smartProxy.getAgent(testAgent.id) expect(updatedAgent.totalCalls).toBe(5) }) }) describe('Error Handling', () => { it('should handle network timeouts gracefully', async () => { // Mock timeout scenario jest.setTimeout(10000) await expect( smartProxy.protectedFetch('https://httpstat.us/200?sleep=8000', { agentId: testAgent.id, timeout: 2000 }) ).rejects.toThrow('timeout') }) it('should retry failed requests', async () => { const retrySmartProxy = new SmartProxy({ endpoint: process.env.XPAY_TEST_ENDPOINT!, apiKey: process.env.XPAY_TEST_API_KEY!, retries: 3, retryDelay: 100 }) // Mock intermittent failure let attempts = 0 const mockFetch = jest.fn().mockImplementation(() => { attempts++ if (attempts < 3) { throw new Error('Temporary failure') } return Promise.resolve(new Response('Success')) }) // Test retry mechanism const response = await retrySmartProxy.protectedFetch('https://api.example.com/retry', { agentId: testAgent.id }) expect(response.ok).toBe(true) expect(attempts).toBe(3) }) }) describe('Analytics and Monitoring', () => { it('should track spending analytics correctly', async () => { // Make several test requests for (let i = 0; i < 3; i++) { await smartProxy.protectedFetch('https://api.example.com/analytics', { agentId: testAgent.id }) } const analytics = await smartProxy.getSpendingAnalytics({ agentIds: [testAgent.id], timeframe: '1h' }) expect(analytics.totalCalls).toBe(3) expect(analytics.totalSpent).toBeGreaterThan(0) expect(analytics.breakdown).toHaveLength(1) }) it('should retrieve transaction history', async () => { // Make a test transaction await smartProxy.protectedFetch('https://api.example.com/history', { agentId: testAgent.id }) const history = await smartProxy.getTransactionHistory({ agentIds: [testAgent.id], limit: 10 }) expect(history.transactions).toHaveLength(1) expect(history.transactions[0].agentId).toBe(testAgent.id) expect(history.transactions[0].status).toBe('confirmed') }) }) }) // Load testing utilities export class LoadTestRunner { constructor(private smartProxy: SmartProxy) {} async runLoadTest(config: LoadTestConfig): Promise { const startTime = Date.now() const results: RequestResult[] = [] // Create test agents const agents = await Promise.all( Array.from({ length: config.agentCount }, (_, i) => this.smartProxy.createAgent({ id: `load-test-agent-${i}`, name: `Load Test Agent ${i}`, walletAddress: process.env.TEST_WALLET_ADDRESS!, dailyLimit: 100, perCallLimit: 5 }) ) ) try { // Generate load const promises: Promise[] = [] for (let i = 0; i < config.totalRequests; i++) { const agent = agents[i % agents.length] const delay = (i / config.requestsPerSecond) * 1000 promises.push( new Promise(resolve => { setTimeout(async () => { const requestStart = Date.now() try { await this.smartProxy.protectedFetch(config.targetUrl, { agentId: agent.id }) resolve({ success: true, duration: Date.now() - requestStart, agentId: agent.id }) } catch (error) { resolve({ success: false, duration: Date.now() - requestStart, agentId: agent.id, error: error.message }) } }, delay) }) ) } const requestResults = await Promise.all(promises) results.push(...requestResults) } finally { // Cleanup test agents await Promise.all( agents.map(agent => this.smartProxy.deleteAgent(agent.id)) ) } return this.analyzeResults(results, Date.now() - startTime) } private analyzeResults(results: RequestResult[], totalTime: number): LoadTestResults { const successful = results.filter(r => r.success) const failed = results.filter(r => !r.success) const durations = successful.map(r => r.duration) durations.sort((a, b) => a - b) return { totalRequests: results.length, successfulRequests: successful.length, failedRequests: failed.length, successRate: successful.length / results.length, totalTime, requestsPerSecond: results.length / (totalTime / 1000), averageResponseTime: durations.reduce((sum, d) => sum + d, 0) / durations.length, medianResponseTime: durations[Math.floor(durations.length / 2)], p95ResponseTime: durations[Math.floor(durations.length * 0.95)], p99ResponseTime: durations[Math.floor(durations.length * 0.99)], errors: failed.reduce((acc, f) => { acc[f.error!] = (acc[f.error!] || 0) + 1 return acc }, {} as Record) } } } ``` These advanced integration patterns provide production-ready solutions for complex Xpay deployments. They cover multi-tenancy, webhook processing, batch operations, analytics, and comprehensive testing strategies that scale with your application needs. ================================================================================ # Page: /en/developer-resources/sdk-reference # Source: src/content/en/developer-resources/sdk-reference.mdx ================================================================================ # SDK Reference Complete reference for the Xpay Agent Kit SDK, including TypeScript interfaces, error handling, and advanced configuration options. ## Installation ```bash npm2yarn npm install @xpaysh/agent-kit ``` ## Core Interfaces ### Agent Interface ```typescript interface Agent { id: string // Unique agent identifier name: string // Human-readable agent name description?: string // Optional agent description userId: string // Owner user ID customerId: string // Customer/organization ID walletAddress: string // Non-custodial wallet address kmsKeyId: string // KMS key for wallet management nonce: number // Current transaction nonce dailyLimit: number // Daily spending limit in USDC perCallLimit: number // Per-request spending limit in USDC monthlyLimit?: number // Optional monthly limit in USDC status: AgentStatus // Current agent status totalSpent: number // Total amount spent (USDC) totalCalls: number // Total API calls made createdAt: number // Creation timestamp updatedAt: number // Last update timestamp } type AgentStatus = 'active' | 'paused' | 'suspended' | 'deleted' ``` ### Transaction Interface ```typescript interface Transaction { id: string // Unique transaction ID agentId: string // Agent that made the transaction endpointId?: string // Endpoint ID (for paywall transactions) amount: number // Transaction amount in USDC currency: 'USDC' // Currency (always USDC) status: TransactionStatus // Transaction status type: TransactionType // Transaction type metadata?: Record // Additional transaction data createdAt: number // Transaction timestamp hash?: string // Blockchain transaction hash gasUsed?: number // Gas used for transaction gasPrice?: string // Gas price in wei } type TransactionStatus = 'pending' | 'confirmed' | 'failed' | 'cancelled' type TransactionType = 'api_call' | 'subscription' | 'refund' | 'adjustment' ``` ### Endpoint Interface ```typescript interface Endpoint { id: string // Unique endpoint identifier name: string // Endpoint display name description?: string // Optional description url: string // Endpoint URL method: HttpMethod // HTTP method pricing: EndpointPricing // Pricing configuration status: EndpointStatus // Current status totalCalls: number // Total calls to this endpoint totalRevenue: number // Total revenue generated (USDC) createdAt: number // Creation timestamp updatedAt: number // Last update timestamp } type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' type EndpointStatus = 'active' | 'paused' | 'maintenance' | 'deprecated' interface EndpointPricing { model: 'per_request' | 'per_token' | 'per_minute' | 'tiered' basePrice: number // Base price in USDC currency: 'USDC' tiers?: PricingTier[] // For tiered pricing } interface PricingTier { from: number // Range start to?: number // Range end (undefined for last tier) price: number // Price for this tier } ``` ## SmartProxy Class ### Constructor ```typescript import { SmartProxy } from '@xpaysh/agent-kit' const smartProxy = new SmartProxy({ endpoint: string // Smart Proxy endpoint URL apiKey: string // Your Xpay API key timeout?: number // Request timeout (default: 30000ms) retries?: number // Number of retries (default: 3) region?: string // Preferred region (default: auto) }) ``` ### Agent Management Methods #### createAgent() ```typescript await smartProxy.createAgent(config: AgentConfig): Promise interface AgentConfig { id: string name: string description?: string walletAddress: string dailyLimit: number perCallLimit: number monthlyLimit?: number allowedAPIs?: string[] // Array of allowed API domains status?: AgentStatus emergencyContact?: string businessHours?: BusinessHours rateLimiting?: RateLimiting autoShutoff?: AutoShutoff fallbackChain?: FallbackConfig[] } interface BusinessHours { enabled: boolean timezone: string // IANA timezone identifier schedule: string // Format: "HH:MM-HH:MM" weekdays?: number[] // 0-6, Sunday = 0 } interface RateLimiting { maxConcurrentRequests: number requestsPerMinute: number requestsPerHour?: number } interface AutoShutoff { enabled: boolean threshold: number // 0.0 to 1.0 (percentage) action: 'pause' | 'notify' | 'both' } interface FallbackConfig { provider: string model?: string maxCost: number timeout?: number } ``` #### updateAgent() ```typescript await smartProxy.updateAgent( agentId: string, updates: Partial ): Promise ``` #### getAgent() ```typescript await smartProxy.getAgent(agentId: string): Promise ``` #### listAgents() ```typescript await smartProxy.listAgents(options?: { limit?: number // Max results (default: 100) offset?: number // Pagination offset status?: AgentStatus // Filter by status search?: string // Search by name/description }): Promise<{ agents: Agent[] total: number hasMore: boolean }> ``` #### pauseAgent() / resumeAgent() ```typescript await smartProxy.pauseAgent(agentId: string): Promise await smartProxy.resumeAgent(agentId: string): Promise ``` #### deleteAgent() ```typescript await smartProxy.deleteAgent(agentId: string): Promise ``` ### Request Methods #### protectedFetch() ```typescript await smartProxy.protectedFetch( urlOrRequest: string | Request, options: RequestOptions & { agentId: string // Required: Agent making the request maxCost?: number // Override per-request limit priority?: 'low' | 'normal' | 'high' metadata?: Record } ): Promise ``` #### batchRequests() ```typescript await smartProxy.batchRequests(requests: Array<{ agentId: string url: string options: RequestInit metadata?: Record }>): Promise> ``` ### Monitoring Methods #### getSpendingAnalytics() ```typescript await smartProxy.getSpendingAnalytics(options: { agentIds?: string[] // Specific agents (default: all) timeframe: '1h' | '24h' | '7d' | '30d' | 'custom' startDate?: Date // For custom timeframe endDate?: Date // For custom timeframe groupBy?: 'agent' | 'api' | 'hour' | 'day' includeMetadata?: boolean }): Promise interface SpendingAnalytics { totalSpent: number totalCalls: number averageCostPerCall: number breakdown: Array<{ key: string // Agent ID, API domain, or time period spent: number calls: number percentage: number }> trends: Array<{ timestamp: number spent: number calls: number }> } ``` #### getTransactionHistory() ```typescript await smartProxy.getTransactionHistory(options: { agentIds?: string[] limit?: number offset?: number status?: TransactionStatus startDate?: Date endDate?: Date }): Promise<{ transactions: Transaction[] total: number hasMore: boolean }> ``` ### Webhook Configuration #### configureWebhooks() ```typescript await smartProxy.configureWebhooks(config: { endpoint: string // Your webhook URL events: WebhookEvent[] // Events to subscribe to secret: string // Webhook signing secret retries?: number // Retry attempts (default: 3) timeout?: number // Webhook timeout (default: 10000ms) }): Promise type WebhookEvent = | 'agent.created' | 'agent.updated' | 'agent.paused' | 'agent.resumed' | 'agent.deleted' | 'agent.spending.warning' | 'agent.spending.exceeded' | 'agent.request.failed' | 'agent.unusual_pattern' | 'transaction.created' | 'transaction.confirmed' | 'transaction.failed' ``` ## XpayPaywall Class ### Constructor ```typescript import { XpayPaywall } from '@xpaysh/agent-kit' const paywall = new XpayPaywall({ receivingWallet: string // Your wallet address facilitatorUrl?: string // x402 facilitator URL defaultPrice?: number // Default price per request apiKey?: string // Xpay API key for analytics }) ``` ### Middleware #### Express.js Middleware ```typescript import express from 'express' const app = express() // Apply paywall to specific route app.get('/api/premium', paywall.middleware({ price: 0.10, // $0.10 per request description: 'Premium API access', metadata: { tier: 'premium' } }), (req, res) => { // This code only runs after successful payment res.json({ data: 'Premium content' }) } ) // Apply paywall to all routes app.use('/api/paid', paywall.middleware({ price: 0.05 })) ``` #### Manual Payment Verification ```typescript const isPaymentValid = await paywall.verifyPayment(req.headers, { price: 0.10, tolerance: 0.001 // Allow small rounding differences }) if (!isPaymentValid) { return res.status(402).json({ error: 'Payment required', paymentDetails: paywall.getPaymentDetails(0.10) }) } ``` ### Endpoint Management #### createEndpoint() ```typescript await paywall.createEndpoint({ name: string url: string method: HttpMethod pricing: EndpointPricing description?: string tags?: string[] rateLimiting?: { requestsPerMinute: number requestsPerHour?: number } }): Promise ``` #### updateEndpoint() ```typescript await paywall.updateEndpoint( endpointId: string, updates: Partial ): Promise ``` ## Error Handling ### Error Types ```typescript import { SpendingLimitError, InsufficientFundsError, AgentNotFoundError, PaymentRequiredError, RateLimitError } from '@xpaysh/agent-kit' // Spending limit exceeded class SpendingLimitError extends Error { limitType: 'daily' | 'monthly' | 'per_request' currentSpent: number limit: number resetTime: Date } // Insufficient funds in wallet class InsufficientFundsError extends Error { required: number available: number walletAddress: string } // Agent not found or access denied class AgentNotFoundError extends Error { agentId: string } // Payment required for paywall class PaymentRequiredError extends Error { price: number paymentDetails: { walletAddress: string amount: string currency: 'USDC' facilitatorUrl: string } } // Rate limit exceeded class RateLimitError extends Error { resetTime: Date limit: number remaining: number } ``` ### Error Handling Patterns ```typescript import { SmartProxy, SpendingLimitError, RateLimitError } from '@xpaysh/agent-kit' async function handleXpayRequest(agentId: string, requestFn: () => Promise) { try { return await smartProxy.protectedFetch(requestFn, { agentId }) } catch (error) { if (error instanceof SpendingLimitError) { // Handle spending limits logger.warn(`Agent ${agentId} hit ${error.limitType} limit`) if (error.limitType === 'daily') { // Schedule retry for tomorrow await scheduleRetry(agentId, requestFn, error.resetTime) } else if (error.limitType === 'per_request') { // Try with smaller/cheaper request return await fallbackToSmallerModel(agentId, requestFn) } } else if (error instanceof RateLimitError) { // Handle rate limiting const waitTime = error.resetTime.getTime() - Date.now() await new Promise(resolve => setTimeout(resolve, waitTime)) return handleXpayRequest(agentId, requestFn) // Retry } else if (error instanceof InsufficientFundsError) { // Handle insufficient funds await notifyFundsNeeded(error.walletAddress, error.required) throw new Error('Agent wallet needs funding') } throw error // Re-throw unknown errors } } ``` ## Advanced Configuration ### Custom HTTP Client ```typescript import axios from 'axios' const smartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-abc123.xpay.sh', apiKey: 'xpay_fw_...', httpClient: axios.create({ timeout: 45000, headers: { 'User-Agent': 'MyApp/1.0' } }) }) ``` ### Connection Pooling ```typescript const smartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-abc123.xpay.sh', apiKey: 'xpay_fw_...', pooling: { maxSockets: 50, keepAlive: true, keepAliveMsecs: 30000 } }) ``` ### Custom Retry Logic ```typescript const smartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-abc123.xpay.sh', apiKey: 'xpay_fw_...', retryConfig: { retries: 5, factor: 2, minTimeout: 1000, maxTimeout: 30000, retryCondition: (error) => { return error.code === 'NETWORK_ERROR' || error.status === 503 } } }) ``` ## TypeScript Support The SDK is written in TypeScript and provides complete type definitions. Enable strict type checking for the best developer experience: ```typescript // tsconfig.json { "compilerOptions": { "strict": true, "noImplicitAny": true, "strictNullChecks": true } } ``` All SDK methods are fully typed and will provide autocomplete and type checking in your IDE. ## Browser Support The SDK works in both Node.js and modern browsers. For browser usage, ensure you handle CORS appropriately: ```typescript // Browser usage import { XpayPaywall } from '@xpaysh/agent-kit/browser' const paywall = new XpayPaywall({ receivingWallet: '0x...', // Browser-specific configuration corsOrigins: ['https://yourapp.com'] }) ``` --- ## OpenAPI Specification Download the [OpenAPI spec](/openapi.json) for the xpay Hub API. You can use it with API clients like Postman, code generators, or feed it to an AI assistant for integration help. --- Need help with integration? Check our [troubleshooting guide](/developer-resources/troubleshooting) or join our [Discord community](https://discord.gg/vukXDGT7n5). ================================================================================ # Page: /en/developer-resources/troubleshooting # Source: src/content/en/developer-resources/troubleshooting.mdx ================================================================================ # Troubleshooting Guide Common issues and solutions for Xpay integrations, with step-by-step debugging instructions. import { Callout } from 'nextra/components' **Quick Support**: For urgent issues, join our [Discord](https://discord.gg/vukXDGT7n5) or email support@xpay.sh with your error details. ## Common Issues ### Payment Verification Failures #### Issue: "Payment verification failed" errors **Symptoms:** - 402 Payment Required responses when payment was made - `PaymentRequiredError` exceptions in your application - Valid payments being rejected **Common Causes:** 1. **Incorrect payment amount** ```bash Expected: 0.10 USDC Received: 0.099 USDC (missing gas/precision) ``` 2. **Stale payment timestamps** ```bash Payment timestamp: 2024-01-01T10:00:00Z Current time: 2024-01-01T10:06:00Z Max age: 300 seconds (5 minutes) - EXPIRED ``` 3. **Wrong facilitator URL** ```bash Expected: https://facilitator.xpay.sh Used: https://facilitator.ethereum.org ``` **Solutions:** ```typescript // 1. Add payment tolerance for precision issues const paywall = new XpayPaywall({ receivingWallet: '0x...', verification: { tolerance: 0.001, // Allow 0.1% variance maxAge: 600 // Extend to 10 minutes if needed } }) // 2. Debug payment verification async function debugPaymentVerification(req: Request, expectedPrice: number) { const headers = req.headers console.log('Payment Headers:', { 'x-payment-amount': headers['x-payment-amount'], 'x-payment-hash': headers['x-payment-hash'], 'x-payment-timestamp': headers['x-payment-timestamp'], 'x-facilitator-url': headers['x-facilitator-url'] }) try { const verification = await paywall.verifyPayment(headers, { price: expectedPrice, tolerance: 0.001, maxAge: 600 }) console.log('Verification Result:', verification) return verification } catch (error) { console.error('Verification Error:', { error: error.message, expectedPrice, receivedAmount: headers['x-payment-amount'], timeDiff: Date.now() - new Date(headers['x-payment-timestamp']).getTime() }) throw error } } // 3. Implement retry logic for temporary failures async function verifyWithRetry(headers: any, options: any, retries = 3) { for (let i = 0; i < retries; i++) { try { return await paywall.verifyPayment(headers, options) } catch (error) { if (i === retries - 1 || !isRetryableError(error)) { throw error } console.log(`Payment verification failed, retrying... (${i + 1}/${retries})`) await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))) } } } function isRetryableError(error: any): boolean { return [ 'NETWORK_ERROR', 'TIMEOUT', 'SERVICE_UNAVAILABLE' ].includes(error.code) } ``` ### Agent Spending Limit Issues #### Issue: Agents hitting limits unexpectedly **Symptoms:** - `SpendingLimitError` exceptions - Agents pausing automatically - API calls being rejected despite sufficient budget **Debugging Steps:** ```typescript // 1. Check current agent status and spending async function debugAgentSpending(agentId: string) { const agent = await smartProxy.getAgent(agentId) console.log('Agent Status:', { id: agent.id, status: agent.status, totalSpent: agent.totalSpent, totalCalls: agent.totalCalls, limits: { daily: agent.dailyLimit, perCall: agent.perCallLimit, monthly: agent.monthlyLimit }, utilization: { daily: (agent.totalSpent / agent.dailyLimit) * 100, monthly: agent.monthlyLimit ? (agent.totalSpent / agent.monthlyLimit) * 100 : null } }) // Check recent transactions const transactions = await smartProxy.getTransactionHistory({ agentIds: [agentId], limit: 10 }) console.log('Recent Transactions:', transactions.transactions.map(tx => ({ id: tx.id, amount: tx.amount, status: tx.status, createdAt: new Date(tx.createdAt) }))) return { agent, transactions } } // 2. Reset daily limits if needed async function resetDailySpending(agentId: string) { try { await smartProxy.resetDailySpending(agentId) console.log(`Daily spending reset for agent ${agentId}`) } catch (error) { console.error('Failed to reset daily spending:', error) } } // 3. Implement graceful limit handling async function makeRequestWithLimitHandling(agentId: string, apiCall: () => Promise) { try { return await smartProxy.protectedFetch(apiCall, { agentId }) } catch (error) { if (error instanceof SpendingLimitError) { switch (error.limitType) { case 'daily': console.log(`Agent ${agentId} hit daily limit. Next reset: ${error.resetTime}`) // Queue for tomorrow or increase limit await handleDailyLimitExceeded(agentId, error) break case 'per_request': console.log(`Request too expensive for agent ${agentId}`) // Try with smaller request or increase per-call limit await handlePerRequestLimitExceeded(agentId, error) break case 'monthly': console.log(`Agent ${agentId} hit monthly limit`) // Pause agent and notify administrators await handleMonthlyLimitExceeded(agentId, error) break } } throw error } } ``` ### Connection and Network Issues #### Issue: Timeouts and connection errors **Symptoms:** - Request timeouts - "Connection refused" errors - Intermittent failures **Solutions:** ```typescript // 1. Configure robust timeout and retry settings const smartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-abc123.xpay.sh', apiKey: 'xpay_fw_...', // Network configuration timeout: 30000, // 30 second timeout retries: 3, // Retry up to 3 times retryDelay: 1000, // Start with 1 second delay // Connection pooling keepAlive: true, maxSockets: 50, // Custom retry logic retryCondition: (error) => { return error.code === 'TIMEOUT' || error.code === 'ECONNRESET' || (error.response && error.response.status >= 500) } }) // 2. Implement circuit breaker pattern class CircuitBreaker { private failures = 0 private lastFailTime = 0 private state: 'closed' | 'open' | 'half-open' = 'closed' constructor( private threshold = 5, private timeout = 60000, private monitorPeriod = 120000 ) {} async execute(operation: () => Promise): Promise { if (this.state === 'open') { if (Date.now() - this.lastFailTime >= this.timeout) { this.state = 'half-open' } else { throw new Error('Circuit breaker is open') } } try { const result = await operation() this.onSuccess() return result } catch (error) { this.onFailure() throw error } } private onSuccess() { this.failures = 0 this.state = 'closed' } private onFailure() { this.failures++ this.lastFailTime = Date.now() if (this.failures >= this.threshold) { this.state = 'open' } } } // 3. Add comprehensive error handling async function robustApiCall(agentId: string, url: string, options: any) { const circuitBreaker = new CircuitBreaker() return await circuitBreaker.execute(async () => { try { return await smartProxy.protectedFetch(url, { ...options, agentId, timeout: 30000 }) } catch (error) { // Enhanced error logging console.error('API call failed:', { agentId, url, error: error.message, code: error.code, status: error.status, timestamp: new Date().toISOString() }) // Specific error handling if (error.code === 'TIMEOUT') { throw new Error('Request timed out - try reducing payload size or increasing timeout') } else if (error.code === 'ECONNRESET') { throw new Error('Connection reset - check network connectivity') } else if (error.status === 503) { throw new Error('Service unavailable - Xpay service may be temporarily down') } throw error } }) } ``` ### Authentication Issues #### Issue: API key and authentication errors **Symptoms:** - 401 Unauthorized responses - "Invalid API key" errors - Intermittent authentication failures **Debugging:** ```typescript // 1. Validate API key format and permissions function validateApiKey(apiKey: string) { if (!apiKey) { throw new Error('API key is required') } if (!apiKey.startsWith('xpay_')) { throw new Error('Invalid API key format - must start with "xpay_"') } if (apiKey.includes('test_') && process.env.NODE_ENV === 'production') { throw new Error('Test API key used in production environment') } if (apiKey.includes('live_') && process.env.NODE_ENV !== 'production') { console.warn('Live API key used in non-production environment') } } // 2. Test API key connectivity async function testApiKeyConnectivity(apiKey: string) { try { const smartProxy = new SmartProxy({ endpoint: process.env.XPAY_SMART_PROXY_ENDPOINT!, apiKey }) // Make a simple API call to test connectivity await smartProxy.ping() console.log('✅ API key is valid and service is reachable') return true } catch (error) { console.error('❌ API key test failed:', error.message) if (error.status === 401) { console.log('🔑 Check your API key in the Xpay dashboard') } else if (error.status === 403) { console.log('🚫 API key lacks required permissions') } else if (error.code === 'ENOTFOUND') { console.log('🌐 Check your smart proxy endpoint URL') } return false } } // 3. Implement API key rotation class ApiKeyManager { private currentKey: string private backupKey?: string constructor(primaryKey: string, backupKey?: string) { this.currentKey = primaryKey this.backupKey = backupKey } async executeWithFallback(operation: (apiKey: string) => Promise): Promise { try { return await operation(this.currentKey) } catch (error) { if (error.status === 401 && this.backupKey) { console.log('Primary API key failed, trying backup key') try { const result = await operation(this.backupKey) // Swap keys if backup works this.currentKey = this.backupKey this.backupKey = undefined console.log('Backup API key worked, keys rotated') return result } catch (backupError) { console.error('Both API keys failed') } } throw error } } } ``` ### Performance Issues #### Issue: Slow response times and high latency **Symptoms:** - Requests taking longer than expected - Timeout errors under load - Poor application performance **Performance Optimization:** ```typescript // 1. Implement request caching class PerformanceOptimizedSmartProxy { private cache = new Map() private smartProxy: SmartProxy constructor(config: any) { this.smartProxy = new SmartProxy(config) } async cachedProtectedFetch( url: string, options: any, cacheOptions?: { ttl?: number, key?: string } ) { const cacheKey = cacheOptions?.key || this.generateCacheKey(url, options) const cached = this.cache.get(cacheKey) if (cached && Date.now() - cached.timestamp < (cacheOptions?.ttl || 300000)) { console.log(`Cache hit for ${cacheKey}`) return cached.response } const response = await this.smartProxy.protectedFetch(url, options) // Cache successful responses if (response.ok) { this.cache.set(cacheKey, { response: response.clone(), timestamp: Date.now() }) } return response } private generateCacheKey(url: string, options: any): string { return `${url}:${JSON.stringify(options)}` } } // 2. Connection pooling and keep-alive const httpAgent = new require('https').Agent({ keepAlive: true, keepAliveMsecs: 30000, maxSockets: 50, maxFreeSockets: 10, timeout: 30000 }) const optimizedSmartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-abc123.xpay.sh', apiKey: 'xpay_fw_...', httpAgent }) // 3. Request batching for multiple operations class BatchingSmartProxy { private pendingRequests: Array<{ request: any resolve: (value: any) => void reject: (error: any) => void }> = [] private batchTimer?: NodeJS.Timeout constructor( private smartProxy: SmartProxy, private batchSize = 10, private batchDelay = 100 ) {} async protectedFetch(url: string, options: any): Promise { return new Promise((resolve, reject) => { this.pendingRequests.push({ request: { url, options }, resolve, reject }) if (this.pendingRequests.length >= this.batchSize) { this.processBatch() } else if (!this.batchTimer) { this.batchTimer = setTimeout(() => this.processBatch(), this.batchDelay) } }) } private async processBatch() { if (this.batchTimer) { clearTimeout(this.batchTimer) this.batchTimer = undefined } const batch = this.pendingRequests.splice(0, this.batchSize) try { const batchRequests = batch.map(item => ({ agentId: item.request.options.agentId, url: item.request.url, options: item.request.options })) const results = await this.smartProxy.batchRequests(batchRequests) batch.forEach((item, index) => { const result = results[index] if (result.success) { item.resolve(result.response) } else { item.reject(result.error) } }) } catch (error) { batch.forEach(item => item.reject(error)) } } } // 4. Performance monitoring class PerformanceMonitor { private metrics: Map = new Map() async monitoredRequest(name: string, operation: () => Promise) { const start = performance.now() try { const result = await operation() const duration = performance.now() - start this.recordMetric(name, duration) if (duration > 5000) { console.warn(`Slow request detected: ${name} took ${duration}ms`) } return result } catch (error) { const duration = performance.now() - start console.error(`Failed request: ${name} failed after ${duration}ms`, error) throw error } } private recordMetric(name: string, duration: number) { if (!this.metrics.has(name)) { this.metrics.set(name, []) } const durations = this.metrics.get(name)! durations.push(duration) // Keep only last 100 measurements if (durations.length > 100) { durations.shift() } } getPerformanceReport(): Record { const report: Record = {} for (const [name, durations] of this.metrics) { const avg = durations.reduce((sum, d) => sum + d, 0) / durations.length const max = Math.max(...durations) const min = Math.min(...durations) report[name] = { average: avg, max, min, count: durations.length } } return report } } ``` ## Frequently Asked Questions ### General Questions **Q: What is the difference between test and live API keys?** A: Test API keys (prefixed with `xpay_test_`) work with testnet USDC and don't process real payments. Live API keys (prefixed with `xpay_live_`) process real mainnet USDC transactions. Always use test keys during development. **Q: How long do payments take to confirm?** A: Most payments confirm within 2-5 seconds on Base network. However, during network congestion, it may take up to 30 seconds. Always implement appropriate timeout handling. **Q: Can I use Xpay with other cryptocurrencies besides USDC?** A: Currently, Xpay only supports USDC on Base network. Support for other stablecoins is planned for future releases. ### Agent Management **Q: What happens if an agent's wallet runs out of funds?** A: The agent will receive `InsufficientFundsError` exceptions. Implement monitoring to track wallet balances and top up before they run empty: ```typescript async function checkWalletBalance(agentId: string) { const agent = await smartProxy.getAgent(agentId) const balance = await getWalletBalance(agent.walletAddress) if (balance < agent.dailyLimit * 0.1) { // 10% buffer await notifications.send({ type: 'low_balance', message: `Agent ${agentId} wallet balance is low: ${balance} USDC`, agentId, balance }) } } ``` **Q: How do I handle agents that are consistently hitting limits?** A: Analyze spending patterns and either: 1. Increase limits if the usage is legitimate 2. Optimize the agent's API usage patterns 3. Implement dynamic limit adjustments based on performance ```typescript async function analyzeLimitHits(agentId: string) { const analytics = await smartProxy.getSpendingAnalytics({ agentIds: [agentId], timeframe: '7d' }) const hitRate = analytics.limitHits / analytics.totalCalls if (hitRate > 0.1) { // More than 10% of calls hit limits console.log(`Agent ${agentId} frequently hits limits - consider optimization`) return { recommendation: 'optimize_usage', hitRate, suggestedActions: [ 'Review API call patterns', 'Implement caching', 'Increase limits if usage is legitimate' ] } } } ``` ### Payment Processing **Q: Why am I getting "Payment amount mismatch" errors?** A: This usually happens due to: 1. Gas fee calculations affecting the final amount 2. Network precision differences 3. Exchange rate fluctuations Always include tolerance in payment verification: ```typescript const verification = await paywall.verifyPayment(headers, { price: 0.10, tolerance: 0.001 // Allow 0.1% variance }) ``` **Q: How do I handle partial payments or refunds?** A: Xpay doesn't currently support partial payments. For refunds, you'll need to implement your own refund logic: ```typescript async function issueRefund(transactionId: string, amount: number) { // Create a new transaction record const refund = await db.query(` INSERT INTO transactions (id, type, amount, status, original_transaction_id) VALUES ($1, 'refund', $2, 'pending', $3) `, [generateId(), amount, transactionId]) // Process refund through your payment system // This is outside of Xpay's scope } ``` ### Integration Issues **Q: How do I test my integration without spending real money?** A: Use the test environment: ```typescript const testSmartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-test-abc123.xpay.sh', apiKey: 'xpay_test_...', network: 'base-sepolia' // Testnet }) // Get testnet USDC from faucets // All transactions use test tokens ``` **Q: Can I run multiple agents with the same wallet?** A: While technically possible, it's not recommended for production: - Nonce conflicts can cause transaction failures - Difficult to track spending per agent - Security implications Instead, create separate wallets for each agent: ```typescript async function createAgentWithNewWallet() { const wallet = generateNewWallet() const agent = await smartProxy.createAgent({ id: generateAgentId(), name: 'New Agent', walletAddress: wallet.address, kmsKeyId: await encryptPrivateKey(wallet.privateKey), dailyLimit: 50, perCallLimit: 2 }) return { agent, wallet } } ``` ### Debugging Tools **Q: How can I debug payment flows in detail?** A: Enable debug logging and use the built-in diagnostic tools: ```typescript // Enable debug mode const smartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-abc123.xpay.sh', apiKey: 'xpay_fw_...', debug: true, // Enables detailed logging logLevel: 'debug' }) // Use diagnostic endpoint async function runDiagnostics(agentId: string) { const diagnostics = await smartProxy.runDiagnostics(agentId) console.log('Diagnostics Report:', { agentStatus: diagnostics.agent.status, walletBalance: diagnostics.wallet.balance, networkConnectivity: diagnostics.network.reachable, apiKeyValid: diagnostics.auth.valid, lastTransaction: diagnostics.transactions.latest }) return diagnostics } // Test specific payment scenarios async function testPaymentScenario() { const testResult = await smartProxy.testPayment({ agentId: 'test-agent', amount: 0.10, dryRun: true // Don't actually process payment }) console.log('Payment Test Result:', testResult) } ``` **Q: How do I monitor my integration's health?** A: Implement comprehensive monitoring: ```typescript // Health check endpoint app.get('/health/xpay', async (req, res) => { try { const checks = await Promise.all([ smartProxy.ping(), checkDatabaseConnection(), checkWalletBalances(), checkRecentTransactionSuccess() ]) res.json({ status: 'healthy', timestamp: new Date().toISOString(), checks: { xpayService: checks[0], database: checks[1], wallets: checks[2], transactions: checks[3] } }) } catch (error) { res.status(503).json({ status: 'unhealthy', error: error.message }) } }) // Automated monitoring setInterval(async () => { try { const health = await checkXpayHealth() if (!health.healthy) { await alerting.send('Xpay integration unhealthy', health) } } catch (error) { await alerting.send('Xpay health check failed', error) } }, 60000) // Check every minute ``` ## Getting Help ### Support Channels - **Discord Community**: [discord.gg/xpay](https://discord.gg/vukXDGT7n5) - Fastest response for general questions - **Email Support**: support@xpay.sh - For account and billing issues - **GitHub Issues**: [github.com/xpaysh/xpay-docs](https://github.com/xpaysh/xpay-docs/issues) - For documentation issues - **Emergency Support**: For production outages, use emergency contact provided in your dashboard ### What to Include in Support Requests When reporting issues, include: 1. **Error details**: Full error message and stack trace 2. **Code snippet**: Minimal reproducible example 3. **Environment**: Node.js version, package versions, OS 4. **Agent/Transaction IDs**: For specific payment issues 5. **Timeline**: When the issue started occurring 6. **Expected vs actual behavior**: Clear description of the problem ### Status Page Monitor Xpay service status at: [status.xpay.sh](https://status.xpay.sh) Subscribe to updates to stay informed about: - Service outages - Planned maintenance - Performance issues - New feature releases --- Still having issues? Our team is here to help! Join our [Discord community](https://discord.gg/vukXDGT7n5) or reach out to support@xpay.sh. ================================================================================ # Page: /en/getting-started/index # Source: src/content/en/getting-started/index.mdx ================================================================================ # Quick Start Get up and running with \{xpay✦\} in under 10 minutes. This guide will help you make your first x402 payment and set up comprehensive agent spending controls. ## Overview \{xpay✦\} provides a complete platform for secure AI agent payments: 1. **🛡️ Smart Proxy** - Enterprise-grade spending controls and monitoring 2. **⚡ Paywall Service** - Instant API monetization with x402 payments 3. **📊 Analytics & Monitoring** - Real-time transaction tracking and insights Choose your integration path: import { Callout } from 'nextra/components' **New to x402?** The x402 protocol enables instant, automatic stablecoin payments over HTTP. Learn more in our [x402 Protocol guide](/x402-protocol). ## Prerequisites Before you begin, ensure you have: - Node.js 18+ or Python 3.8+ installed - A wallet with USDC on Base network ([get testnet USDC](https://faucet.circle.com/)) - Your Xpay API key ([sign up for free](https://app.xpay.sh/signup)) **Production Ready**: All examples use mainnet configurations. For testing, use Base Sepolia testnet. ## Installation Install the \{xpay✦\} Agent Kit: ```bash npm2yarn npm install @xpaysh/agent-kit ``` Or install individual packages: ```bash npm2yarn npm install @xpaysh/agent-kit npm install @xpaysh/agent-kit npm install @xpaysh/explorer ``` ## Step 1: Create Your First Protected Agent Set up an agent with enterprise-grade spending controls: ```typescript import { SmartProxy } from '@xpaysh/agent-kit' const smartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-abc123.xpay.sh', apiKey: 'xpay_fw_...' }) // Create an agent with comprehensive controls const agent = await smartProxy.createAgent({ id: 'my-first-agent', name: 'Customer Support Agent', description: 'Handles customer inquiries with AI', walletAddress: '0x742d35Cc6634C0532925a3b8D3Ac2d00fBc1d555', dailyLimit: 50, // $50 daily limit perCallLimit: 2, // $2 per request limit monthlyLimit: 1000, // $1000 monthly limit allowedAPIs: ['openai.com', 'anthropic.com'], businessHours: { enabled: true, timezone: 'America/New_York', schedule: '09:00-17:00', weekdays: [1, 2, 3, 4, 5] // Monday-Friday }, autoShutoff: { enabled: true, threshold: 0.9, // Stop at 90% of limit action: 'pause' } }) console.log('Agent created:', agent.id) ``` ## Step 2: Make Protected API Calls Now use your agent to make safe, monitored API calls: ```typescript // Make a protected AI API call async function askAI(question: string) { try { const response = await smartProxy.protectedFetch('https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_OPENAI_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'gpt-4', messages: [{ role: 'user', content: question }] }), agentId: 'my-first-agent', maxCost: 1.50, // Override per-request limit for this call metadata: { requestType: 'customer_support', priority: 'high' } }) if (!response.ok) { throw new Error(`API call failed: ${response.statusText}`) } const data = await response.json() return data.choices[0].message.content } catch (error) { if (error instanceof SpendingLimitError) { console.log(`Spending limit reached: ${error.limitType}`) console.log(`Resets at: ${error.resetTime}`) return "I'm currently at my spending limit. Please try again later." } throw error } } // Usage const answer = await askAI("How can I help you today?") console.log('AI Response:', answer) ``` ## Step 3: Set Up API Monetization Turn your existing APIs into revenue streams with x402 payments: ```typescript import { XpayPaywall } from '@xpaysh/agent-kit' import express from 'express' const app = express() app.use(express.json()) const paywall = new Paywall({ receivingWallet: '0x742d35Cc6634C0532925a3b8D3Ac2d00fBc1d555', facilitatorUrl: 'https://facilitator.xpay.sh', apiKey: 'xpay_pw_...' }) // Create different pricing tiers const endpoints = [ { path: '/api/basic-data', price: 0.05, description: 'Basic market data' }, { path: '/api/premium-analysis', price: 0.25, description: 'AI-powered market analysis' }, { path: '/api/enterprise-insights', price: 1.00, description: 'Real-time enterprise analytics' } ] // Set up paywalled endpoints endpoints.forEach(endpoint => { app.get(endpoint.path, paywall.middleware({ price: endpoint.price, description: endpoint.description, metadata: { tier: endpoint.path.includes('enterprise') ? 'enterprise' : 'standard', version: 'v1' } }), (req, res) => { // Your API logic here - only runs after successful payment res.json({ message: `${endpoint.description} - Payment verified!`, data: generateMockData(endpoint.path), cost: endpoint.price, timestamp: new Date().toISOString() }) } ) }) // Revenue analytics endpoint app.get('/api/analytics', async (req, res) => { const analytics = await paywall.getRevenueAnalytics({ timeframe: '24h', groupBy: 'endpoint' }) res.json(analytics) }) function generateMockData(path: string) { // Return appropriate mock data based on endpoint if (path.includes('basic')) { return { price: 50000, volume: 1234567 } } else if (path.includes('premium')) { return { analysis: 'Bullish trend detected', confidence: 0.87, signals: ['RSI oversold', 'Volume increase'] } } else { return { insights: ['Market volatility increasing', 'Institutional buying detected'], riskScore: 0.23, recommendations: ['Reduce position size', 'Monitor closely'] } } } app.listen(3000, () => { console.log('🚀 Monetized API server running on port 3000') console.log('💰 Revenue tracking enabled') }) ``` ## Step 4: Monitor and Analyze Get comprehensive insights into your agent spending and API revenue: ```typescript // Monitor agent spending patterns const spendingAnalytics = await smartProxy.getSpendingAnalytics({ agentIds: ['my-first-agent'], timeframe: '24h', groupBy: 'agent', includeMetadata: true }) console.log('Spending Analytics:') console.log(`Total spent: $${spendingAnalytics.totalSpent}`) console.log(`Total calls: ${spendingAnalytics.totalCalls}`) console.log(`Average cost per call: $${spendingAnalytics.averageCostPerCall}`) spendingAnalytics.breakdown.forEach(item => { console.log(`${item.key}: $${item.spent} (${item.percentage}%)`) }) // Track transaction history const transactions = await smartProxy.getTransactionHistory({ agentIds: ['my-first-agent'], limit: 10, status: 'confirmed' }) console.log('\nRecent Transactions:') transactions.transactions.forEach(tx => { console.log(`${tx.createdAt}: $${tx.amount} - ${tx.status}`) }) // Set up real-time webhooks for monitoring await smartProxy.configureWebhooks({ endpoint: 'https://your-app.com/webhooks/xpay', events: [ 'agent.spending.warning', // 80% of limit reached 'agent.spending.exceeded', // Limit hit 'agent.unusual_pattern', // Suspicious activity 'transaction.failed' // Failed payments ], secret: 'webhook_secret_key', retries: 3 }) // Monitor paywall revenue const revenueAnalytics = await paywall.getRevenueAnalytics({ timeframe: '7d', groupBy: 'endpoint' }) console.log('\nRevenue Analytics:') console.log(`Total revenue: $${revenueAnalytics.totalRevenue}`) console.log(`Unique customers: ${revenueAnalytics.uniqueCustomers}`) revenueAnalytics.breakdown.forEach(endpoint => { console.log(`${endpoint.path}: $${endpoint.revenue} (${endpoint.requests} requests)`) }) ``` ## 🎉 Success! You're Now Xpay-Enabled You've successfully set up: - ✅ Agent with enterprise spending controls - ✅ Protected API calls with automatic monitoring - ✅ Monetized endpoints earning x402 payments - ✅ Real-time analytics and webhook notifications ## Next Steps ### 🛡️ **Advanced Agent Security** - **[Smart Proxy](/products/smart-proxy)** - Multi-agent management, custom rules, and circuit breakers - **[Production Deployment](/getting-started/production-deployment)** - Docker, Kubernetes, and CI/CD pipelines - **[Integration Patterns](/developer-resources/integration-patterns)** - Complex scenarios and best practices ### ⚡ **Scale Your Revenue** - **[Paywall Service](/products/paywall-service)** - Advanced pricing models and subscription management - **[Revenue Optimization](/guides/revenue-optimization)** - Maximize earnings with dynamic pricing - **[API Marketplace](/marketplace)** - List your APIs for discovery ### 📊 **Production Monitoring** - **[Analytics Dashboard](https://app.xpay.sh/analytics)** - Visual insights and reports - **[Alerts & Notifications](/guides/monitoring-alerts)** - Proactive issue detection - **[SDK Reference](/developer-resources/sdk-reference)** - Complete API documentation ### 🔧 **Developer Resources** - **[Troubleshooting Guide](/developer-resources/troubleshooting)** - Common issues and solutions - **[Testing Patterns](/guides/testing)** - Unit tests and integration testing - **[Migration Guide](/guides/migration)** - Upgrade from legacy payment systems ## Get Support **Enterprise Support**: Need dedicated support? [Contact our enterprise team](https://xpay.sh/enterprise) for priority assistance, custom integrations, and SLA guarantees. ### Community & Support Channels - 💬 **[Discord Community](https://discord.gg/vukXDGT7n5)** - Chat with developers and get real-time help - 📚 **[Documentation](/)** - Comprehensive guides and API reference - 🐛 **[GitHub Issues](https://github.com/xpaysh/xpay-docs/issues)** - Bug reports and feature requests - 📧 **[Support Email](mailto:support@xpay.sh)** - Direct support for technical issues ### Quick Links - 🎮 **[Interactive Playground](https://playground.xpay.sh)** - Test API calls in your browser - 📊 **[Status Page](https://status.xpay.sh)** - Real-time service status and incident history - 🔧 **[Postman Collection](https://www.postman.com/xpay-team/workspace/xpay-public)** - Ready-to-use API requests - 📱 **[Mobile SDKs](https://github.com/xpaysh/mobile-sdks)** - iOS and Android integration libraries --- **Ready to build production systems?** Continue to [Production Deployment →](/getting-started/production-deployment) ================================================================================ # Page: /en/getting-started/installation # Source: src/content/en/getting-started/installation.mdx ================================================================================ # Installation This guide covers everything you need to install and configure \{xpay✦\} for your project. ## System Requirements - **Node.js**: Version 18.0 or higher - **Package Manager**: npm, yarn, or pnpm - **Crypto Wallet**: MetaMask, Coinbase Wallet, or any Web3 wallet - **Network**: Base mainnet or testnet ## Package Installation ### Full Agent Kit (Recommended) For most developers, installing the complete agent kit is the easiest way to get started: ```bash npm2yarn npm install @xpaysh/agent-kit ``` This includes all \{xpay✦\} components: - `@xpaysh/agent-kit` - Agent spending protection - `@xpaysh/agent-kit` - API monetization - `@xpaysh/explorer` - Transaction monitoring - `@xpaysh/sdk` - Core x402 utilities ### Individual Packages Install only what you need: **Agent protection only:** ```bash npm2yarn npm install @xpaysh/agent-kit ``` **API monetization only:** ```bash npm2yarn npm install @xpaysh/agent-kit ``` **Transaction monitoring only:** ```bash npm2yarn npm install @xpaysh/explorer ``` **Core SDK only:** ```bash npm2yarn npm install @xpaysh/sdk ``` ## Environment Setup ### 1. Environment Variables Create a `.env.local` file in your project root: ```bash # \{xpay✦\} Configuration XPAY_API_KEY=xpay_test_... XPAY_PROJECT_ID=proj_... # Wallet Configuration AGENT_WALLET_PRIVATE_KEY=0x... RECEIVING_WALLET_ADDRESS=0x... # x402 Network X402_NETWORK=base-sepolia # or 'base-mainnet' for production X402_FACILITATOR_URL=https://facilitator.xpay.sh # Optional: Custom RPC BASE_RPC_URL=https://base-sepolia.g.alchemy.com/v2/... ``` ### 2. TypeScript Configuration Add types to your `tsconfig.json`: ```json { "compilerOptions": { "moduleResolution": "node", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true }, "include": [ "**/*.ts", "**/*.tsx", "node_modules/@xpaysh/*/types/**/*" ] } ``` ### 3. Next.js Configuration (if using Next.js) Update your `next.config.js`: ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { serverComponentsExternalPackages: ['@xpaysh/agent-kit'] }, webpack: (config) => { config.resolve.fallback = { ...config.resolve.fallback, fs: false, net: false, tls: false, } return config } } module.exports = nextConfig ``` ## Wallet Setup ### Getting Test Funds For development and testing: 1. **Base Sepolia Testnet**: - Get ETH: [Base Sepolia Faucet](https://faucet.quicknode.com/base/sepolia) - Get USDC: [Circle Faucet](https://faucet.circle.com/) 2. **Add Base Sepolia to your wallet**: ``` Network Name: Base Sepolia RPC URL: https://sepolia.base.org Chain ID: 84532 Currency Symbol: ETH ``` ### Production Wallets For production deployments: 1. **Agent Wallets**: Use HD wallets or hardware wallets for agent private keys 2. **Receiving Wallets**: Use multisig wallets for receiving payments 3. **Key Management**: Never commit private keys to version control ## Framework-Specific Setup ### Express.js ```javascript import express from 'express' import { XpayPaywall } from '@xpaysh/agent-kit' const app = express() app.use(express.json()) // Initialize \{xpay✦\} middleware const paywall = new Paywall({ pricePerRequest: 0.10, receivingWallet: process.env.RECEIVING_WALLET_ADDRESS }) app.use('/api/premium', paywall.middleware) ``` ### Fastify ```javascript import Fastify from 'fastify' import { SmartProxy } from '@xpaysh/agent-kit' const fastify = Fastify() // Register \{xpay✦\} plugin fastify.register(async function (fastify) { const smartProxy = new SmartProxy({ maxDailySpend: 100 }) fastify.decorateRequest('smartProxy', smartProxy) }) ``` ### Vercel Edge Functions ```typescript import { NextRequest } from 'next/server' import { XpayPaywall } from '@xpaysh/agent-kit' export const config = { runtime: 'edge' } const paywall = new Paywall({ pricePerRequest: 0.05, receivingWallet: process.env.RECEIVING_WALLET_ADDRESS }) export default async function handler(req: NextRequest) { return await paywall.handleRequest(req) } ``` ## Verification Test your installation: ```typescript import { XpaySDK } from '@xpaysh/agent-kit' async function verifyInstallation() { try { const sdk = new XpaySDK({ apiKey: process.env.XPAY_API_KEY, projectId: process.env.XPAY_PROJECT_ID }) const status = await sdk.healthCheck() console.log('✅ \{xpay✦\} installation verified:', status) } catch (error) { console.error('❌ Installation verification failed:', error) } } verifyInstallation() ``` Expected output: ``` ✅ \{xpay✦\} installation verified: { status: 'healthy', network: 'base-sepolia', facilitator: 'connected', version: '1.0.0' } ``` ## Common Issues ### Module Resolution Errors If you see `Cannot resolve module '@xpaysh/agent-kit'`: ```bash # Clear cache and reinstall rm -rf node_modules package-lock.json npm install # Or with yarn yarn cache clean yarn install ``` ### Wallet Connection Issues If wallet connections fail: 1. Ensure you're on the correct network (Base Sepolia for testing) 2. Check that your wallet has sufficient ETH for gas fees 3. Verify the RPC URL is accessible ### TypeScript Errors Add type declarations if needed: ```typescript // types/xpay.d.ts declare module '@xpaysh/agent-kit' { export * from '@xpaysh/agent-kit/types' } ``` ## Next Steps Now that \{xpay✦\} is installed: 1. [Make your first payment →](/getting-started/first-payment) 2. [Integrate with your agent →](/getting-started/agent-integration) 3. [Monetize your API →](/getting-started/api-monetization) ## Need Help? - 📚 **Troubleshooting Guide**: [Common issues and solutions](/guides/troubleshooting) - 💬 **Discord**: Get help from our [community](https://discord.gg/vukXDGT7n5) - 🐛 **Bug Reports**: [GitHub Issues](https://github.com/xpaysh/xpay-agent-kit/issues) ================================================================================ # Page: /en/getting-started/production-deployment # Source: src/content/en/getting-started/production-deployment.mdx ================================================================================ # Production Deployment Guide Complete guide for deploying Xpay-integrated applications to production, including security, monitoring, and scaling considerations. import { Callout } from 'nextra/components' **Security First**: Production deployments handle real payments. Follow all security guidelines carefully to protect your users and revenue. ## Pre-Deployment Checklist ### Security Requirements - [ ] **Environment Variables**: All sensitive data stored in environment variables - [ ] **HTTPS Only**: All endpoints serve over HTTPS with valid certificates - [ ] **API Key Rotation**: Regular rotation schedule for Xpay API keys - [ ] **Wallet Security**: Non-custodial wallets with proper KMS integration - [ ] **Rate Limiting**: Protection against DDoS and abuse - [ ] **Input Validation**: All user inputs properly validated and sanitized ### Performance Requirements - [ ] **Caching Strategy**: Payment verification and customer data caching - [ ] **Database Indexing**: Proper indexes on transaction and agent tables - [ ] **Connection Pooling**: Database and HTTP connection pooling configured - [ ] **Error Handling**: Comprehensive error handling and retry logic - [ ] **Monitoring**: Health checks, metrics, and alerting configured ### Business Requirements - [ ] **Backup Strategy**: Regular backups of critical data - [ ] **Disaster Recovery**: Recovery procedures documented and tested - [ ] **Compliance**: Legal and regulatory requirements met - [ ] **Customer Support**: Support processes for payment issues ## Environment Configuration ### Environment Variables ```bash # Xpay Configuration XPAY_API_KEY=xpay_live_... XPAY_SMART_PROXY_ENDPOINT=https://smart-proxy-prod-abc123.xpay.sh XPAY_WEBHOOK_SECRET=whsec_... # Wallet Configuration XPAY_RECEIVING_WALLET=0x742d35Cc6634C0532925a3b8D3Ac2d00fBc1d555 XPAY_KMS_KEY_ID=arn:aws:kms:us-east-1:123456789:key/... # Network Configuration XPAY_FACILITATOR_URL=https://facilitator.xpay.sh XPAY_NETWORK=base-mainnet XPAY_BLOCK_CONFIRMATIONS=3 # Security HTTPS_ONLY=true CORS_ORIGINS=https://yourdomain.com,https://app.yourdomain.com RATE_LIMIT_REQUESTS_PER_MINUTE=100 # Monitoring DATADOG_API_KEY=... SENTRY_DSN=... PROMETHEUS_ENABLED=true PROMETHEUS_PORT=9090 # Database DATABASE_URL=postgresql://user:pass@host:5432/dbname REDIS_URL=redis://cache.cluster.amazonaws.com:6379 # Application NODE_ENV=production PORT=3000 LOG_LEVEL=info ``` ### Configuration Files Create production configuration files: ```typescript // config/production.ts export const productionConfig = { xpay: { apiKey: process.env.XPAY_API_KEY!, smartProxyEndpoint: process.env.XPAY_SMART_PROXY_ENDPOINT!, webhookSecret: process.env.XPAY_WEBHOOK_SECRET!, // Production optimizations timeout: 30000, retries: 3, caching: { enabled: true, ttl: 300, provider: 'redis' }, // Security settings security: { httpsOnly: true, validateOrigin: true, maxPaymentAge: 300, rateLimitByWallet: true } }, database: { url: process.env.DATABASE_URL!, pool: { min: 2, max: 20, acquireTimeoutMillis: 30000, idleTimeoutMillis: 30000 }, migrations: { directory: './migrations', tableName: 'knex_migrations' } }, monitoring: { enabled: true, healthCheck: '/health', metrics: { enabled: true, port: 9090, path: '/metrics' }, logging: { level: 'info', format: 'json', destination: 'datadog' } } } ``` ## Infrastructure Setup ### Docker Configuration ```dockerfile # Multi-stage build for optimized production image FROM node:18-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci --only=production && npm cache clean --force # Production stage FROM node:18-alpine AS production # Security: Create non-root user RUN addgroup -g 1001 -S nodejs RUN adduser -S nextjs -u 1001 WORKDIR /app # Copy production dependencies COPY --from=builder /app/node_modules ./node_modules COPY --chown=nextjs:nodejs . . # Security and performance optimizations ENV NODE_ENV=production ENV NODE_OPTIONS="--max-old-space-size=1024" USER nextjs EXPOSE 3000 # Health check HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ CMD curl -f http://localhost:3000/health || exit 1 CMD ["npm", "start"] ``` ### Docker Compose (Development/Staging) ```yaml version: '3.8' services: app: build: . ports: - "3000:3000" environment: - NODE_ENV=production - DATABASE_URL=postgresql://postgres:password@db:5432/xpay - REDIS_URL=redis://redis:6379 depends_on: - db - redis restart: unless-stopped db: image: postgres:15-alpine environment: POSTGRES_DB: xpay POSTGRES_USER: postgres POSTGRES_PASSWORD: password volumes: - postgres_data:/var/lib/postgresql/data restart: unless-stopped redis: image: redis:7-alpine volumes: - redis_data:/data restart: unless-stopped nginx: image: nginx:alpine ports: - "80:80" - "443:443" volumes: - ./nginx.conf:/etc/nginx/nginx.conf - ./ssl:/etc/nginx/ssl depends_on: - app restart: unless-stopped volumes: postgres_data: redis_data: ``` ### Kubernetes Deployment ```yaml # deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: xpay-app labels: app: xpay-app spec: replicas: 3 strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 0 selector: matchLabels: app: xpay-app template: metadata: labels: app: xpay-app spec: containers: - name: app image: your-registry/xpay-app:latest ports: - containerPort: 3000 env: - name: XPAY_API_KEY valueFrom: secretKeyRef: name: xpay-secrets key: api-key - name: DATABASE_URL valueFrom: secretKeyRef: name: database-secrets key: url resources: requests: cpu: 200m memory: 256Mi limits: cpu: 1000m memory: 1Gi livenessProbe: httpGet: path: /health port: 3000 initialDelaySeconds: 30 periodSeconds: 10 failureThreshold: 3 readinessProbe: httpGet: path: /ready port: 3000 initialDelaySeconds: 10 periodSeconds: 5 failureThreshold: 3 --- apiVersion: v1 kind: Service metadata: name: xpay-app-service spec: selector: app: xpay-app ports: - port: 80 targetPort: 3000 type: ClusterIP --- apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: xpay-app-ingress annotations: kubernetes.io/ingress.class: nginx cert-manager.io/cluster-issuer: letsencrypt-prod nginx.ingress.kubernetes.io/rate-limit: "100" spec: tls: - hosts: - api.yourdomain.com secretName: xpay-tls rules: - host: api.yourdomain.com http: paths: - path: / pathType: Prefix backend: service: name: xpay-app-service port: number: 80 ``` ## Database Setup ### Migration Strategy ```typescript // migrations/001_create_agents.ts export async function up(knex: Knex): Promise { return knex.schema.createTable('agents', (table) => { table.string('id').primary() table.string('name').notNullable() table.text('description') table.string('user_id').notNullable().index() table.string('customer_id').notNullable().index() table.string('wallet_address').notNullable() table.string('kms_key_id').notNullable() table.integer('nonce').notNullable().defaultTo(0) table.decimal('daily_limit', 18, 6).notNullable() table.decimal('per_call_limit', 18, 6).notNullable() table.decimal('monthly_limit', 18, 6) table.enum('status', ['active', 'paused', 'suspended', 'deleted']).notNullable().defaultTo('active') table.decimal('total_spent', 18, 6).notNullable().defaultTo(0) table.integer('total_calls').notNullable().defaultTo(0) table.timestamp('created_at').notNullable().defaultTo(knex.fn.now()) table.timestamp('updated_at').notNullable().defaultTo(knex.fn.now()) // Indexes for performance table.index(['user_id', 'status']) table.index(['customer_id', 'status']) table.index('created_at') }) } // migrations/002_create_transactions.ts export async function up(knex: Knex): Promise { return knex.schema.createTable('transactions', (table) => { table.string('id').primary() table.string('agent_id').notNullable().references('id').inTable('agents') table.string('endpoint_id').references('id').inTable('endpoints') table.decimal('amount', 18, 6).notNullable() table.string('currency').notNullable().defaultTo('USDC') table.enum('status', ['pending', 'confirmed', 'failed', 'cancelled']).notNullable() table.enum('type', ['api_call', 'subscription', 'refund', 'adjustment']).notNullable() table.jsonb('metadata') table.string('hash') table.integer('gas_used') table.string('gas_price') table.timestamp('created_at').notNullable().defaultTo(knex.fn.now()) // Indexes for analytics and reporting table.index(['agent_id', 'created_at']) table.index(['status', 'created_at']) table.index(['type', 'created_at']) table.index('hash') }) } ``` ### Database Optimization ```typescript // config/database.ts import { Pool } from 'pg' export const createDatabasePool = () => { return new Pool({ connectionString: process.env.DATABASE_URL, // Connection pool settings min: 2, max: 20, idleTimeoutMillis: 30000, connectionTimeoutMillis: 10000, // Performance optimizations statement_timeout: 30000, query_timeout: 30000, // SSL configuration for production ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false }) } // Database queries with proper indexing export class AgentRepository { constructor(private db: Pool) {} async findActiveAgentsByUser(userId: string): Promise { // Optimized query using compound index const result = await this.db.query(` SELECT * FROM agents WHERE user_id = $1 AND status = 'active' ORDER BY created_at DESC `, [userId]) return result.rows } async getSpendingAnalytics(agentId: string, timeframe: string): Promise { // Use time-based partitioning for large datasets const result = await this.db.query(` SELECT DATE_TRUNC('hour', created_at) as hour, SUM(amount) as total_spent, COUNT(*) as total_calls FROM transactions WHERE agent_id = $1 AND created_at >= NOW() - INTERVAL '${timeframe}' AND status = 'confirmed' GROUP BY hour ORDER BY hour `, [agentId]) return result.rows } } ``` ## Monitoring & Observability ### Health Checks ```typescript // health.ts import express from 'express' import { SmartProxy } from '@xpaysh/agent-kit' const router = express.Router() router.get('/health', async (req, res) => { const checks = { timestamp: new Date().toISOString(), status: 'healthy', checks: { database: 'unknown', redis: 'unknown', xpay: 'unknown' } } try { // Database health check await db.query('SELECT 1') checks.checks.database = 'healthy' } catch (error) { checks.checks.database = 'unhealthy' checks.status = 'unhealthy' } try { // Redis health check await redis.ping() checks.checks.redis = 'healthy' } catch (error) { checks.checks.redis = 'unhealthy' checks.status = 'unhealthy' } try { // Xpay service health check await smartProxy.ping() checks.checks.xpay = 'healthy' } catch (error) { checks.checks.xpay = 'unhealthy' checks.status = 'unhealthy' } const statusCode = checks.status === 'healthy' ? 200 : 503 res.status(statusCode).json(checks) }) router.get('/ready', async (req, res) => { // Readiness check - can serve traffic try { await db.query('SELECT 1') res.status(200).json({ status: 'ready' }) } catch (error) { res.status(503).json({ status: 'not ready' }) } }) export default router ``` ### Metrics Collection ```typescript // metrics.ts import client from 'prom-client' // Create custom metrics const httpRequestsTotal = new client.Counter({ name: 'http_requests_total', help: 'Total number of HTTP requests', labelNames: ['method', 'route', 'status_code'] }) const xpayPaymentsTotal = new client.Counter({ name: 'xpay_payments_total', help: 'Total number of Xpay payments', labelNames: ['agent_id', 'status', 'type'] }) const xpayPaymentAmount = new client.Histogram({ name: 'xpay_payment_amount_usdc', help: 'Payment amounts in USDC', buckets: [0.01, 0.05, 0.1, 0.5, 1, 5, 10, 50, 100], labelNames: ['agent_id', 'type'] }) const agentSpendingLimit = new client.Gauge({ name: 'xpay_agent_spending_limit_usdc', help: 'Agent spending limits', labelNames: ['agent_id', 'limit_type'] }) // Middleware to collect HTTP metrics export const metricsMiddleware = (req: express.Request, res: express.Response, next: express.NextFunction) => { const start = Date.now() res.on('finish', () => { const duration = Date.now() - start httpRequestsTotal.labels( req.method, req.route?.path || req.path, res.statusCode.toString() ).inc() }) next() } // Function to update payment metrics export const recordPayment = (agentId: string, amount: number, status: string, type: string) => { xpayPaymentsTotal.labels(agentId, status, type).inc() if (status === 'confirmed') { xpayPaymentAmount.labels(agentId, type).observe(amount) } } // Metrics endpoint export const metricsEndpoint = (req: express.Request, res: express.Response) => { res.set('Content-Type', client.register.contentType) res.end(client.register.metrics()) } ``` ### Logging Strategy ```typescript // logger.ts import winston from 'winston' import { DatadogWinston } from '@datadog/winston' const logger = winston.createLogger({ level: process.env.LOG_LEVEL || 'info', format: winston.format.combine( winston.format.timestamp(), winston.format.errors({ stack: true }), winston.format.json() ), defaultMeta: { service: 'xpay-app', version: process.env.npm_package_version }, transports: [ // Console logging for development new winston.transports.Console({ format: winston.format.simple() }), // Datadog logging for production new DatadogWinston({ apiKey: process.env.DATADOG_API_KEY!, hostname: process.env.HOSTNAME, service: 'xpay-app', ddsource: 'nodejs' }) ] }) // Payment-specific logging export const logPayment = (event: string, data: any) => { logger.info('Payment event', { event, agentId: data.agentId, amount: data.amount, transactionId: data.transactionId, timestamp: new Date().toISOString() }) } // Error logging with context export const logError = (error: Error, context: any) => { logger.error('Application error', { error: error.message, stack: error.stack, context, timestamp: new Date().toISOString() }) } export default logger ``` ## Security Implementation ### API Security ```typescript // security.ts import helmet from 'helmet' import rateLimit from 'express-rate-limit' import slowDown from 'express-slow-down' // Security headers export const securityMiddleware = helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], scriptSrc: ["'self'", "'unsafe-inline'"], styleSrc: ["'self'", "'unsafe-inline'"], imgSrc: ["'self'", "data:", "https:"], connectSrc: ["'self'", "https://facilitator.xpay.sh"] } }, hsts: { maxAge: 31536000, includeSubDomains: true, preload: true } }) // Rate limiting export const createRateLimit = (windowMs: number, max: number) => rateLimit({ windowMs, max, message: { error: 'Too many requests', retryAfter: Math.ceil(windowMs / 1000) }, standardHeaders: true, legacyHeaders: false, // Skip successful payments from rate limiting skip: (req) => { return req.headers['x-payment-verified'] === 'true' } }) // Slow down repeated requests export const speedLimiter = slowDown({ windowMs: 15 * 60 * 1000, // 15 minutes delayAfter: 10, // Allow 10 requests per window at full speed delayMs: 500 // Add 500ms delay per request after delayAfter }) // Payment verification middleware export const verifyPayment = async (req: express.Request, res: express.Response, next: express.NextFunction) => { try { const paymentValid = await paywall.verifyPayment(req.headers, { price: req.route?.price || 0.01, tolerance: 0.001, maxAge: 300 }) if (paymentValid.valid) { req.headers['x-payment-verified'] = 'true' req.paymentDetails = paymentValid } next() } catch (error) { logger.error('Payment verification failed', { error, headers: req.headers }) res.status(500).json({ error: 'Payment verification error' }) } } ``` ### Wallet Security ```typescript // wallet-security.ts import AWS from 'aws-sdk' import { encrypt, decrypt } from './encryption' const kms = new AWS.KMS({ region: process.env.AWS_REGION }) export class SecureWalletManager { private kmsKeyId: string constructor(kmsKeyId: string) { this.kmsKeyId = kmsKeyId } async encryptPrivateKey(privateKey: string): Promise { const params = { KeyId: this.kmsKeyId, Plaintext: Buffer.from(privateKey) } const result = await kms.encrypt(params).promise() return result.CiphertextBlob!.toString('base64') } async decryptPrivateKey(encryptedKey: string): Promise { const params = { CiphertextBlob: Buffer.from(encryptedKey, 'base64') } const result = await kms.decrypt(params).promise() return result.Plaintext!.toString() } async rotateWalletKeys(agentId: string): Promise { // Generate new wallet const newWallet = generateNewWallet() // Encrypt new private key const encryptedKey = await this.encryptPrivateKey(newWallet.privateKey) // Update agent with new wallet await db.query(` UPDATE agents SET wallet_address = $1, kms_key_id = $2, updated_at = NOW() WHERE id = $3 `, [newWallet.address, encryptedKey, agentId]) // Log key rotation logger.info('Wallet key rotated', { agentId, newAddress: newWallet.address }) } } ``` ## Performance Optimization ### Caching Strategy ```typescript // cache.ts import Redis from 'ioredis' const redis = new Redis(process.env.REDIS_URL!) export class CacheManager { // Cache payment verifications async cachePaymentVerification(paymentHash: string, isValid: boolean, ttl = 300) { await redis.setex(`payment:${paymentHash}`, ttl, JSON.stringify({ valid: isValid, timestamp: Date.now() })) } async getCachedPaymentVerification(paymentHash: string): Promise { const cached = await redis.get(`payment:${paymentHash}`) if (!cached) return null const data = JSON.parse(cached) return data.valid } // Cache agent data async cacheAgent(agentId: string, agent: Agent, ttl = 900) { // 15 minutes await redis.setex(`agent:${agentId}`, ttl, JSON.stringify(agent)) } async getCachedAgent(agentId: string): Promise { const cached = await redis.get(`agent:${agentId}`) return cached ? JSON.parse(cached) : null } // Cache spending analytics async cacheSpendingAnalytics(key: string, data: any, ttl = 300) { // 5 minutes await redis.setex(`analytics:${key}`, ttl, JSON.stringify(data)) } async invalidateAgentCache(agentId: string) { const pattern = `*${agentId}*` const keys = await redis.keys(pattern) if (keys.length > 0) { await redis.del(...keys) } } } export const cache = new CacheManager() ``` ### Database Connection Pooling ```typescript // database.ts import { Pool, PoolConfig } from 'pg' import { promisify } from 'util' const poolConfig: PoolConfig = { connectionString: process.env.DATABASE_URL, // Pool settings for high-traffic production min: parseInt(process.env.DB_POOL_MIN || '5'), max: parseInt(process.env.DB_POOL_MAX || '20'), // Connection timing idleTimeoutMillis: 30000, connectionTimeoutMillis: 10000, acquireTimeoutMillis: 10000, // Health checks allowExitOnIdle: false, // SSL for production ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false } export const db = new Pool(poolConfig) // Graceful shutdown process.on('SIGINT', async () => { console.log('Closing database pool...') await db.end() process.exit(0) }) // Connection monitoring db.on('connect', () => { console.log('Database connected') }) db.on('error', (err) => { console.error('Database error:', err) }) ``` ## Deployment Automation ### CI/CD Pipeline (GitHub Actions) ```yaml # .github/workflows/deploy.yml name: Deploy to Production on: push: branches: [main] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js uses: actions/setup-node@v3 with: node-version: '18' cache: 'npm' - name: Install dependencies run: npm ci - name: Run tests run: npm test - name: Run security audit run: npm audit --audit-level high build: needs: test runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Build Docker image run: | docker build -t xpay-app:${{ github.sha }} . docker tag xpay-app:${{ github.sha }} your-registry/xpay-app:latest - name: Push to registry run: | echo ${{ secrets.DOCKER_PASSWORD }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin docker push your-registry/xpay-app:latest docker push your-registry/xpay-app:${{ github.sha }} deploy: needs: build runs-on: ubuntu-latest environment: production steps: - name: Deploy to Kubernetes run: | echo ${{ secrets.KUBECONFIG }} | base64 -d > kubeconfig export KUBECONFIG=kubeconfig kubectl set image deployment/xpay-app app=your-registry/xpay-app:${{ github.sha }} kubectl rollout status deployment/xpay-app ``` ### Health Check Monitoring ```typescript // monitoring/alerts.ts import { CloudWatch } from 'aws-sdk' const cloudwatch = new CloudWatch({ region: process.env.AWS_REGION }) export class AlertManager { async sendMetric(metricName: string, value: number, unit = 'Count') { await cloudwatch.putMetricData({ Namespace: 'XpayApp', MetricData: [{ MetricName: metricName, Value: value, Unit: unit, Timestamp: new Date() }] }).promise() } async checkHealthAndAlert() { try { // Check database connectivity await db.query('SELECT 1') await this.sendMetric('DatabaseHealth', 1) } catch (error) { await this.sendMetric('DatabaseHealth', 0) await this.sendAlert('Database connection failed', error) } try { // Check Xpay service await smartProxy.ping() await this.sendMetric('XpayServiceHealth', 1) } catch (error) { await this.sendMetric('XpayServiceHealth', 0) await this.sendAlert('Xpay service unreachable', error) } } private async sendAlert(message: string, error: any) { // Send to Slack, PagerDuty, etc. logger.error('Health check failed', { message, error }) } } // Run health checks every minute setInterval(async () => { const alertManager = new AlertManager() await alertManager.checkHealthAndAlert() }, 60000) ``` ## Post-Deployment Checklist ### Immediate Post-Deploy - [ ] **Health checks passing**: All endpoints returning 200 - [ ] **Database migrations**: Applied successfully - [ ] **Payment processing**: Test transactions working - [ ] **Monitoring active**: Metrics being collected - [ ] **Logs flowing**: Centralized logging operational ### Within 24 Hours - [ ] **Performance baseline**: Response times within SLA - [ ] **Error rates**: Below acceptable thresholds - [ ] **Payment success rate**: Above 99% - [ ] **Customer notifications**: No support tickets related to deployment - [ ] **Backup verification**: Recent backups tested and accessible ### Within 1 Week - [ ] **Load testing**: System handles expected traffic - [ ] **Disaster recovery**: Procedures tested - [ ] **Security scan**: No new vulnerabilities - [ ] **Performance optimization**: Any bottlenecks identified and addressed - [ ] **Documentation updated**: Deployment notes and lessons learned --- Need help with deployment? Check our [troubleshooting guide](/developer-resources/troubleshooting) or contact support at support@xpay.sh. ================================================================================ # Page: /en/hub/get-started/create-account # Source: src/content/en/hub/get-started/create-account.mdx ================================================================================ # Create Account xpay✦ Hub uses [Privy](https://privy.io) for authentication, providing multiple sign-in options. ## Sign In Options ### Email 1. Visit [hub.xpay.sh](https://hub.xpay.sh) 2. Click **Sign In** 3. Enter your email address 4. Check your email for a verification code 5. Enter the code to complete sign-in A wallet will be automatically created for you. ### Web3 Wallet Connect your existing Web3 wallet: 1. Click **Sign In** 2. Select **Connect Wallet** 3. Choose your wallet (MetaMask, Coinbase Wallet, WalletConnect, etc.) 4. Approve the connection in your wallet ### Social Login Sign in with your social accounts: - **Google** - Use your Google account - **Twitter** - Connect via Twitter/X - **Discord** - Sign in with Discord ## Your Wallet After signing in, xpay✦ creates a wallet for you: - **Address** - Your unique wallet address on Base network - **Balance** - Your USDC balance for running RDAs - **Default Allowance** - $10 initial spending limit You can view your wallet at [Account > Wallet](https://hub.xpay.sh/account/wallet). ## Account Features Once signed in, you can: - **Run RDAs** - Execute any RDA from the marketplace - **View History** - See all your past RDA runs - **Manage Wallet** - Deposit funds and adjust spending limits - **Create RDAs** - Build and publish your own RDAs (creator mode) ## Security xpay✦ Hub is **non-custodial**: - You control your private keys (via Privy) - Funds are held in your wallet, not ours - All transactions are on-chain on Base network ## Next Steps - [Fund your wallet](/hub/get-started/fund-wallet) with USDC - [Run your first RDA](/hub/get-started/run-first-rda) ================================================================================ # Page: /en/hub/get-started/fund-wallet # Source: src/content/en/hub/get-started/fund-wallet.mdx ================================================================================ # Fund Your Wallet To run RDAs, you need USDC in your xpay✦ wallet. ## Supported Currency - **USDC** - USD Coin on Base network - **Network** - Base (Coinbase L2) - **Minimum** - No minimum deposit ## How to Deposit ### From External Wallet 1. Go to [Account > Wallet](https://hub.xpay.sh/account/wallet) 2. Copy your wallet address 3. Send USDC on Base network to this address 4. Wait for confirmation (~2 seconds) ### Bridge from Other Networks If your USDC is on Ethereum, Polygon, or other networks: 1. Use [Base Bridge](https://bridge.base.org) to bridge to Base 2. Send bridged USDC to your xpay✦ wallet ### Purchase with Card Coming soon - purchase USDC directly with credit/debit card. ## Spending Allowance xpay✦ Hub uses a spending allowance system: - **Default Allowance** - $10 initial limit - **Per-Transaction Limit** - Configurable maximum per RDA run - **No Per-Transaction Signing** - Seamless UX once funded ### How It Works 1. Deposit USDC to your wallet 2. Set your spending allowance (default $10) 3. Run RDAs without signing each transaction 4. Balance is automatically deducted ## Check Your Balance View your wallet status at [Account > Wallet](https://hub.xpay.sh/account/wallet): - **Balance** - Total USDC available - **Available** - Amount available for spending - **Locked** - Amount locked in pending transactions ## API Access Check balance programmatically: ```bash curl -X GET https://api.xpay.sh/hub/wallet/balance \ -H "Authorization: Bearer YOUR_TOKEN" ``` Response: ```json { "wallet": { "balance": 100.50, "availableBalance": 95.00, "totalLocked": 5.50 } } ``` ## Next Steps - [Run your first RDA](/hub/get-started/run-first-rda) - [Understanding pricing](/hub/guides/users/understanding-pricing) ================================================================================ # Page: /en/hub/get-started/index # Source: src/content/en/hub/get-started/index.mdx ================================================================================ # Get Started Welcome to xpay✦ Hub! This guide will help you get up and running quickly. ## Prerequisites Before you begin, you'll need: - A web browser (Chrome, Firefox, Safari, or Edge) - An email address or Web3 wallet for authentication - USDC on Base network for running RDAs (optional for browsing) ## Quick Start Steps ### 1. Create an Account Visit [hub.xpay.sh](https://hub.xpay.sh) and sign in using Privy: - **Email** - Sign in with your email address - **Wallet** - Connect MetaMask, Coinbase Wallet, or other Web3 wallets - **Social** - Use Google, Twitter, or Discord [Learn more about account creation](/hub/get-started/create-account) ### 2. Fund Your Wallet To run RDAs, you'll need USDC in your xpay✦ wallet: - Deposit USDC from your external wallet - Purchase USDC directly with a card (coming soon) - Start with the default $10 spending allowance [Learn more about funding](/hub/get-started/fund-wallet) ### 3. Run Your First RDA Browse the marketplace and find an RDA to run: 1. Go to [Explore](https://hub.xpay.sh/explore) 2. Browse by type (Prompts, Agents, Tools) 3. Click on an RDA to see details 4. Fill in the required inputs 5. Click **Run** to execute [Detailed walkthrough](/hub/get-started/run-first-rda) ## Understanding RDAs Before diving in, it helps to understand [what RDAs are](/hub/get-started/what-are-rdas) and the three types available: - **Prompts** - LLM-based text generation with model selection - **Agents** - Workflow automation via webhooks - **Tools** - API proxies with authentication handling ## Next Steps Once you're set up: - [Discover RDAs](/hub/guides/users/discovering-rdas) in the marketplace - [Understand pricing](/hub/guides/users/understanding-pricing) and model tiers - [Create your own RDA](/hub/guides/creators/creating-prompt) to monetize ================================================================================ # Page: /en/hub/get-started/run-first-rda # Source: src/content/en/hub/get-started/run-first-rda.mdx ================================================================================ # Run Your First RDA This guide walks you through running your first RDA on xpay✦ Hub. ## Prerequisites Before running an RDA: 1. [Create an account](/hub/get-started/create-account) 2. [Fund your wallet](/hub/get-started/fund-wallet) with USDC ## Step 1: Browse the Marketplace 1. Go to [Explore](https://hub.xpay.sh/explore) 2. Browse available RDAs or use filters: - **Type** - Prompt, Agent, or Tool - **Price** - Free, under $0.05, under $0.10 - **Verified** - Show only verified RDAs ## Step 2: Select an RDA Click on any RDA card to view its detail page: - **Description** - What the RDA does - **Pricing** - Cost per run - **Stats** - Total runs, rating, success rate - **Creator** - Who built this RDA ## Step 3: Configure Inputs Each RDA has an input form based on its schema: ### For Prompts 1. Fill in the required text fields 2. Select a **Model Tier**: - Fast ($0.02) - Quick responses - Balanced ($0.05) - Best quality/speed - Reasoning ($0.10) - Complex analysis 3. Review the estimated cost ### For Agents/Tools 1. Fill in the required fields 2. Review the fixed price per run ## Step 4: Run the RDA 1. Click the **Run** button 2. Confirm the transaction (first time only) 3. Wait for execution (typically 2-30 seconds) ## Step 5: View Results Results appear in the console panel: - **Prompts** - Markdown-formatted text output - **Agents** - Status updates and final result - **Tools** - JSON response data ### Actions - **Copy** - Copy output to clipboard - **Download** - Save as file - **Share** - Share result link ## Example: Running a Prompt RDA Let's run the "Research Report Generator" RDA: 1. Go to the RDA page 2. Fill in the form: - **Topic**: Competitor Analysis - **Industry**: SaaS - **Depth**: Comprehensive 3. Select **Balanced** tier ($0.05) 4. Click **Run** 5. View generated report in the output ## Viewing Run History See all your past runs at [Account > History](https://hub.xpay.sh/account/history): - Run ID and timestamp - RDA name and type - Cost and status - Link to view full output ## Troubleshooting ### "Insufficient Balance" Your wallet doesn't have enough USDC: - [Fund your wallet](/hub/get-started/fund-wallet) - Check for locked funds in pending transactions ### "RDA Not Found" The RDA may have been removed or unpublished: - Try a different RDA from the [marketplace](https://hub.xpay.sh/explore) ### "Execution Error" The RDA encountered an error during execution: - Check your inputs are valid - Try running again - Contact support if the issue persists ## Next Steps - [Discover more RDAs](/hub/guides/users/discovering-rdas) - [Understand pricing](/hub/guides/users/understanding-pricing) - [Create your own RDA](/hub/guides/creators/creating-prompt) ================================================================================ # Page: /en/hub/get-started/what-are-rdas # Source: src/content/en/hub/get-started/what-are-rdas.mdx ================================================================================ # What are RDAs? RDAs are **Runnable Digital Assets** - AI capabilities packaged for instant execution with micropayments. ## The Three RDA Types ### Prompts Prompts are LLM-based RDAs that generate text using large language models. **Features:** - Choose from multiple model tiers (Fast, Balanced, Reasoning) - Input schema defines what information you provide - Output is typically markdown-formatted text - Option to purchase the prompt source code **Example Use Cases:** - Research and analysis reports - Content generation and copywriting - Technical documentation - Strategy and planning documents **Pricing:** $0.02 - $0.10 per run depending on model tier ### Agents Agents are workflow orchestrators that execute multi-step tasks via webhooks. **Features:** - Define webhook endpoints for execution - Support for async polling for long-running tasks - Chain multiple actions together - Handle complex automation workflows **Example Use Cases:** - Lead enrichment and research - Multi-platform content publishing - Data aggregation pipelines - Scheduled monitoring tasks **Pricing:** Custom per-run pricing set by creator ### Tools Tools are API proxies that wrap external services with payment handling. **Features:** - Wrap any HTTP API endpoint - Handle authentication (API key, Bearer, Basic) - Request/response transformation - Rate limiting and error handling **Example Use Cases:** - Data queries and lookups - External service integrations - Analytics and reporting - Third-party API access **Pricing:** Custom per-run pricing set by creator ## Model Tiers (For Prompts) When running prompt RDAs, you can choose from different model tiers: | Tier | Price | Best For | Models | |------|-------|----------|--------| | **Fast** | $0.02/run | Quick responses, simple tasks | GPT-4o Mini, Claude 3 Haiku, Llama 8B | | **Balanced** | $0.05/run | Best quality/speed tradeoff | GPT-4o, Claude 3.5 Sonnet, Llama 70B | | **Reasoning** | $0.10/run | Complex analysis, multi-step reasoning | o1-preview, Claude 3 Opus, Llama 405B | ## Next Steps - [Create your account](/hub/get-started/create-account) - [Fund your wallet](/hub/get-started/fund-wallet) - [Run your first RDA](/hub/get-started/run-first-rda) ================================================================================ # Page: /en/hub/guides/creators/creating-agent # Source: src/content/en/hub/guides/creators/creating-agent.mdx ================================================================================ # Creating an Agent This guide walks you through creating an Agent RDA for workflow automation. ## What is an Agent RDA? An Agent RDA orchestrates multi-step workflows by communicating with external services via webhooks. ## Prerequisites - xpay✦ Hub account - Webhook endpoint (n8n, Make, custom server) - Understanding of HTTP APIs ## Step 1: Set Up Your Webhook ### Using n8n 1. Create a new workflow in n8n 2. Add a **Webhook** trigger node 3. Configure to receive POST requests 4. Copy the webhook URL ### Webhook Payload Your endpoint will receive: ```json { "run_id": "run_abc123", "rda_id": "rda_xyz", "rda_slug": "my-agent", "rda_name": "My Agent", "inputs": { "field1": "value1", "field2": "value2" }, "user_id": "did:privy:xxx", "timestamp": 1702000000000 } ``` ### Response Format Return results as JSON: ```json { "status": "success", "output": "Your result here", "metadata": { "steps_completed": 3, "duration_ms": 5000 } } ``` ## Step 2: Define Your RDA ### Basic Information - **Name** - Clear, action-oriented title - **Slug** - URL-friendly identifier - **Description** - What the agent does - **Tags** - Relevant keywords for discovery ## Step 3: Configure Agent Settings ```typescript const agentConfig = { webhookUrl: 'https://your-n8n.com/webhook/xxx', webhookMethod: 'POST', webhookHeaders: { 'X-Custom-Header': 'value' }, timeoutSeconds: 60, maxRetries: 3, retryDelayMs: 1000, // For async/long-running tasks pollUrl: 'https://your-n8n.com/poll/xxx', pollIntervalMs: 2000 } ``` ### Configuration Options | Option | Description | Default | |--------|-------------|---------| | `webhookUrl` | Endpoint to call | Required | | `webhookMethod` | HTTP method | POST | | `webhookHeaders` | Custom headers | {} | | `timeoutSeconds` | Max execution time | 60 | | `maxRetries` | Retry attempts | 3 | | `pollUrl` | Async polling endpoint | null | | `pollIntervalMs` | Polling interval | 2000 | ## Step 4: Design Input Schema Define inputs users will provide: ```typescript const inputSchema = [ { name: 'targetCompany', label: 'Company Name', type: 'text', required: true, placeholder: 'Acme Inc' }, { name: 'action', label: 'Action', type: 'select', required: true, options: ['research', 'analyze', 'report'] }, { name: 'depth', label: 'Research Depth', type: 'number', required: false, default: 3 } ] ``` ## Step 5: Handle Async Workflows For long-running tasks, use polling: ### Initial Response ```json { "status": "pending", "job_id": "job_123", "message": "Processing started" } ``` ### Poll Endpoint The poll endpoint is called until completion: ```json { "status": "completed", "output": "Final results here", "metadata": {...} } ``` ### Status Values - `pending` - Still processing - `completed` - Success, results ready - `failed` - Error occurred ## Step 6: Set Pricing Agents use custom pricing: ```typescript const pricing = { model: 'per-run', amount: 0.10, // $0.10 per run currency: 'USDC' } ``` Consider: - Your infrastructure costs - External API costs - Execution time - Value delivered ## Step 7: Testing Before publishing: 1. **Test the webhook** - Ensure it handles all inputs 2. **Test timeouts** - Verify behavior on slow responses 3. **Test errors** - Handle failures gracefully 4. **Test polling** - For async workflows ## Example: Lead Research Agent ```typescript // RDA Configuration { name: 'Lead Research Agent', slug: 'lead-research', type: 'agent', agentConfig: { webhookUrl: 'https://n8n.example.com/webhook/lead-research', webhookMethod: 'POST', timeoutSeconds: 120, pollUrl: 'https://n8n.example.com/poll/lead-research', pollIntervalMs: 5000 }, inputSchema: [ { name: 'companyName', label: 'Company to Research', type: 'text', required: true }, { name: 'researchDepth', label: 'Research Depth', type: 'select', options: ['quick', 'standard', 'deep'], default: 'standard' } ], pricing: { model: 'per-run', amount: 0.15, currency: 'USDC' } } ``` ## Best Practices ### Webhook Design - Use authentication headers - Validate incoming payloads - Return meaningful errors - Log all requests ### Error Handling - Return clear error messages - Include error codes - Provide recovery suggestions ### Performance - Optimize for speed - Use async for long tasks - Set appropriate timeouts ## Next Steps - [Creating a Tool](/hub/guides/creators/creating-tool) - [Input/Output Schemas](/hub/guides/creators/input-output-schemas) - [Pricing Your RDA](/hub/guides/creators/pricing-your-rda) ================================================================================ # Page: /en/hub/guides/creators/creating-prompt # Source: src/content/en/hub/guides/creators/creating-prompt.mdx ================================================================================ # Creating a Prompt This guide walks you through creating your first Prompt RDA. ## What is a Prompt RDA? A Prompt RDA uses large language models (LLMs) to generate text based on user inputs and a prompt template. ## Prerequisites - xpay✦ Hub account - Understanding of prompt engineering - Ideas for valuable AI capabilities ## Step 1: Define Your RDA ### Basic Information - **Name** - Clear, descriptive title (e.g., "Competitor Analysis Report") - **Slug** - URL-friendly identifier (e.g., "competitor-analysis-report") - **Description** - What the RDA does (1-2 sentences) - **Long Description** - Detailed explanation (optional) ### Tags Add relevant tags for discoverability: - Function tags: "analysis", "generation", "research", "planning" - Industry tags: "saas", "marketing", "sales" ## Step 2: Design Your Input Schema Define what users need to provide: ```typescript const inputSchema = [ { name: 'companyName', label: 'Company Name', type: 'text', required: true, placeholder: 'Acme Corp', description: 'The company to analyze' }, { name: 'analysisDepth', label: 'Analysis Depth', type: 'select', required: true, options: ['basic', 'detailed', 'comprehensive'] }, { name: 'focusAreas', label: 'Focus Areas', type: 'text', required: false, placeholder: 'pricing, features, positioning' } ] ``` ### Field Types | Type | Description | Use For | |------|-------------|---------| | `text` | Single-line input | Short text, names | | `textarea` | Multi-line input | Long text, descriptions | | `number` | Numeric input | Quantities, limits | | `select` | Dropdown | Fixed options | | `checkbox` | Boolean toggle | Flags, options | | `url` | URL input | Links, endpoints | | `file` | File upload | Documents | ## Step 3: Write Your Prompt Template Create the prompt that will be sent to the LLM: ``` You are an expert business analyst. Analyze the company {{companyName}} with {{analysisDepth}} depth. {{#if focusAreas}} Focus particularly on: {{focusAreas}} {{/if}} Provide: 1. Executive summary 2. Product/service overview 3. Competitive positioning 4. Strengths and weaknesses 5. Actionable recommendations Format your response in clear markdown with headers and bullet points. ``` ### Template Syntax - `{{variable}}` - Insert variable value - `{{#if var}}...{{/if}}` - Conditional sections - `{{#each items}}...{{/each}}` - Loop over arrays ### System Prompt (Optional) Add a system prompt for consistent behavior: ``` You are a business analyst with deep experience in market research, competitive analysis, and strategic consulting. ``` ## Step 4: Configure Models Select which models users can choose from: ```typescript const allowedModels = [ { id: 'gpt-4o-mini', name: 'GPT-4o Mini', tier: 'fast', pricePerRun: 0.02 }, { id: 'claude-3.5-sonnet', name: 'Claude 3.5 Sonnet', tier: 'balanced', pricePerRun: 0.05 }, { id: 'o1-preview', name: 'o1 Preview', tier: 'reasoning', pricePerRun: 0.10 } ] ``` ### Available Models **Fast Tier ($0.02)** - GPT-4o Mini - Claude 3 Haiku - Llama 3.1 8B - Gemini Flash **Balanced Tier ($0.05)** - GPT-4o - Claude 3.5 Sonnet - Llama 3.1 70B - Gemini Pro **Reasoning Tier ($0.10)** - o1-preview - Claude 3 Opus - Llama 3.1 405B ## Step 5: Add Examples Create pre-generated examples to showcase your RDA: ```typescript const examples = [ { id: 'ex_001', title: 'SaaS Competitor Analysis', inputs: { companyName: 'Salesforce', analysisDepth: 'detailed', focusAreas: 'pricing, enterprise features' }, output: '## Competitor Analysis\n\n...', model: 'claude-3.5-sonnet' } ] ``` ## Step 6: Set Pricing ### Per-Run Price Included in model tier pricing above. ### Source Code Price (Optional) Allow users to buy your prompt template: ```typescript const promptSourcePrice = 4.99 // USDC ``` ## Step 7: Submit for Review Before publishing: 1. **Test thoroughly** - Run with various inputs 2. **Check output quality** - Ensure consistent results 3. **Review pricing** - Compare to similar RDAs 4. **Add examples** - Show best use cases Submit your RDA for verification review. ## Best Practices ### Prompt Quality - Be specific about output format - Include examples in the prompt - Handle edge cases gracefully ### User Experience - Use clear field labels - Provide helpful descriptions - Show placeholder examples ### Pricing - Start competitive - Consider your costs - Offer value vs alternatives ## Next Steps - [Input/Output Schemas](/hub/guides/creators/input-output-schemas) - [Pricing Your RDA](/hub/guides/creators/pricing-your-rda) - [Publishing & Verification](/hub/guides/creators/publishing-verification) ================================================================================ # Page: /en/hub/guides/creators/creating-tool # Source: src/content/en/hub/guides/creators/creating-tool.mdx ================================================================================ # Creating a Tool This guide walks you through creating a Tool RDA that wraps external APIs. ## What is a Tool RDA? A Tool RDA acts as an API proxy, wrapping external services with payment handling and user-friendly inputs. ## Prerequisites - xpay✦ Hub account - API endpoint to wrap - API credentials (if required) ## Step 1: Choose an API to Wrap Good candidates for Tool RDAs: - **Data APIs** - Company data, market intelligence - **Enrichment APIs** - Lead enrichment, company lookup - **Analytics APIs** - Social metrics, usage data - **AI APIs** - Replicate, Hugging Face ## Step 2: Configure the Tool ```typescript const toolConfig = { apiEndpoint: 'https://api.example.com/v1/data', apiMethod: 'GET', // or POST, PUT, DELETE apiHeaders: { 'Content-Type': 'application/json' }, // Authentication authType: 'api_key', // 'none', 'api_key', 'bearer', 'basic' authConfig: { headerName: 'X-API-Key', // Key is stored securely, not in config }, // Optional transformations requestTransform: null, // Jinja2 template responseTransform: null, // JSONPath extraction // Rate limiting rateLimitPerMinute: 60 } ``` ### Authentication Types | Type | Description | Config | |------|-------------|--------| | `none` | No authentication | - | | `api_key` | API key in header | `headerName` | | `bearer` | Bearer token | - | | `basic` | Basic auth | `username`, `password` | ## Step 3: Design Input Schema Map user inputs to API parameters: ```typescript const inputSchema = [ { name: 'companyDomain', label: 'Company Domain', type: 'text', required: true, description: 'Company website domain to look up' }, { name: 'dataType', label: 'Data Type', type: 'select', required: true, options: ['company_info', 'contacts', 'financials'] } ] ``` ## Step 4: Request Transformation Transform user inputs into API request: ### URL Parameters ```typescript // Input: { companyDomain: 'acme.com', dataType: 'company_info' } // API URL: https://api.example.com/v1/company?domain=acme.com&type=company_info const requestTransform = ` domain={{ companyDomain }} &type={{ dataType }} ` ``` ### JSON Body ```typescript const requestTransform = ` { "query": "{{ query }}", "limit": {{ limit | default(10) }}, "filters": {{ filters | tojson }} } ` ``` ## Step 5: Response Transformation Extract relevant data from API response: ```typescript // JSONPath extraction const responseTransform = '$.result.data' // Or complex transformation const responseTransform = ` { "company": $.result.name, "employees": $.result.employeeCount, "industry": $.result.industry } ` ``` ## Step 6: Set Pricing Tools use custom pricing: ```typescript const pricing = { model: 'per-run', amount: 0.02, // $0.02 per API call currency: 'USDC' } ``` Factor in: - External API costs - Rate limit value - Data value ## Step 7: Handle Errors Define error handling: ```typescript // Common API errors to handle const errorMapping = { 401: 'API authentication failed', 429: 'Rate limit exceeded, try again later', 404: 'Resource not found', 500: 'External service error' } ``` ## Example: Company Lookup Tool ```typescript { name: 'Company Lookup', slug: 'company-lookup', type: 'tool', toolConfig: { apiEndpoint: 'https://api.clearbit.com/v2/companies/find', apiMethod: 'GET', authType: 'bearer', rateLimitPerMinute: 10 }, inputSchema: [ { name: 'domain', label: 'Company Domain', type: 'text', required: true, placeholder: 'example.com' } ], requestTransform: `domain={{ domain }}`, responseTransform: '$.company', pricing: { model: 'per-run', amount: 0.05, currency: 'USDC' } } ``` ## Storing API Credentials API keys are stored securely: 1. Go to Creator Dashboard 2. Navigate to Secrets 3. Add your API key 4. Reference in tool config Keys are: - Encrypted at rest - Never exposed to users - Injected at runtime ## Rate Limiting Configure rate limits: ```typescript const rateLimitConfig = { perMinute: 60, perHour: 1000, perDay: 10000 } ``` When limits are hit: - Request is queued - User sees wait time - Or error if exceeded ## Best Practices ### API Selection - Choose reliable APIs - Check rate limits - Verify pricing/costs - Test availability ### Input Design - Clear labels - Helpful descriptions - Sensible defaults - Input validation ### Error Messages - User-friendly errors - Actionable guidance - Don't expose internals ## Next Steps - [Input/Output Schemas](/hub/guides/creators/input-output-schemas) - [Pricing Your RDA](/hub/guides/creators/pricing-your-rda) - [Publishing & Verification](/hub/guides/creators/publishing-verification) ================================================================================ # Page: /en/hub/guides/creators/input-output-schemas # Source: src/content/en/hub/guides/creators/input-output-schemas.mdx ================================================================================ # Input/Output Schemas Define what data your RDA accepts and returns. ## Input Schema The input schema defines the form users fill out to run your RDA. ### Schema Structure ```typescript type InputSchema = { name: string // Field identifier (used in templates) label: string // Display label for users type: FieldType // Input type required: boolean // Is this field required? description?: string // Help text placeholder?: string // Placeholder text default?: any // Default value options?: string[] // For select fields min?: number // For number fields max?: number // For number fields pattern?: string // Regex validation }[] ``` ### Field Types #### text Single-line text input. ```typescript { name: 'companyDomain', label: 'Company Domain', type: 'text', required: true, placeholder: 'example.com', pattern: '^[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$' } ``` #### textarea Multi-line text input. ```typescript { name: 'description', label: 'Project Description', type: 'textarea', required: true, placeholder: 'Describe your project...' } ``` #### number Numeric input with optional range. ```typescript { name: 'limit', label: 'Result Limit', type: 'number', required: true, min: 1, max: 100, default: 10 } ``` #### select Dropdown selection. ```typescript { name: 'depth', label: 'Analysis Depth', type: 'select', required: true, options: ['quick', 'standard', 'comprehensive'], default: 'standard' } ``` #### checkbox Boolean toggle. ```typescript { name: 'includeMetadata', label: 'Include Metadata', type: 'checkbox', required: false, default: true } ``` #### url URL input with validation. ```typescript { name: 'apiEndpoint', label: 'API Endpoint', type: 'url', required: true, placeholder: 'https://api.example.com' } ``` #### file File upload (supported types vary). ```typescript { name: 'document', label: 'Upload Document', type: 'file', required: false, accept: '.pdf,.doc,.docx' } ``` ## Output Schema Define the structure of your RDA's output. ### Output Types ```typescript type OutputSchema = { type: 'markdown' | 'json' | 'text' | 'file' schema?: JSONSchema // For JSON type } ``` #### markdown Formatted text output (most common for prompts). ```typescript { type: 'markdown' } ``` #### json Structured data output. ```typescript { type: 'json', schema: { type: 'object', properties: { score: { type: 'number' }, issues: { type: 'array' }, recommendation: { type: 'string' } } } } ``` #### text Plain text output. ```typescript { type: 'text' } ``` ## Validation ### Built-in Validation Fields are validated automatically: - **Required** - Must have a value - **Type** - Must match field type - **Pattern** - Must match regex (if provided) - **Min/Max** - Must be within range ### Custom Validation Add patterns for specific formats: ```typescript // Domain pattern: '^[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$' // UUID pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' // URL pattern: '^https?://.*' // Email pattern: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$' ``` ## Examples ### Competitor Analysis ```typescript const schema = { inputs: [ { name: 'companyName', label: 'Company Name', type: 'text', required: true }, { name: 'industry', label: 'Industry', type: 'select', required: true, options: ['saas', 'fintech', 'ecommerce', 'healthcare'] }, { name: 'depth', label: 'Analysis Depth', type: 'select', required: true, options: ['quick', 'standard', 'comprehensive'], default: 'standard' } ], outputs: { type: 'markdown' } } ``` ### Data Lookup Tool ```typescript const schema = { inputs: [ { name: 'query', label: 'Search Query', type: 'text', required: true, placeholder: 'Company name or domain...' }, { name: 'limit', label: 'Result Limit', type: 'number', required: false, default: 10, min: 1, max: 100 } ], outputs: { type: 'json', schema: { type: 'object', properties: { results: { type: 'array' }, total: { type: 'number' } } } } } ``` ## Best Practices ### Input Design - **Clear labels** - Users should understand immediately - **Helpful descriptions** - Explain what's expected - **Sensible defaults** - Reduce friction - **Appropriate types** - Use select for fixed options ### Validation - **Required wisely** - Only require what's truly needed - **Validate formats** - Use patterns for specific data - **Show errors clearly** - Help users fix issues ### Output - **Consistent format** - Same structure every run - **Useful metadata** - Include timestamps, versions - **Error details** - Clear error messages ## Next Steps - [Pricing Your RDA](/hub/guides/creators/pricing-your-rda) - [Publishing & Verification](/hub/guides/creators/publishing-verification) ================================================================================ # Page: /en/hub/guides/creators/pricing-your-rda # Source: src/content/en/hub/guides/creators/pricing-your-rda.mdx ================================================================================ # Pricing Your RDA Set competitive pricing that reflects value and covers costs. ## Pricing Models ### Per-Run (Recommended) Fixed price per execution: ```typescript pricing: { model: 'per-run', amount: 0.05, currency: 'USDC' } ``` **Best for:** - Prompts with predictable costs - Tools with fixed API costs - Simple, consistent outputs ### Per-Token Cost based on input/output tokens: ```typescript pricing: { model: 'per-token', amount: 0.001, // per 1K tokens currency: 'USDC' } ``` **Best for:** - Variable-length prompts - Cost pass-through scenarios ### Per-Second Cost based on execution time: ```typescript pricing: { model: 'per-second', amount: 0.01, currency: 'USDC' } ``` **Best for:** - Long-running agents - Compute-intensive tasks ### Free No cost to run: ```typescript pricing: { model: 'free', amount: 0, currency: 'USDC' } ``` **Best for:** - Building reputation - Open source tools - Limited functionality demos ## Model Tiers (Prompts Only) For prompt RDAs, users choose model tiers: | Tier | Your Revenue | Platform Fee | |------|-------------|--------------| | Fast ($0.02) | ~$0.018 | ~$0.002 | | Balanced ($0.05) | ~$0.045 | ~$0.005 | | Reasoning ($0.10) | ~$0.09 | ~$0.01 | ## Pricing Strategy ### Cost Calculation Factor in your costs: 1. **API Costs** - LLM API costs (for prompts) - External API costs (for tools) - Infrastructure costs (for agents) 2. **Time Investment** - Development time - Maintenance effort - Support time 3. **Value Delivered** - Time saved for users - Quality of output - Uniqueness of capability ### Market Research Check comparable RDAs: 1. Browse similar RDAs in marketplace 2. Note their pricing 3. Consider your differentiators 4. Price competitively ### Starting Point Suggested starting prices: | Type | Simple | Medium | Complex | |------|--------|--------|---------| | Prompts | $0.02-0.05 | $0.05-0.10 | $0.10+ | | Agents | $0.05-0.10 | $0.10-0.25 | $0.25+ | | Tools | $0.01-0.03 | $0.03-0.10 | $0.10+ | ## Source Code Pricing (Prompts) Offer your prompt template for sale: ```typescript promptSourcePrice: 4.99 // One-time purchase ``` ### Pricing Factors - **Uniqueness** - How novel is your approach? - **Complexity** - How much engineering went in? - **Value** - How much would users save? ### Suggested Prices | Complexity | Price | |------------|-------| | Simple | $1.99 - $4.99 | | Medium | $4.99 - $9.99 | | Complex | $9.99 - $24.99 | ## Revenue & Fees ### Creator Revenue You receive the majority of each payment: - **Platform fee**: ~10% - **Your revenue**: ~90% ### Payment Timing - **Instant settlement** - Paid immediately - **USDC** - To your connected wallet - **No minimums** - Withdraw anytime ## Optimization Tips ### Price Testing 1. Start with competitive pricing 2. Monitor run volume 3. Adjust based on demand 4. Consider A/B testing ### Value Perception - **Quality descriptions** - Explain the value - **Good examples** - Show what users get - **Verified badge** - Build trust ### Volume vs. Margin - **Lower price** - More runs, lower margin - **Higher price** - Fewer runs, higher margin - **Find balance** - Test and optimize ## Analytics Track your RDA performance: - **Total runs** - How often it's used - **Revenue** - Earnings over time - **Rating** - User satisfaction - **Success rate** - Reliability Use analytics to inform pricing decisions. ## Common Mistakes ### Pricing Too High - Users won't try it - No reviews/ratings - Low discoverability ### Pricing Too Low - Unsustainable - Perceived as low quality - Race to bottom ### Ignoring Costs - API costs add up - Infrastructure costs - Support time ## Next Steps - [Publishing & Verification](/hub/guides/creators/publishing-verification) - RDA Analytics (coming soon) ================================================================================ # Page: /en/hub/guides/creators/publishing-verification # Source: src/content/en/hub/guides/creators/publishing-verification.mdx ================================================================================ # Publishing & Verification Get your RDA live in the marketplace. ## RDA Status RDAs have four status levels: | Status | Description | Visibility | |--------|-------------|------------| | **Draft** | Work in progress | Only you | | **Published** | Live in marketplace | Everyone | | **Archived** | Hidden from search | Direct link only | | **Deprecated** | Being phased out | Shows warning | ## Publishing Process ### Step 1: Complete Your RDA Ensure you have: - [ ] Name and description - [ ] Tags for discovery - [ ] Input schema defined - [ ] Pricing configured - [ ] At least one example (recommended) ### Step 2: Test Thoroughly Before publishing: 1. **Run your RDA** multiple times 2. **Try edge cases** - empty inputs, long inputs 3. **Check output quality** - consistent and useful 4. **Verify pricing** - cost matches value ### Step 3: Submit for Publishing 1. Go to your RDA in Creator Dashboard 2. Click **Publish** 3. Review the checklist 4. Confirm submission Your RDA is now live! ## Verification Verified RDAs get a badge and better visibility. ### Benefits of Verification - **Verified badge** - Builds user trust - **Featured eligibility** - Can be featured - **Better ranking** - Higher in search results - **Collection inclusion** - Can join curated collections ### Verification Criteria Our team reviews: 1. **Quality** - Output meets expectations 2. **Safety** - No harmful content 3. **Reliability** - Consistent performance 4. **Pricing** - Fair and transparent 5. **Documentation** - Clear description ### How to Get Verified 1. Publish your RDA 2. Maintain good performance 3. Get positive user ratings 4. Apply for verification We review applications weekly. ## After Publishing ### Monitor Performance Track your RDA's metrics: - **Runs** - Daily/weekly/monthly - **Revenue** - Earnings over time - **Rating** - User feedback - **Success rate** - Reliability ### Respond to Feedback - Check user ratings - Address common issues - Update based on feedback ### Update Your RDA You can update published RDAs: 1. Make changes in Creator Dashboard 2. Test the changes 3. Save to publish updates Users see the latest version. ## Moderation ### Content Policy RDAs must not: - Generate harmful content - Facilitate illegal activities - Violate intellectual property - Spread misinformation - Compromise user privacy ### Enforcement Violations result in: 1. **Warning** - First offense, fix required 2. **Unpublish** - RDA removed from marketplace 3. **Ban** - Repeat offenders banned ### Appeals If your RDA is moderated: 1. Review the violation notice 2. Make required changes 3. Submit for re-review ## Best Practices ### Before Publishing - **Test extensively** - Various inputs and scenarios - **Write clear descriptions** - What it does, who it's for - **Add examples** - Show expected outputs - **Price fairly** - Research competitors ### After Publishing - **Monitor metrics** - Track performance - **Respond to issues** - Fix problems quickly - **Update regularly** - Improve over time - **Engage community** - Discord, forums ### Building Reputation - **Start with quality** - First impressions matter - **Be consistent** - Reliable performance - **Support users** - Help with issues - **Iterate** - Continuous improvement ## FAQ ### How long does verification take? Typically 3-5 business days. ### Can I unpublish an RDA? Yes, set status to Archived or Draft. ### What if my RDA breaks? Update immediately or set to Draft while fixing. ### Can I transfer ownership? Not currently supported. Contact support for special cases. ## Next Steps - Monitor your RDA in Creator Dashboard - Join [Discord](https://discord.gg/xpay) for creator community - Apply for verification when ready ================================================================================ # Page: /en/hub/guides/users/discovering-rdas # Source: src/content/en/hub/guides/users/discovering-rdas.mdx ================================================================================ # Discovering RDAs Learn how to find the right RDAs for your needs in the xpay✦ Hub marketplace. ## The Marketplace Visit [hub.xpay.sh/explore](https://hub.xpay.sh/explore) to browse all available RDAs. ### Grid View Each RDA card displays: - **Cover Image** - Visual preview or code snippet - **Name** - RDA title - **Type Badge** - Prompt, Agent, or Tool - **Price** - Cost per run - **Stats** - Total runs, rating - **Creator** - Owner name and verification status ### Filtering Options #### By Type Filter by RDA type: - **Prompts** - LLM-based text generation - **Agents** - Workflow automation - **Tools** - API proxies #### By Price Filter by price range: - **Free** - No cost to run - **Under $0.05** - Budget-friendly - **Under $0.10** - Standard pricing - **All prices** - Show everything #### By Verification - **Verified Only** - Show only verified RDAs - **All** - Include unverified RDAs ### Sorting Options Sort results by: - **Trending** - Most popular recently - **Newest** - Recently published - **Price: Low to High** - **Price: High to Low** - **Rating** - Highest rated ## Search Use the search bar to find RDAs by: - Name - Description keywords - Tags - Creator name ## RDA Detail Page Click any RDA to view its detail page: ### Information - **Full description** - What the RDA does - **Input schema** - What inputs are required - **Output format** - What you'll receive - **Code snippet** - Sample code (if provided) ### Stats - **Total Runs** - How many times it's been executed - **Average Rating** - User ratings (1-5 stars) - **Success Rate** - Percentage of successful runs - **Average Latency** - Typical response time ### Creator - **Name** - Creator's display name - **Verified Badge** - xpay✦ verified creator - **Other RDAs** - More from this creator ## Featured & Collections ### Featured RDAs Hand-picked RDAs highlighted on the homepage and explore page. ### Collections Curated bundles of related RDAs: - **Research Toolkit** - Analysis and research RDAs - **Content Generation** - Writing and creative tools - **Data & Analytics** - Data access and insights ## Next Steps - [Running Prompts](/hub/guides/users/running-prompts) - [Running Agents](/hub/guides/users/running-agents) - [Running Tools](/hub/guides/users/running-tools) ================================================================================ # Page: /en/hub/guides/users/managing-wallet # Source: src/content/en/hub/guides/users/managing-wallet.mdx ================================================================================ # Managing Your Wallet Your xpay✦ wallet holds USDC for running RDAs. ## Wallet Overview Access your wallet at [Account > Wallet](https://hub.xpay.sh/account/wallet). ### Wallet Information - **Address** - Your Base network wallet address - **Balance** - Total USDC in your wallet - **Available** - Amount available for spending - **Locked** - Amount in pending transactions ## Depositing Funds ### From External Wallet 1. Copy your xpay✦ wallet address 2. Send USDC on Base network to this address 3. Transaction confirms in ~2 seconds ### Supported Methods - **MetaMask** - Send directly - **Coinbase Wallet** - Send directly - **Exchange** - Withdraw to Base network - **Bridge** - Bridge from other networks ## Withdrawing Funds ### To External Wallet 1. Go to Wallet page 2. Click **Withdraw** 3. Enter destination address 4. Enter amount 5. Confirm transaction ### Fees - Network gas fees apply - No platform withdrawal fee ## Spending Controls ### Global Allowance Set a maximum spending limit: - **Default** - $10 initial allowance - **Adjustable** - Change anytime - **Per-session** - Resets on login ### Per-Transaction Limit Set maximum cost per RDA run: - Prevents expensive accidents - Configurable by you - Applies to all RDA types ## Transaction History View all transactions at [Account > History](https://hub.xpay.sh/account/history). ### Transaction Types - **Deposit** - USDC added to wallet - **Withdrawal** - USDC sent out - **RDA Run** - Cost of running an RDA - **Refund** - Failed run refund ### Details Each transaction shows: - Date and time - Transaction type - Amount - Status (pending, completed, failed) - Transaction hash (for on-chain txs) ## Security ### Non-Custodial xpay✦ is non-custodial: - You control your private keys - Funds are in your wallet, not ours - Export keys via Privy if needed ### Best Practices - Don't share your wallet address publicly - Only deposit what you plan to spend - Monitor transaction history regularly ## API Access ### Check Balance ```bash curl -X GET https://api.xpay.sh/hub/wallet/balance \ -H "Authorization: Bearer YOUR_TOKEN" ``` ### Record Deposit ```bash curl -X POST https://api.xpay.sh/hub/wallet/deposit \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{"amount": 10.00, "transactionHash": "0x..."}' ``` ## Troubleshooting ### Balance Not Updating - Wait for blockchain confirmation - Refresh the page - Check transaction on Base explorer ### Transaction Failed - Check you have enough balance - Verify the destination address - Try again with lower amount ## Next Steps - [Understanding Pricing](/hub/guides/users/understanding-pricing) - [Run Your First RDA](/hub/get-started/run-first-rda) ================================================================================ # Page: /en/hub/guides/users/running-agents # Source: src/content/en/hub/guides/users/running-agents.mdx ================================================================================ # Running Agents Agents are workflow orchestration RDAs that execute multi-step tasks. ## How Agents Work 1. You provide input parameters 2. The agent sends data to a webhook endpoint 3. External workflow (n8n, Make, etc.) executes 4. Results are returned to you ## Agent Features ### Webhooks Agents communicate via HTTP webhooks: - **POST requests** - Send data to external services - **Custom headers** - Authentication and metadata - **Payload transformation** - Format inputs for the endpoint ### Async Execution For long-running tasks: - **Polling** - Agent checks for completion periodically - **Timeouts** - Up to 180 seconds for complex workflows - **Retries** - Automatic retry on transient failures ### Multi-Step Workflows Agents can orchestrate complex flows: - Sequential task execution - Parallel processing - Conditional logic - Data aggregation ## Running an Agent ### Step 1: Review Requirements Check the agent's input schema: - Required fields (marked with *) - Field types and formats - Example values ### Step 2: Fill Inputs Complete the input form: - Text inputs for queries/parameters - Numbers for quantities/limits - URLs for target resources - File uploads if supported ### Step 3: Execute Click **Run Agent**: 1. Inputs are sent to the webhook 2. Progress updates appear in console 3. Final results are displayed ### Step 4: Monitor Progress Watch the console for: - Status updates - Intermediate results - Final output ## Agent Output ### Console View Results displayed in terminal-style output: - Timestamped log entries - Status indicators (running, success, error) - Final result payload ### Structured Data Agents often return JSON data: ```json { "status": "success", "result": { "analysis": "...", "recommendations": ["..."] }, "metadata": { "duration": 15000, "steps_completed": 3 } } ``` ## Common Agent Use Cases ### Lead Enrichment - Research company information - Find contact details - Aggregate from multiple sources ### Data Pipelines - Aggregate data from multiple sources - Transform and clean data - Store results in databases ### Content Publishing - Generate content with LLMs - Format for different platforms - Schedule and publish ### Monitoring - Watch for specific events - Alert on conditions - Track activities ## Timeout and Retries ### Timeouts - Default: 60 seconds - Maximum: 180 seconds - Shown in RDA details ### Retries - Automatic retry on network errors - Configurable retry count - Exponential backoff ## Error Handling ### Common Errors - **Timeout**: Workflow took too long - **Webhook Error**: External service unavailable - **Invalid Input**: Data format incorrect ### What to Do 1. Check your inputs are valid 2. Try running again (transient errors) 3. Contact the creator for persistent issues ## Next Steps - [Running Tools](/hub/guides/users/running-tools) - [Managing Your Wallet](/hub/guides/users/managing-wallet) ================================================================================ # Page: /en/hub/guides/users/running-prompts # Source: src/content/en/hub/guides/users/running-prompts.mdx ================================================================================ # Running Prompts Prompts are LLM-based RDAs that generate text using AI models. ## How Prompts Work 1. You provide input data 2. The prompt template is filled with your inputs 3. The LLM generates a response 4. You receive formatted output ## Running a Prompt ### Step 1: Select a Model Tier Choose the AI model tier based on your needs: | Tier | Price | Best For | Response Time | |------|-------|----------|---------------| | **Fast** | $0.02 | Simple tasks, quick answers | 2-5 seconds | | **Balanced** | $0.05 | Most use cases, quality output | 5-15 seconds | | **Reasoning** | $0.10 | Complex analysis, deep thinking | 15-60 seconds | ### Step 2: Fill Input Fields Complete the input form based on the RDA's schema: - **Text fields** - Enter text or keywords - **Select fields** - Choose from dropdown options - **Number fields** - Enter numeric values - **URL fields** - Paste valid URLs - **File fields** - Upload documents (if supported) ### Step 3: Review Cost The estimated cost is shown based on: - Selected model tier - RDA base price - Expected output length ### Step 4: Execute Click **Run Prompt** to execute. The button shows: - Loading state during execution - Cost that will be deducted ## Viewing Output ### Output Panel Results appear in the console tab: - **Markdown formatted** - Headers, lists, code blocks - **Copy button** - Copy to clipboard - **Download button** - Save as .md file ### Examples Tab View pre-generated examples: - See what outputs look like before running - Learn from different input combinations - Understand the RDA's capabilities ## Buying Prompt Source Some prompts offer source code purchase: 1. Click **Unlock Source** ($X.XX) 2. Pay the one-time fee 3. Access the prompt template 4. Use in your own applications ## Tips for Best Results ### Be Specific Provide detailed, specific inputs: - Bad: "Write a report" - Good: "Write a competitive analysis report for B2B SaaS CRM products" ### Choose the Right Tier - **Fast**: Simple formatting, short answers - **Balanced**: Most tasks, good quality - **Reasoning**: Complex analysis, multi-step thinking ### Review Examples First Check the Examples tab to understand: - Expected input format - Output quality and format - Best practices for inputs ## Common Prompt Types ### Analysis Prompts Analyze data and provide insights: - Competitor analysis - Market research - Document summarization ### Generation Prompts Create new content: - Blog posts and articles - Technical documentation - Marketing copy ### Planning Prompts Create actionable plans: - Project roadmaps - Strategy documents - Implementation checklists ## Next Steps - [Running Agents](/hub/guides/users/running-agents) - [Running Tools](/hub/guides/users/running-tools) - [Understanding Pricing](/hub/guides/users/understanding-pricing) ================================================================================ # Page: /en/hub/guides/users/running-tools # Source: src/content/en/hub/guides/users/running-tools.mdx ================================================================================ # Running Tools Tools are API proxy RDAs that wrap external services with payment handling. ## How Tools Work 1. You provide input parameters 2. The tool calls an external API 3. The response is transformed and returned 4. Payment is handled automatically ## Tool Features ### API Wrapping Tools wrap existing APIs: - **HTTP methods** - GET, POST, PUT, DELETE - **Authentication** - API keys, Bearer tokens, Basic auth - **Headers** - Custom request headers ### Request Transformation Inputs are transformed before sending: - Variable substitution - JSON formatting - Query parameter building ### Response Transformation API responses are processed: - Extract relevant fields - Format output - Handle errors gracefully ## Running a Tool ### Step 1: Review the Schema Check what inputs the tool requires: - Endpoint-specific parameters - Required vs optional fields - Data format expectations ### Step 2: Provide Inputs Fill in the input form: - **Query parameters** - For search/filter - **Resource identifiers** - For lookups - **Data payloads** - For POST requests ### Step 3: Execute Click **Run Tool**: 1. Request is built from your inputs 2. Tool calls the external API 3. Response is processed 4. Results displayed in console ## Tool Output ### JSON Response Most tools return structured JSON: ```json { "data": { "id": "...", "results": [...], "metadata": {...} }, "metadata": { "source": "api-provider", "timestamp": "2024-01-01T00:00:00Z" } } ``` ### Formatted Display Tools may provide formatted views: - Tables for lists - Charts for data visualization - Markdown for text ## Common Tool Categories ### Data Lookup - Company information - Contact enrichment - Market data ### Analytics - Social media metrics - Usage analytics - Engagement tracking ### External Services - AI model inference - Document processing - Data aggregation ### Integrations - CRM data access - Marketing platform APIs - Communication services ## Rate Limits Tools may have rate limits: - **Per-minute limits** - Maximum calls per minute - **Daily limits** - Maximum calls per day - **Shown in details** - Check before running ## Authentication Tools handle auth automatically: - **API Key** - Stored securely, injected in requests - **Bearer Token** - OAuth-style authentication - **Basic Auth** - Username/password You don't need to provide credentials - the tool creator configures these. ## Error Responses ### API Errors - **Rate Limited** - Too many requests - **Not Found** - Resource doesn't exist - **Unauthorized** - API credentials invalid ### What to Do 1. Check your inputs are valid 2. Wait and retry for rate limits 3. Try an alternative tool if persistent ## Next Steps - [Managing Your Wallet](/hub/guides/users/managing-wallet) - [Understanding Pricing](/hub/guides/users/understanding-pricing) ================================================================================ # Page: /en/hub/guides/users/understanding-pricing # Source: src/content/en/hub/guides/users/understanding-pricing.mdx ================================================================================ # Understanding Pricing Learn how pricing works on xpay✦ Hub. ## Pricing Models RDAs can use different pricing models: ### Per-Run Pricing Fixed cost per execution: - **Example**: $0.05 per run - **Predictable** - Know the cost upfront - **Most common** - Used by most RDAs ### Per-Token Pricing Cost based on input/output tokens: - **Example**: $0.001 per 1K tokens - **Variable** - Depends on content length - **Used by**: Some prompt RDAs ### Per-Second Pricing Cost based on execution time: - **Example**: $0.01 per second - **Variable** - Depends on task complexity - **Used by**: Some agent RDAs ### Free No cost to run: - **Good for**: Trying new RDAs - **May have**: Usage limits - **Creators use for**: Building reputation ## Model Tiers (Prompts) Prompt RDAs offer different model tiers: | Tier | Price | Models | Best For | |------|-------|--------|----------| | **Fast** | $0.02/run | GPT-4o Mini, Claude Haiku, Llama 8B | Simple tasks | | **Balanced** | $0.05/run | GPT-4o, Claude 3.5 Sonnet, Llama 70B | Most use cases | | **Reasoning** | $0.10/run | o1-preview, Claude Opus, Llama 405B | Complex analysis | ## Cost Estimation ### Before Running The RDA page shows: - **Base price** - Minimum cost - **Model tier prices** - For prompts - **Estimated cost** - Based on typical usage ### During Execution The Run button shows: - **Exact cost** - What will be charged - **Your balance** - Current available funds ## What Affects Cost ### For Prompts - **Model tier** - Fast < Balanced < Reasoning - **Input length** - More text = higher cost - **Output length** - Longer responses cost more ### For Agents - **Base price** - Set by creator - **Execution time** - For time-based pricing - **External API costs** - Built into price ### For Tools - **Base price** - Set by creator - **API rate limits** - May affect pricing - **Data volume** - For data-heavy tools ## Payment Flow ### How It Works 1. **Lock** - Amount is locked when you click Run 2. **Execute** - RDA runs 3. **Success** - Locked amount is deducted 4. **Failure** - Locked amount is released back ### Failed Runs If an RDA fails: - You're NOT charged - Locked funds are released - Balance is restored immediately ## Creator Earnings When you run an RDA: - **Creator receives** - Majority of the payment - **Platform fee** - Small percentage - **Instant settlement** - Creators paid immediately ## Tips for Cost Optimization ### Choose the Right Tier - Use **Fast** for simple tasks - Use **Balanced** for most work - Save **Reasoning** for complex analysis ### Test with Examples - Check Examples tab first - Understand expected costs - Start with simpler inputs ### Monitor Spending - Set spending limits - Review transaction history - Track monthly spending ## Comparing Costs ### Traditional AI APIs | Service | Cost per 1K tokens | |---------|-------------------| | OpenAI GPT-4 | ~$0.03 | | Anthropic Claude | ~$0.015 | | Direct API | Variable | ### xpay✦ Hub - **Bundled pricing** - No token counting - **Predictable costs** - Fixed per-run prices - **No API keys** - Use immediately ## Next Steps - [Model Tiers Deep Dive](/hub/topics/model-tiers) - [Pricing Models Explained](/hub/topics/pricing-models) ================================================================================ # Page: /en/hub/index # Source: src/content/en/hub/index.mdx ================================================================================ # Welcome to xpay✦ Hub xpay✦ Hub is a **marketplace for AI capabilities** - Runnable Digital Assets (RDAs) that you can run instantly with USDC micropayments. Think of it as an App Store where every app is an AI capability you can run with a single click. ## What is an RDA? An RDA (Runnable Digital Asset) is a packaged AI capability that you can run with a single click. RDAs come in three types: | Type | Description | Example Use Cases | |------|-------------|-------------------| | **Prompts** | LLM-based text generation | Research reports, content generation, analysis | | **Agents** | Workflow orchestration via webhooks | Automated tasks, multi-step workflows, data pipelines | | **Tools** | API proxies with payment handling | Data queries, external service integrations, analytics | ## Quick Start Get started in 3 simple steps: 1. **Connect Wallet** - Sign in with Privy (email, wallet, or social) 2. **Fund Your Account** - Deposit USDC to your wallet 3. **Run an RDA** - Find and execute any RDA from the marketplace [Get Started](/hub/get-started) ## For Creators Build and monetize your own AI capabilities: - Create Prompts, Agents, or Tools - Set flexible pricing (per-run, per-token, or free) - Earn USDC every time someone runs your RDA - Track performance with detailed analytics [Creator Guide](/hub/guides/creators/creating-prompt) ## Payment Infrastructure xpay✦ Hub uses the xpay✦ payment infrastructure for secure USDC micropayments on Base network: - **Instant** - ~2 second settlement - **Transparent** - Pay only for what you use - **Non-custodial** - You control your funds Learn more about [xpay✦ infrastructure](/getting-started). ## Links - [Marketplace](https://hub.xpay.sh/explore) - Browse and run RDAs - [GitHub](https://github.com/xpaysh) - Open source projects - [Discord](https://discord.gg/xpay) - Join the community - [Twitter](https://x.com/xpaysh) - Follow for updates ================================================================================ # Page: /en/hub/reference/create-rda # Source: src/content/en/hub/reference/create-rda.mdx ================================================================================ # Create an RDA Create a new RDA in the marketplace. ## Endpoint ``` POST /rda ``` ## Authentication Required. Bearer token in Authorization header. ## Request ### Headers ``` Authorization: Bearer YOUR_TOKEN Content-Type: application/json ``` ### Body ```json { "slug": "my-new-rda", "type": "prompt", "name": "My New RDA", "description": "A short description of what this RDA does", "longDescription": "A longer, more detailed description...", "tags": ["tag1", "tag2"], "coverImage": "https://...", "codeSnippet": "const result = await run(input)", "codeLanguage": "javascript", "inputSchema": [ { "name": "fieldName", "label": "Field Label", "type": "text", "required": true, "placeholder": "Enter value..." } ], "outputSchema": { "type": "markdown" }, "promptConfig": { "promptTemplate": "Your prompt template with {{variables}}", "systemPrompt": "Optional system prompt", "allowedModels": ["gpt-4o", "claude-3.5-sonnet"], "defaultModelId": "gpt-4o", "sourcePrice": 4.99, "examples": [] } } ``` ### Required Fields | Field | Type | Description | |-------|------|-------------| | `slug` | string | Unique URL-friendly identifier | | `type` | string | prompt, agent, or tool | | `name` | string | Display name | | `description` | string | Short description | | `inputSchema` | array | Input field definitions | ### Optional Fields | Field | Type | Description | |-------|------|-------------| | `longDescription` | string | Detailed description | | `tags` | array | Discovery tags | | `coverImage` | string | Cover image URL | | `codeSnippet` | string | Example code | | `codeLanguage` | string | Code language | | `outputSchema` | object | Output format definition | ### Type-Specific Config #### For Prompts ```json { "promptConfig": { "promptTemplate": "Template with {{variables}}", "systemPrompt": "System context", "allowedModels": ["gpt-4o", "claude-3.5-sonnet"], "defaultModelId": "gpt-4o", "sourcePrice": 4.99, "examples": [ { "title": "Example 1", "inputs": {"field": "value"}, "output": "Example output", "model": "gpt-4o" } ] } } ``` #### For Agents ```json { "agentConfig": { "webhookUrl": "https://your-webhook.com/endpoint", "webhookMethod": "POST", "webhookHeaders": {"X-Custom": "value"}, "timeoutSeconds": 60, "maxRetries": 3, "pollUrl": "https://your-webhook.com/poll", "pollIntervalMs": 2000, "basePrice": 0.10 } } ``` #### For Tools ```json { "toolConfig": { "apiEndpoint": "https://api.example.com/endpoint", "apiMethod": "GET", "apiHeaders": {}, "authType": "api_key", "authConfig": {"headerName": "X-API-Key"}, "requestTransform": "...", "responseTransform": "...", "rateLimitPerMinute": 60, "basePrice": 0.05 } } ``` ## Response ### Success (201) ```json { "created": true, "rda": { "id": "rda_abc123", "slug": "my-new-rda", "type": "prompt", "status": "draft" } } ``` ## Error Responses ### Validation Error (400) ```json { "error": "Validation failed", "details": { "slug": "Slug already exists", "inputSchema": "At least one input field required" } } ``` ### Unauthorized (401) ```json { "error": "Authentication required" } ``` ## Examples ### Create a Prompt RDA ```bash curl -X POST https://api.xpay.sh/hub/rda \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "slug": "competitor-analyzer", "type": "prompt", "name": "Competitor Analyzer", "description": "Analyze competitors for strategic insights", "inputSchema": [ { "name": "companyName", "label": "Company Name", "type": "text", "required": true } ], "promptConfig": { "promptTemplate": "Analyze the company {{companyName}}...", "allowedModels": ["gpt-4o", "claude-3.5-sonnet"], "defaultModelId": "gpt-4o" } }' ``` ## Code Examples ### JavaScript ```javascript const response = await fetch('https://api.xpay.sh/hub/rda', { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ slug: 'my-rda', type: 'prompt', name: 'My RDA', description: 'Description here', inputSchema: [ { name: 'input1', label: 'Input 1', type: 'text', required: true } ], promptConfig: { promptTemplate: 'Process: {{input1}}', allowedModels: ['gpt-4o'], defaultModelId: 'gpt-4o' } }) }) const { rda } = await response.json() console.log(`Created: ${rda.id}`) ``` ## Notes - RDAs are created in draft status - Publish via the Creator Dashboard - Slugs must be unique - Input schema is validated ================================================================================ # Page: /en/hub/reference/get-rda # Source: src/content/en/hub/reference/get-rda.mdx ================================================================================ # Get RDA Details Retrieve detailed information about a specific RDA. ## Endpoint ``` GET /rda/{identifier} ``` ## Authentication Optional. Required for draft RDAs. ## Path Parameters | Parameter | Type | Description | |-----------|------|-------------| | `identifier` | string | RDA slug or ID | ## Response ### Success (200) ```json { "rda": { "id": "rda_abc123", "slug": "research-report-generator", "name": "AI Research Report Generator", "description": "Generate comprehensive research reports on any topic", "longDescription": "This RDA uses advanced AI models to generate detailed...", "type": "prompt", "status": "published", "verified": true, "featured": false, "trending": true, "tags": ["research", "reports", "analysis", "content"], "coverImage": "https://...", "codeSnippet": "const report = await generate({topic, depth})", "codeLanguage": "javascript", "version": "1.2.0", "schema": { "inputs": [ { "name": "topic", "label": "Research Topic", "type": "text", "required": true, "placeholder": "Enter topic to research..." }, { "name": "depth", "label": "Research Depth", "type": "select", "required": true, "options": ["quick", "standard", "comprehensive"] }, { "name": "focusAreas", "label": "Focus Areas", "type": "text", "required": false, "placeholder": "pricing, competitors, trends" } ], "outputs": { "type": "markdown" } }, "promptConfig": { "allowedModels": [ {"id": "gpt-4o-mini", "name": "GPT-4o Mini", "tier": "fast"}, {"id": "gpt-4o", "name": "GPT-4o", "tier": "balanced"}, {"id": "claude-3.5-sonnet", "name": "Claude 3.5 Sonnet", "tier": "balanced"} ], "defaultModelId": "gpt-4o", "sourcePrice": 4.99, "examples": [ { "id": "ex_001", "title": "SaaS Pricing Analysis", "inputs": {"topic": "SaaS Pricing", "depth": "comprehensive"}, "output": "## Research Report\n\n### Executive Summary...", "model": "gpt-4o" } ] }, "pricing": { "model": "per-run", "amount": 0.05, "currency": "USDC", "estimatedCost": "~$0.02-0.10 per run" }, "stats": { "totalRuns": 1250, "totalRevenue": 62.50, "averageRating": 4.8, "totalRatings": 89, "successRate": 98.5, "averageLatency": 3500 }, "ownerId": "user_xyz", "ownerName": "ResearchLabs", "ownerVerified": true, "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-15T00:00:00Z", "publishedAt": "2024-01-02T00:00:00Z" } } ``` ### Response Fields See full schema in the response above. Key fields: | Field | Type | Description | |-------|------|-------------| | `schema` | object | Input/output schema definition | | `promptConfig` | object | Prompt-specific config (for prompts) | | `agentConfig` | object | Agent-specific config (for agents) | | `toolConfig` | object | Tool-specific config (for tools) | | `stats` | object | Usage statistics | | `examples` | array | Pre-generated examples | ## Error Responses ### Not Found (404) ```json { "error": "RDA not found: invalid-slug" } ``` ### Unauthorized (401) For draft RDAs without authentication: ```json { "error": "Authentication required" } ``` ## Examples ### Get by Slug ```bash curl https://api.xpay.sh/hub/rda/research-report-generator ``` ### Get by ID ```bash curl https://api.xpay.sh/hub/rda/rda_abc123 ``` ### With Authentication (for drafts) ```bash curl https://api.xpay.sh/hub/rda/my-draft-rda \ -H "Authorization: Bearer YOUR_TOKEN" ``` ## Code Examples ### JavaScript ```javascript const response = await fetch('https://api.xpay.sh/hub/rda/research-report-generator') const { rda } = await response.json() console.log(rda.name) console.log(rda.description) console.log(rda.schema.inputs) ``` ### Python ```python import requests response = requests.get('https://api.xpay.sh/hub/rda/research-report-generator') rda = response.json()['rda'] print(rda['name']) print(rda['description']) for input_field in rda['schema']['inputs']: print(f" {input_field['name']}: {input_field['type']}") ``` ## Notes - Public RDAs are accessible without authentication - Draft RDAs require owner authentication - Stats are updated in real-time - Examples are included for prompt RDAs ================================================================================ # Page: /en/hub/reference/index # Source: src/content/en/hub/reference/index.mdx ================================================================================ # API Reference xpay✦ Hub provides a REST API for running RDAs and managing your account. ## Base URL ``` https://api.xpay.sh/hub ``` ## Authentication All authenticated endpoints require a Bearer token: ```bash Authorization: Bearer YOUR_TOKEN ``` Tokens are obtained through Privy authentication. ## Endpoints Overview ### RDA Execution | Method | Endpoint | Description | |--------|----------|-------------| | POST | `/run` | Execute an RDA | ### RDA Catalog | Method | Endpoint | Description | |--------|----------|-------------| | GET | `/rdas` | List all RDAs | | GET | `/rda/{slug}` | Get RDA details | | POST | `/rda` | Create an RDA | ### Wallet | Method | Endpoint | Description | |--------|----------|-------------| | GET | `/wallet/balance` | Check balance | | POST | `/wallet/deposit` | Record deposit | ## Response Format All responses follow this structure: ### Success ```json { "data": { ... }, "metadata": { "timestamp": "2024-01-01T00:00:00Z" } } ``` ### Error ```json { "error": "Error message", "code": "ERROR_CODE", "details": { ... } } ``` ## HTTP Status Codes | Code | Description | |------|-------------| | 200 | Success | | 201 | Created | | 400 | Bad request | | 401 | Unauthorized | | 402 | Payment required | | 403 | Forbidden | | 404 | Not found | | 500 | Server error | ## Rate Limits - **Authenticated**: 100 requests/minute - **Unauthenticated**: 10 requests/minute Rate limit headers: ``` X-RateLimit-Limit: 100 X-RateLimit-Remaining: 95 X-RateLimit-Reset: 1704067200 ``` ## SDKs ### JavaScript/TypeScript ```bash npm install @xpaysh/hub-sdk ``` ```typescript import { XpayHub } from '@xpaysh/hub-sdk' const client = new XpayHub({ apiKey: 'YOUR_API_KEY' }) const result = await client.run('research-report-generator', { topic: 'SaaS Pricing', depth: 'comprehensive' }) ``` ### Python Coming soon. ## Webhooks For long-running operations, configure webhook callbacks: ```json { "webhookUrl": "https://your-server.com/callback", "webhookEvents": ["run.completed", "run.failed"] } ``` ## OpenAPI Specification Download the full [OpenAPI spec](/openapi.json) for use with API clients, code generators, or AI assistants. ## Getting Help - [Discord](https://discord.gg/xpay) - Community support - [GitHub Issues](https://github.com/xpaysh/xpay-docs/issues) - Bug reports - [Email](mailto:support@xpay.sh) - Direct support ================================================================================ # Page: /en/hub/reference/list-rdas # Source: src/content/en/hub/reference/list-rdas.mdx ================================================================================ # List RDAs Retrieve a list of RDAs from the marketplace. ## Endpoint ``` GET /rdas ``` ## Authentication Optional. Some filters may require authentication. ## Query Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `type` | string | - | Filter by type (prompt, agent, tool) | | `status` | string | published | Filter by status | | `verified` | boolean | - | Only verified RDAs | | `featured` | boolean | - | Only featured RDAs | | `trending` | boolean | - | Only trending RDAs | | `ownerId` | string | - | Filter by creator | | `search` | string | - | Search in name/description | | `limit` | number | 20 | Results per page (max 100) | | `offset` | number | 0 | Pagination offset | ## Response ### Success (200) ```json { "rdas": [ { "id": "rda_abc123", "slug": "research-report-generator", "name": "AI Research Report Generator", "description": "Generate comprehensive research reports on any topic", "type": "prompt", "status": "published", "verified": true, "featured": false, "trending": true, "coverImage": "https://...", "pricing": { "model": "per-run", "amount": 0.05, "currency": "USDC" }, "stats": { "totalRuns": 1250, "averageRating": 4.8, "successRate": 98.5 }, "ownerId": "user_xyz", "ownerName": "ResearchLabs", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-15T00:00:00Z" } ], "total": 150, "limit": 20, "offset": 0 } ``` ### Response Fields | Field | Type | Description | |-------|------|-------------| | `rdas` | array | List of RDA objects | | `total` | number | Total matching RDAs | | `limit` | number | Results per page | | `offset` | number | Current offset | ### RDA Object | Field | Type | Description | |-------|------|-------------| | `id` | string | Unique identifier | | `slug` | string | URL-friendly identifier | | `name` | string | Display name | | `description` | string | Short description | | `type` | string | prompt, agent, or tool | | `status` | string | draft, published, archived | | `verified` | boolean | Verification status | | `featured` | boolean | Featured status | | `trending` | boolean | Trending status | | `pricing` | object | Pricing configuration | | `stats` | object | Usage statistics | | `ownerId` | string | Creator ID | | `ownerName` | string | Creator display name | ## Examples ### List All Published RDAs ```bash curl https://api.xpay.sh/hub/rdas ``` ### Filter by Type ```bash curl "https://api.xpay.sh/hub/rdas?type=prompt" ``` ### Search ```bash curl "https://api.xpay.sh/hub/rdas?search=research%20report" ``` ### Pagination ```bash curl "https://api.xpay.sh/hub/rdas?limit=10&offset=20" ``` ### Multiple Filters ```bash curl "https://api.xpay.sh/hub/rdas?type=agent&verified=true" ``` ## Code Examples ### JavaScript ```javascript const params = new URLSearchParams({ type: 'prompt', limit: '20' }) const response = await fetch(`https://api.xpay.sh/hub/rdas?${params}`) const { rdas, total } = await response.json() console.log(`Found ${total} RDAs`) rdas.forEach(r => console.log(r.name)) ``` ### Python ```python import requests response = requests.get( 'https://api.xpay.sh/hub/rdas', params={ 'type': 'prompt', 'limit': 20 } ) data = response.json() print(f"Found {data['total']} RDAs") for rda in data['rdas']: print(rda['name']) ``` ## Notes - Public endpoint, no auth required - Results sorted by relevance/trending by default - Maximum 100 results per request - Use pagination for large result sets ================================================================================ # Page: /en/hub/reference/run-rda # Source: src/content/en/hub/reference/run-rda.mdx ================================================================================ # Run an RDA Execute an RDA and receive the output. ## Endpoint ``` POST /run ``` ## Authentication Required. Bearer token in Authorization header. ## Request ### Headers ``` Authorization: Bearer YOUR_TOKEN Content-Type: application/json ``` ### Body ```json { "rdaSlug": "research-report-generator", "inputs": { "topic": "Competitor Analysis", "industry": "SaaS" }, "modelId": "claude-3.5-sonnet" } ``` ### Parameters | Field | Type | Required | Description | |-------|------|----------|-------------| | `rdaSlug` | string | Yes | RDA identifier (slug or ID) | | `inputs` | object | Yes | Input values matching RDA schema | | `modelId` | string | No | Model ID for prompts (uses default if omitted) | ## Response ### Success (200) ```json { "success": true, "runId": "run_abc123", "output": "## Research Report\n\n### Executive Summary...", "cost": 0.05, "duration": 3500, "modelId": "claude-3.5-sonnet", "usage": { "prompt_tokens": 150, "completion_tokens": 250, "total_tokens": 400 } } ``` ### Response Fields | Field | Type | Description | |-------|------|-------------| | `success` | boolean | Whether execution succeeded | | `runId` | string | Unique run identifier | | `output` | string | RDA output (format varies by type) | | `cost` | number | Amount charged (USDC) | | `duration` | number | Execution time (ms) | | `modelId` | string | Model used (for prompts) | | `usage` | object | Token usage (for prompts) | ## Error Responses ### Insufficient Balance (402) ```json { "error": "Insufficient balance", "required": 0.05, "available": 0.02, "runId": "run_abc123" } ``` ### RDA Not Found (404) ```json { "error": "RDA not found: invalid-slug", "runId": "run_abc123" } ``` ### Invalid Input (400) ```json { "error": "Invalid input", "details": { "topic": "Required field missing" }, "runId": "run_abc123" } ``` ### Execution Error (500) ```json { "error": "Execution failed: LLM timeout", "runId": "run_abc123" } ``` ## Examples ### Run a Prompt RDA ```bash curl -X POST https://api.xpay.sh/hub/run \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "rdaSlug": "competitor-analysis", "inputs": { "companyName": "Acme Corp", "industry": "saas", "depth": "detailed" }, "modelId": "gpt-4o" }' ``` ### Run an Agent RDA ```bash curl -X POST https://api.xpay.sh/hub/run \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "rdaSlug": "lead-research", "inputs": { "companyName": "Acme Corp", "researchDepth": "standard" } }' ``` ### Run a Tool RDA ```bash curl -X POST https://api.xpay.sh/hub/run \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "rdaSlug": "company-lookup", "inputs": { "domain": "example.com" } }' ``` ## Code Examples ### JavaScript ```javascript const response = await fetch('https://api.xpay.sh/hub/run', { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ rdaSlug: 'research-report-generator', inputs: { topic: 'SaaS Pricing', depth: 'comprehensive' } }) }) const result = await response.json() console.log(result.output) ``` ### Python ```python import requests response = requests.post( 'https://api.xpay.sh/hub/run', headers={ 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json' }, json={ 'rdaSlug': 'research-report-generator', 'inputs': { 'topic': 'SaaS Pricing', 'depth': 'comprehensive' } } ) result = response.json() print(result['output']) ``` ## Notes - Failed runs are not charged - Runs are logged in your history - Cost is deducted from available balance - Long-running agents may take up to 180 seconds ================================================================================ # Page: /en/hub/reference/wallet-balance # Source: src/content/en/hub/reference/wallet-balance.mdx ================================================================================ # Check Wallet Balance Get your current wallet balance and status. ## Endpoint ``` GET /wallet/balance ``` ## Authentication Required. Bearer token in Authorization header. ## Request ### Headers ``` Authorization: Bearer YOUR_TOKEN ``` ## Response ### Success (200) ```json { "wallet": { "userId": "did:privy:abc123", "walletAddress": "0x1234567890abcdef1234567890abcdef12345678", "balance": 100.50, "availableBalance": 95.00, "pendingLocks": { "run_abc123": 5.50 }, "totalLocked": 5.50, "totalDeposited": 500.00, "totalSpent": 399.50 } } ``` ### Response Fields | Field | Type | Description | |-------|------|-------------| | `userId` | string | Your Privy user ID | | `walletAddress` | string | Your Base wallet address | | `balance` | number | Total USDC balance | | `availableBalance` | number | Balance available for spending | | `pendingLocks` | object | Funds locked for pending runs | | `totalLocked` | number | Total locked amount | | `totalDeposited` | number | Lifetime deposits | | `totalSpent` | number | Lifetime spending | ## Error Responses ### Unauthorized (401) ```json { "error": "Authentication required" } ``` ### Wallet Not Found (404) ```json { "error": "Wallet not found for user" } ``` ## Examples ### Basic Request ```bash curl https://api.xpay.sh/hub/wallet/balance \ -H "Authorization: Bearer YOUR_TOKEN" ``` ## Code Examples ### JavaScript ```javascript const response = await fetch('https://api.xpay.sh/hub/wallet/balance', { headers: { 'Authorization': `Bearer ${token}` } }) const { wallet } = await response.json() console.log(`Balance: $${wallet.balance}`) console.log(`Available: $${wallet.availableBalance}`) console.log(`Locked: $${wallet.totalLocked}`) ``` ### Python ```python import requests response = requests.get( 'https://api.xpay.sh/hub/wallet/balance', headers={'Authorization': f'Bearer {token}'} ) wallet = response.json()['wallet'] print(f"Balance: ${wallet['balance']}") print(f"Available: ${wallet['availableBalance']}") ``` ## Understanding Balance States ### Balance vs Available - **Balance**: Total USDC in your wallet - **Available**: What you can spend right now - **Locked**: Reserved for pending operations ### Locked Funds Funds are locked when: - An RDA run is in progress - Waiting for execution to complete Funds are released when: - Run completes successfully (deducted) - Run fails (returned to available) ## Notes - Balance updates in real-time - Locked funds are temporary - Available balance is what you can spend - All amounts are in USDC ================================================================================ # Page: /en/hub/reference/wallet-deposit # Source: src/content/en/hub/reference/wallet-deposit.mdx ================================================================================ # Record Deposit Record a USDC deposit to your wallet. ## Endpoint ``` POST /wallet/deposit ``` ## Authentication Required. Bearer token in Authorization header. ## Request ### Headers ``` Authorization: Bearer YOUR_TOKEN Content-Type: application/json ``` ### Body ```json { "amount": 50.00, "transactionHash": "0xabc123..." } ``` ### Parameters | Field | Type | Required | Description | |-------|------|----------|-------------| | `amount` | number | Yes | USDC amount deposited | | `transactionHash` | string | No | On-chain transaction hash | ## Response ### Success (200) ```json { "deposited": true, "amount": 50.00, "transactionHash": "0xabc123...", "newBalance": 150.50 } ``` ### Response Fields | Field | Type | Description | |-------|------|-------------| | `deposited` | boolean | Whether deposit was recorded | | `amount` | number | Amount deposited | | `transactionHash` | string | Transaction hash (if provided) | | `newBalance` | number | Updated wallet balance | ## Error Responses ### Invalid Amount (400) ```json { "error": "Invalid amount", "details": { "amount": "Must be greater than 0" } } ``` ### Unauthorized (401) ```json { "error": "Authentication required" } ``` ### Duplicate Transaction (409) ```json { "error": "Transaction already recorded", "transactionHash": "0xabc123..." } ``` ## Examples ### Basic Deposit ```bash curl -X POST https://api.xpay.sh/hub/wallet/deposit \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "amount": 50.00 }' ``` ### With Transaction Hash ```bash curl -X POST https://api.xpay.sh/hub/wallet/deposit \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "amount": 50.00, "transactionHash": "0xabc123def456..." }' ``` ## Code Examples ### JavaScript ```javascript const response = await fetch('https://api.xpay.sh/hub/wallet/deposit', { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ amount: 50.00, transactionHash: txHash }) }) const result = await response.json() console.log(`New balance: $${result.newBalance}`) ``` ### Python ```python import requests response = requests.post( 'https://api.xpay.sh/hub/wallet/deposit', headers={ 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json' }, json={ 'amount': 50.00, 'transactionHash': tx_hash } ) result = response.json() print(f"New balance: ${result['newBalance']}") ``` ## How Deposits Work ### 1. Send USDC Send USDC on Base network to your xpay✦ wallet address. ### 2. Get Transaction Hash Copy the transaction hash from your wallet or block explorer. ### 3. Record Deposit Call this endpoint to record the deposit and update your balance. ### 4. Start Using Your balance is now available for running RDAs. ## Auto-Detection In some cases, deposits are auto-detected: - Via blockchain monitoring - Through Privy wallet events Manual recording is optional but recommended for immediate balance updates. ## Notes - Deposits must be USDC on Base network - Transaction hash helps prevent duplicates - Balance updates immediately after recording - Check balance with GET /wallet/balance ================================================================================ # Page: /en/hub/topics/model-tiers # Source: src/content/en/hub/topics/model-tiers.mdx ================================================================================ # Model Tiers Understanding AI model tiers for prompt RDAs. ## Tier Overview | Tier | Price | Speed | Quality | Best For | |------|-------|-------|---------|----------| | **Fast** | $0.02 | 2-5s | Good | Simple tasks | | **Balanced** | $0.05 | 5-15s | Great | Most use cases | | **Reasoning** | $0.10 | 15-60s | Best | Complex analysis | ## Fast Tier ### Price: $0.02 per run ### Models - **GPT-4o Mini** (OpenAI) - **Claude 3 Haiku** (Anthropic) - **Llama 3.1 8B** (Meta) - **Gemini Flash** (Google) - **Mistral 7B** (Mistral) ### Characteristics - Fastest response times - Lower cost - Good for straightforward tasks - May miss nuance ### Best For - Simple formatting - Quick translations - Basic summaries - Short answers - High-volume tasks ### Example Use "Generate 5 creative name ideas for a SaaS product" ## Balanced Tier ### Price: $0.05 per run ### Models - **GPT-4o** (OpenAI) - **Claude 3.5 Sonnet** (Anthropic) - **Llama 3.1 70B** (Meta) - **Gemini Pro** (Google) - **Mistral Large** (Mistral) ### Characteristics - Optimal quality/speed balance - Handles complex tasks well - Good reasoning ability - Most popular choice ### Best For - Code analysis - Content generation - Technical writing - Strategy development - Most general tasks ### Example Use "Analyze this company's competitive positioning and provide strategic recommendations" ## Reasoning Tier ### Price: $0.10 per run ### Models - **o1-preview** (OpenAI) - **o1-mini** (OpenAI) - **Claude 3 Opus** (Anthropic) - **Llama 3.1 405B** (Meta) - **DeepSeek V3** (DeepSeek) ### Characteristics - Highest quality output - Deep reasoning ability - Handles complex analysis - Longer response times ### Best For - Complex problem solving - Multi-step reasoning - Deep technical analysis - Critical decisions - Research tasks ### Example Use "Perform a comprehensive market analysis examining competitive dynamics, pricing strategies, and growth opportunities in the B2B SaaS space" ## Choosing a Tier ### Consider Your Task | Task Type | Recommended | |-----------|-------------| | Quick lookup | Fast | | Formatting | Fast | | General content | Balanced | | Code review | Balanced | | Complex analysis | Reasoning | | Critical decisions | Reasoning | ### Consider Your Budget - **High volume** → Fast tier saves money - **Quality critical** → Reasoning worth the cost - **General use** → Balanced is best value ### Consider Speed - **Need results fast** → Fast tier - **Can wait for quality** → Reasoning tier - **Balance needed** → Balanced tier ## Model Comparison ### OpenAI Models | Model | Tier | Strengths | |-------|------|-----------| | GPT-4o Mini | Fast | Speed, efficiency | | GPT-4o | Balanced | Versatility, quality | | o1-preview | Reasoning | Deep reasoning, accuracy | ### Anthropic Models | Model | Tier | Strengths | |-------|------|-----------| | Claude 3 Haiku | Fast | Speed, safety | | Claude 3.5 Sonnet | Balanced | Writing, analysis | | Claude 3 Opus | Reasoning | Complex tasks | ### Meta Models | Model | Tier | Strengths | |-------|------|-----------| | Llama 3.1 8B | Fast | Efficiency | | Llama 3.1 70B | Balanced | Open source quality | | Llama 3.1 405B | Reasoning | Frontier open source | ## For Creators When building prompt RDAs: ### Default Model Choose a sensible default: - Simple prompts → Fast as default - Most prompts → Balanced as default - Complex prompts → Reasoning as default ### Allowed Models Select which tiers to allow: - Enable all three for flexibility - Restrict if prompt needs specific tier - Consider your target audience ## Related Topics - [Pricing Models](/hub/topics/pricing-models) - [Understanding Pricing](/hub/guides/users/understanding-pricing) ================================================================================ # Page: /en/hub/topics/payment-flow # Source: src/content/en/hub/topics/payment-flow.mdx ================================================================================ # Payment Flow How payments work on xpay✦ Hub. ## Overview xpay✦ Hub uses USDC on Base network for instant micropayments. ``` Deposit → Lock → Execute → Settle ``` ## Currency & Network ### USDC - **Type**: Stablecoin (1 USDC = $1 USD) - **Contract**: `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` (Base) - **Decimals**: 6 ### Base Network - **Type**: Layer 2 (Coinbase) - **Chain ID**: 8453 (mainnet), 84532 (testnet) - **Speed**: ~2 second finality - **Cost**: Very low gas fees ## Payment Steps ### 1. Deposit Users add USDC to their xpay✦ wallet: 1. Send USDC on Base to wallet address 2. Transaction confirms (~2 seconds) 3. Balance updates automatically ### 2. Lock When running an RDA: 1. Click "Run" 2. Cost is locked from available balance 3. Locked funds reserved for this run ### 3. Execute The RDA runs: 1. Inputs processed 2. Execution happens 3. Output generated ### 4. Settle After execution: **On Success:** - Locked funds deducted - Creator receives payment - User sees result **On Failure:** - Locked funds released - Balance restored - User not charged ## Non-Custodial Design xpay✦ never holds your funds: - **Your keys** - Controlled via Privy - **Your wallet** - On Base network - **Direct settlement** - Creator paid directly ## Spending Controls ### Global Allowance Set maximum spending: ```typescript { allowance: 10.00, // Max $10 per session refreshOnLogin: true } ``` ### Per-Transaction Limit Limit individual runs: ```typescript { maxPerTransaction: 1.00 // Max $1 per run } ``` ## API Integration ### Check Balance ```bash GET /wallet/balance ``` ```json { "balance": 100.50, "availableBalance": 95.00, "totalLocked": 5.50 } ``` ### Record Deposit ```bash POST /wallet/deposit { "amount": 50.00, "transactionHash": "0x..." } ``` ## Fee Structure ### Platform Fee - ~10% of transaction - Covers infrastructure - Instant settlement ### Network Fees - Base gas fees (very low) - Paid by platform - No user gas needed ## Security ### Transaction Safety - Funds locked only for execution - Released on failure - No pre-authorization abuse ### Wallet Security - Privy-managed keys - MPC technology - Non-custodial ## Troubleshooting ### Balance Not Updating 1. Check transaction on Base explorer 2. Wait for confirmation 3. Refresh the page ### Transaction Failed 1. Check sufficient balance 2. Verify inputs are valid 3. Try again ### Funds Locked Funds are released: - After successful execution - On execution failure - If timeout occurs ## xpay✦ Infrastructure xpay✦ Hub uses the xpay✦ payment infrastructure: - x402 protocol support - Spending controls - Transaction logging - Instant settlement Learn more in the [xpay✦ documentation](/getting-started). ## Related Topics - [Managing Your Wallet](/hub/guides/users/managing-wallet) - [Fund Your Wallet](/hub/get-started/fund-wallet) ================================================================================ # Page: /en/hub/topics/pricing-models # Source: src/content/en/hub/topics/pricing-models.mdx ================================================================================ # Pricing Models How RDA pricing works on xpay✦ Hub. ## Available Models ### Per-Run Fixed price for each execution. ```typescript { model: 'per-run', amount: 0.05, currency: 'USDC' } ``` **How it works:** - Same price every time - Regardless of input/output size - Most predictable for users **Best for:** - Most RDAs - Predictable costs - Simple pricing ### Per-Token Price based on input and output tokens. ```typescript { model: 'per-token', amount: 0.001, // per 1K tokens currency: 'USDC' } ``` **How it works:** - Cost scales with content length - Input + output tokens counted - More variable pricing **Best for:** - Variable-length outputs - Pass-through pricing - Usage-based billing ### Per-Second Price based on execution time. ```typescript { model: 'per-second', amount: 0.01, currency: 'USDC' } ``` **How it works:** - Cost scales with time - Execution time measured - Good for compute tasks **Best for:** - Long-running agents - Compute-intensive tasks - Time-based resources ### Free No cost to execute. ```typescript { model: 'free', amount: 0, currency: 'USDC' } ``` **How it works:** - No charge to users - Creator pays any API costs - Good for building audience **Best for:** - Demo/trial RDAs - Open source tools - Building reputation ## Prompt Tier Pricing For prompt RDAs, pricing is tied to model tiers: | Tier | Price | Creator Revenue | |------|-------|-----------------| | Fast | $0.02 | ~$0.018 | | Balanced | $0.05 | ~$0.045 | | Reasoning | $0.10 | ~$0.09 | Users select tier when running. ## Source Code Pricing Prompt RDAs can sell their template: ```typescript { promptSourcePrice: 4.99 // One-time purchase } ``` **What users get:** - Full prompt template - System prompt (if any) - License to use **Typical prices:** - Simple: $1.99 - $4.99 - Medium: $4.99 - $9.99 - Complex: $9.99 - $24.99 ## Revenue Split ### Standard Split - **Creator**: ~90% - **Platform**: ~10% ### Payout - Instant settlement - USDC to your wallet - No minimums ## Pricing Strategy ### Competitive Analysis 1. Find similar RDAs 2. Note their pricing 3. Consider your value-add 4. Price accordingly ### Value-Based Pricing Consider what users would pay elsewhere: - Time saved - Quality delivered - Alternative costs ### Cost-Plus Pricing Calculate your costs: - API costs (LLM, external) - Infrastructure - Time investment - Add margin ## Dynamic Pricing ### Estimators Show estimated cost before running: ```typescript { estimatedCost: '~$0.05 per run' } ``` ### Variable Costs For token-based pricing, estimate range: ```typescript { minCost: 0.01, maxCost: 0.50, typicalCost: 0.05 } ``` ## User Experience ### Cost Display Users see: - Price per run (or estimate) - Their balance - Cost breakdown ### Cost Protection - Spending limits - Confirmation dialogs - Failed run refunds ## Related Topics - [Model Tiers](/hub/topics/model-tiers) - [Understanding Pricing](/hub/guides/users/understanding-pricing) - [Pricing Your RDA](/hub/guides/creators/pricing-your-rda) ================================================================================ # Page: /en/hub/topics/rda-types # Source: src/content/en/hub/topics/rda-types.mdx ================================================================================ # RDA Types Deep dive into the three types of Runnable Digital Assets. ## Overview | Type | Description | Use Case | Pricing | |------|-------------|----------|---------| | **Prompts** | LLM-based generation | Text analysis, content creation | Model tiers | | **Agents** | Workflow orchestration | Automation, multi-step tasks | Custom | | **Tools** | API proxies | Data access, integrations | Custom | ## Prompts ### What They Are Prompts use large language models to generate text based on: - A prompt template - User-provided inputs - Selected model tier ### How They Work ``` User Input → Prompt Template → LLM → Output ``` 1. User fills input form 2. Inputs are injected into template 3. Template sent to LLM 4. Response returned to user ### Key Features - **Model selection** - Choose AI model tier - **Template variables** - Dynamic input injection - **Examples** - Pre-generated output samples - **Source purchase** - Buy the prompt template ### Best For - Text generation and analysis - Creative content - Technical documentation - Planning and strategy ## Agents ### What They Are Agents orchestrate workflows by communicating with external services via webhooks. ### How They Work ``` User Input → Webhook → External Service → Result ``` 1. User provides inputs 2. Agent calls webhook endpoint 3. External service processes (n8n, Make, etc.) 4. Result returned to user ### Key Features - **Webhook integration** - Connect to any HTTP endpoint - **Async support** - Long-running task polling - **Multi-step** - Chain complex workflows - **Retries** - Automatic failure handling ### Best For - Automation workflows - Multi-step processes - External service orchestration - Scheduled tasks ## Tools ### What They Are Tools wrap external APIs with payment handling and user-friendly inputs. ### How They Work ``` User Input → Transform → API Call → Transform → Output ``` 1. User provides inputs 2. Request is transformed 3. External API is called 4. Response is transformed 5. Result returned to user ### Key Features - **API wrapping** - Any HTTP API - **Authentication** - Secure credential handling - **Transformation** - Request/response formatting - **Rate limiting** - Usage control ### Best For - Data access - External service integration - API aggregation - Service proxying ## Comparison ### Execution Model | Aspect | Prompts | Agents | Tools | |--------|---------|--------|-------| | **Engine** | LLM API | Webhook | HTTP API | | **Latency** | 2-60s | Variable | 1-10s | | **Output** | Text | Any | JSON/Text | | **Async** | No | Yes | No | ### Creator Requirements | Aspect | Prompts | Agents | Tools | |--------|---------|--------|-------| | **Needs** | Prompt engineering | Webhook endpoint | API access | | **Complexity** | Low | Medium | Medium | | **Hosting** | None | External | None | | **Secrets** | None | Optional | API keys | ### Pricing | Aspect | Prompts | Agents | Tools | |--------|---------|--------|-------| | **Model** | Tier-based | Custom | Custom | | **Range** | $0.02-0.10 | $0.05+ | $0.01+ | | **Source** | Optional sale | N/A | N/A | ## Choosing a Type ### Create a Prompt When: - Your capability is text-based - Output comes from AI generation - You want tiered pricing - No external services needed ### Create an Agent When: - You need multi-step workflows - Tasks are long-running - External services are involved - Complex orchestration needed ### Create a Tool When: - Wrapping an existing API - Data access is the goal - Simple request/response - Authentication needed ## Technical Details ### Prompt Internals ```typescript interface PromptConfig { promptTemplate: string systemPrompt?: string allowedModels: ModelOption[] defaultModelId: string sourcePrice?: number examples?: Example[] } ``` ### Agent Internals ```typescript interface AgentConfig { webhookUrl: string webhookMethod: 'GET' | 'POST' webhookHeaders?: Record timeoutSeconds: number maxRetries: number pollUrl?: string pollIntervalMs?: number } ``` ### Tool Internals ```typescript interface ToolConfig { apiEndpoint: string apiMethod: 'GET' | 'POST' | 'PUT' | 'DELETE' apiHeaders?: Record authType: 'none' | 'api_key' | 'bearer' | 'basic' authConfig?: Record requestTransform?: string responseTransform?: string rateLimitPerMinute?: number } ``` ## Related Topics - [Model Tiers](/hub/topics/model-tiers) - [Pricing Models](/hub/topics/pricing-models) ================================================================================ # Page: /en/hub/topics/verification # Source: src/content/en/hub/topics/verification.mdx ================================================================================ # Verification Understanding RDA and creator verification. ## What is Verification? Verification is xpay✦ Hub's quality assurance program. Verified RDAs and creators have been reviewed by our team. ## Verified Badge ### What It Means - **Quality reviewed** - Meets our standards - **Tested** - Works as described - **Safe** - No harmful content - **Reliable** - Consistent performance ### Visual Indicator Verified RDAs show a checkmark badge: - On RDA cards in marketplace - On RDA detail pages - Next to creator name ## Benefits of Verification ### For Users - **Trust** - Know the RDA works - **Quality** - Meets standards - **Safety** - No harmful content - **Support** - Creator is responsive ### For Creators - **Visibility** - Higher in search - **Trust** - Users more likely to run - **Featured** - Eligible for featuring - **Collections** - Can join curated bundles ## Verification Criteria ### RDA Requirements We review: 1. **Functionality** - Works as described - Handles edge cases - Consistent output 2. **Quality** - Useful output - Good UX - Clear documentation 3. **Safety** - No harmful content - No malicious code - Privacy respecting 4. **Pricing** - Fair pricing - Transparent costs - Value delivered ### Creator Requirements We also assess: - **History** - Track record on platform - **Responsiveness** - Handles issues - **Quality** - Consistent across RDAs ## Verification Process ### Step 1: Publish RDA First, publish your RDA: 1. Complete all fields 2. Add examples 3. Set pricing 4. Submit for publishing ### Step 2: Build Track Record Run period before verification: - Accumulate runs - Get user ratings - Demonstrate reliability ### Step 3: Apply Request verification: 1. Go to Creator Dashboard 2. Select RDA 3. Click "Request Verification" 4. Wait for review ### Step 4: Review Our team reviews: - Runs the RDA - Checks output quality - Reviews documentation - Assesses safety ### Step 5: Decision Within 5 business days: - **Approved** - Badge granted - **Needs Work** - Feedback provided - **Denied** - Explanation given ## Maintaining Verification ### Ongoing Requirements Verified status requires: - Continued quality - User satisfaction - No policy violations - Active maintenance ### Losing Verification Status can be revoked for: - Quality degradation - Policy violations - User complaints - Abandonment ## Verification Levels ### Verified RDA Individual RDA reviewed: - One RDA verified - Badge on that RDA - Must maintain quality ### Verified Creator Creator-level verification: - Multiple verified RDAs - All RDAs get badge - Higher trust level - Faster reviews ## FAQ ### How long does verification take? Typically 3-5 business days. ### Can I request verification immediately? We recommend waiting for some run history and ratings first. ### What if I'm denied? You'll receive feedback. Address issues and reapply. ### Do I need to pay for verification? No, verification is free. ### Can verification be transferred? No, verification is specific to RDA and creator. ## Related Topics - [Publishing & Verification](/hub/guides/creators/publishing-verification) ================================================================================ # Page: /en/index # Source: src/content/en/index.mdx ================================================================================ # Welcome to \{xpay✦\}

Dedicated infrastructure for the agentic payment protocols. Essential tools that sit between AI agents and autonomous payments, ensuring agents never overspend while enabling instant API monetization.

## What is \{xpay✦\}? \{xpay✦\} is building the essential infrastructure for the agentic payment protocols. We provide developers and businesses with the tools they need to safely integrate autonomous payments while enabling instant API monetization. ### Our Mission **Helping the agentic community get paid and pay safely.** As AI agents become more autonomous, they need secure, reliable payment infrastructure. \{xpay✦\} bridges this gap by providing: - 🛡️ **Safety-first payment controls** for autonomous agents - ⚡ **Instant API monetization** with zero setup complexity - 📊 **Complete observability** into agent spending and revenue - 🔧 **Developer-friendly tools** built for the modern web ## Core Products ### 🛡️ Smart Proxy **Cost Control Dashboard** Developers are concerned about their agents getting stuck in spending loops. Our smart proxy provides AWS proxy endpoints with hard spending limits, real-time alerts, and per-agent budgets. [Learn more →](/products/smart-proxy) ### ⚡ Paywall-as-a-Service **Easy Monetization** Turn any API into a revenue stream. Paste your endpoint, get an x402-monetized URL, and start earning immediately with our managed payment infrastructure. [Learn more →](/products/paywall-service) ### 📊 Transaction Explorer **Observability** Complete visibility into agent spending patterns, API performance, and transaction flows. The "Datadog for x402" that every agent developer needs. [Learn more →](/products/transaction-explorer) ## Quick Start Get started with \{xpay✦\} in under 5 minutes: ```bash npm install @xpaysh/agent-kit ``` ```typescript import { SmartProxy } from '@xpaysh/agent-kit' // Set spending limits for your agent const smartProxy = new SmartProxy({ maxDailySpend: 100, // $100 USD maxPerRequest: 5, // $5 USD per request alertThreshold: 0.8 // Alert at 80% of limits }) // Your agent's API calls are now protected await smartProxy.protectedFetch('https://api.example.com/expensive-ai-service') ``` [Full Quick Start Guide →](/getting-started) ## Why x402? The x402 protocol enables a new paradigm for internet payments: - **Micropayments**: Pay per API call, per token, per second - **Agent-native**: Designed for autonomous machine-to-machine payments - **Instant settlement**: Payments settle in ~2 seconds on Base network - **Zero subscription friction**: No signups, no monthly fees ## Open Source Ecosystem \{xpay✦\} actively contributes to the x402 ecosystem with open source tools: - [**awesome-x402**](https://github.com/xpaysh/awesome-x402) - Curated resources for x402 developers - [**x402-agent-kit**](https://github.com/xpaysh/x402-agent-kit) - Build x402-paying agents in 5 minutes - [**x402-local**](https://github.com/xpaysh/x402-local) - Local x402 development environment - [**x402-sdk**](https://github.com/xpaysh/x402-sdk) - TypeScript-first x402 SDK ## Community Join our growing community of x402 developers: - [GitHub](https://github.com/xpaysh) - Contribute to our open source projects - [Discord](https://discord.gg/vukXDGT7n5) - Connect with other developers - [Twitter](https://twitter.com/xpaysh) - Follow our updates - [Blog](https://www.xpay.sh/blog) - Read about x402 and autonomous payments --- Ready to start building? [Get started →](/getting-started) or explore our [product documentation →](/products). ================================================================================ # Page: /en/integrations/activepieces # Source: src/content/en/integrations/activepieces.mdx ================================================================================ # Activepieces Integration Monetize your Activepieces flows using xpay Pay-to-Run webhooks. ## Overview Activepieces is an open-source automation platform with a clean interface and powerful capabilities. With xpay, you can: - Accept USDC payments before flow execution - Collect customer information via custom forms - Trigger any Activepieces flow after payment --- ## Setup Guide ### Step 1: Create a Webhook Trigger in Activepieces 1. Open Activepieces and create a new flow 2. Add the **Webhook** trigger 3. Select **Catch Request** 4. Copy the generated webhook URL ### Step 2: Create an xpay Checkout 1. Go to [xpay Dashboard](https://app.xpay.sh/dashboard/pay-to-run/new) 2. Create a new checkout: - **Product Name**: Your flow's name - **Price**: Amount to charge in USDC - **Callback URL**: Your Activepieces webhook URL - **Network**: Base Sepolia (testnet) or Base (mainnet) - **Recipient Wallet**: Your wallet address 3. Add form fields for customer information 4. Save your checkout ### Step 3: Build Your Flow After the webhook trigger, add your flow logic. The webhook data structure: ```json { "payment": { "tx_hash": "0x...", "payer_address": "0x...", "amount": 5.00, "currency": "USDC", "network": "base", "timestamp": 1703001234567 }, "customer_input": { "email": "customer@example.com", "prompt": "Generate a blog post about AI" }, "metadata": { "checkout_id": "chk_abc123", "test_mode": false } } ``` --- ## Example Flow: AI Content Generator ``` [Webhook] → [OpenAI: Generate] → [Gmail: Send Result] ``` 1. **Webhook Trigger** - Receives payment confirmation from xpay 2. **OpenAI Piece** - Use `{{trigger.body.customer_input.prompt}}` as input - Generate content based on customer request 3. **Gmail Piece** - Send to `{{trigger.body.customer_input.email}}` - Include generated content --- ## Signature Verification (Optional) For production flows, verify webhook authenticity: 1. Add a **Code** piece after the webhook trigger 2. Use this JavaScript: ```javascript const crypto = require('crypto'); const signature = inputs.headers['x-xpay-signature']; const timestamp = inputs.headers['x-xpay-timestamp']; const body = inputs.body; const secret = 'YOUR_WEBHOOK_SECRET'; // Store in flow variables const data = `${timestamp}.${JSON.stringify(body)}`; const expected = 'sha256=' + crypto .createHmac('sha256', secret) .update(data) .digest('hex'); if (signature !== expected) { throw new Error('Invalid signature'); } return body; ``` --- ## Flow Templates ### Template 1: PDF Generator Accept payment, generate PDF from customer data, email result. ``` [Webhook] → [Code: Build PDF] → [Gmail: Send PDF] ``` ### Template 2: API Access Accept payment, provide temporary API key or access token. ``` [Webhook] → [Code: Generate Key] → [HTTP: Store in DB] → [Gmail: Send Key] ``` ### Template 3: Data Analysis Accept payment with file upload, analyze data, return insights. ``` [Webhook] → [OpenAI: Analyze] → [Airtable: Store] → [Gmail: Send Report] ``` --- ## Testing Your Flow 1. In Activepieces, use **Test Flow** to simulate webhooks 2. In xpay dashboard, click **Test Webhook** to send a test payload 3. Verify data flows through each piece correctly --- ## Tips for Production ### Handle Errors Gracefully Add error handling pieces: - **Branch** piece for conditional logic - **HTTP Request** piece to notify xpay of failures ### Use Variables Store sensitive data like webhook secrets in Activepieces variables: 1. Go to Project Settings → Variables 2. Add `XPAY_WEBHOOK_SECRET` 3. Reference as `{{vars.XPAY_WEBHOOK_SECRET}}` ### Logging Add logging for debugging: 1. Use **HTTP Request** piece to send to a logging service 2. Or use **Airtable/Google Sheets** to log transactions --- ## Troubleshooting ### Flow not triggering 1. Ensure flow is **published and enabled** 2. Check webhook URL matches exactly in xpay dashboard 3. Look at Activepieces run history for errors ### Missing data 1. Check you're accessing `trigger.body` not just `trigger` 2. Verify customer form fields match expected names 3. Use **Code** piece to inspect raw payload ### Timeouts Activepieces webhooks timeout after 30 seconds. For long flows: 1. Return response immediately 2. Use **Delay** piece with retries for external services --- ## Next Steps - [Create your checkout](https://app.xpay.sh/dashboard/pay-to-run/new) - [Universal Webhook Guide](/integrations/universal-webhook) - [Activepieces Documentation](https://www.activepieces.com/docs) ================================================================================ # Page: /en/integrations/index # Source: src/content/en/integrations/index.mdx ================================================================================ # Integrations Connect \{xpay\} with your favorite tools and platforms to monetize workflows, APIs, and automation. ## Universal Pay-to-Run The [Universal Webhook](/integrations/universal-webhook) approach works with **any** automation platform that supports webhooks. Create checkouts in the xpay dashboard, receive signed webhook calls after each payment. ## Available Integrations ### Workflow Automation | Platform | Description | Status | |----------|-------------|--------| | [n8n (Self-hosted)](/integrations/n8n) | Custom xpay node for n8n | Available | | [n8n Cloud](/integrations/n8n-cloud) | Standard webhook approach | Available | | [Activepieces](/integrations/activepieces) | Webhook trigger integration | Available | | Zapier | Accept payments in Zaps | Coming Soon | | Make (Integromat) | Monetize Make scenarios | Coming Soon | ### AI & Agents | Platform | Description | Status | |----------|-------------|--------| | LangChain | Protected fetch for LangChain agents | Available | | AutoGPT | Spending limits for autonomous agents | Coming Soon | | CrewAI | Multi-agent payment orchestration | Coming Soon | ### API Frameworks | Platform | Description | Status | |----------|-------------|--------| | Express.js | Paywall middleware for Express APIs | Available | | Next.js | API route protection with x402 | Available | | FastAPI | Python x402 middleware | Coming Soon | --- ## Quick Links - [Universal Webhook Guide](/integrations/universal-webhook) - Works with any platform - [n8n Integration Guide](/integrations/n8n) - Custom node for self-hosted n8n - [n8n Cloud Guide](/integrations/n8n-cloud) - Standard webhook for n8n Cloud - [Activepieces Guide](/integrations/activepieces) - Monetize Activepieces flows - [Developer Resources](/developer-resources) - SDKs, examples, and tools - [x402 Protocol](/x402-protocol) - Learn about the payment protocol --- Need an integration we don't have? [Let us know](https://github.com/xpaysh/xpay/issues) ================================================================================ # Page: /en/integrations/n8n-cloud # Source: src/content/en/integrations/n8n-cloud.mdx ================================================================================ # n8n Cloud Integration Use xpay Pay-to-Run with n8n Cloud using standard webhook nodes - no custom installation required. ## Why This Approach? n8n Cloud doesn't allow unverified community nodes. Instead of the custom xpay node, you'll use: - **Webhook node** as a trigger - **HTTP Request node** for optional signature verification - Standard n8n nodes for your workflow logic This approach works identically to the custom node - you just configure it manually. --- ## Setup Guide ### Step 1: Create Your Webhook in n8n Cloud 1. Open n8n Cloud and create a new workflow 2. Add a **Webhook** node as the trigger 3. Configure it: - **HTTP Method**: POST - **Path**: Choose a unique path (e.g., `/xpay-payment`) - **Response Mode**: Respond immediately 4. Activate the workflow to get your webhook URL ### Step 2: Create a Checkout in xpay 1. Go to [xpay Dashboard](https://app.xpay.sh/dashboard/pay-to-run/new) 2. Create a new checkout: - **Product Name**: Your workflow name - **Price**: Amount in USDC - **Callback URL**: Your n8n webhook URL from Step 1 - **Network**: Base Sepolia (testnet) or Base (mainnet) - **Recipient Wallet**: Your Ethereum wallet address 3. Add any custom fields to collect customer information 4. Save and copy your checkout URL ### Step 3: Connect Your Workflow After the Webhook node, add your workflow logic. The incoming data includes: ```json { "body": { "payment": { "tx_hash": "0x...", "payer_address": "0x...", "amount": 5.00, "currency": "USDC" }, "customer_input": { "email": "customer@example.com" } } } ``` Access payment data: `{{ $json.body.payment.amount }}` Access customer input: `{{ $json.body.customer_input.email }}` --- ## Complete Workflow Example Here's a typical Pay-to-Run workflow: ``` [Webhook] → [IF: Verify Payment] → [Your Logic] → [Respond] ``` ### Example: AI Content Generator 1. **Webhook** - Receives payment confirmation 2. **OpenAI** - Generates content based on customer input 3. **Send Email** - Delivers result to customer 4. **Respond to Webhook** - Returns success --- ## Import Ready-to-Use Template Copy this JSON into n8n Cloud (Ctrl/Cmd + V in the canvas): ```json { "name": "xpay Pay-to-Run Template", "nodes": [ { "parameters": { "httpMethod": "POST", "path": "xpay-payment", "responseMode": "responseNode", "options": {} }, "name": "Webhook", "type": "n8n-nodes-base.webhook", "typeVersion": 2, "position": [250, 300] }, { "parameters": { "respondWith": "json", "responseBody": "={\"success\": true, \"message\": \"Payment processed\"}", "options": {} }, "name": "Respond to Webhook", "type": "n8n-nodes-base.respondToWebhook", "typeVersion": 1, "position": [650, 300] } ], "connections": { "Webhook": { "main": [[{"node": "Respond to Webhook", "type": "main", "index": 0}]] } } } ``` --- ## Optional: Signature Verification For production workflows, verify the webhook signature: 1. Add a **Code** node after Webhook 2. Use this code: ```javascript const crypto = require('crypto'); // Get headers and body const signature = $input.first().headers['x-xpay-signature']; const timestamp = $input.first().headers['x-xpay-timestamp']; const body = $input.first().json.body; // Your webhook secret from xpay dashboard const secret = 'YOUR_WEBHOOK_SECRET'; // Verify signature const data = `${timestamp}.${JSON.stringify(body)}`; const expected = 'sha256=' + crypto .createHmac('sha256', secret) .update(data) .digest('hex'); if (signature !== expected) { throw new Error('Invalid webhook signature'); } return $input.all(); ``` 3. Store your webhook secret in n8n credentials for security --- ## Test Your Integration 1. In xpay dashboard, go to your checkout details 2. Click **Test Webhook** 3. Check your n8n workflow execution history 4. Verify the data flows correctly --- ## Comparison: Custom Node vs Webhook | Feature | Custom Node (Self-hosted) | Webhook (Cloud) | |---------|--------------------------|-----------------| | Setup time | ~2 min | ~5 min | | Signature verification | Automatic | Manual (optional) | | Checkout URL display | In node | In dashboard | | Test mode | Built-in | Dashboard button | | Works on n8n Cloud | No | Yes | --- ## Troubleshooting ### Workflow not triggering 1. Ensure workflow is **active** (toggle in top-right) 2. Check webhook URL is correct in xpay dashboard 3. Verify webhook path matches exactly ### Missing data 1. Check Response Mode is set correctly 2. Verify you're accessing `$json.body` not just `$json` 3. Look at execution log for full payload ### Timeout errors n8n Cloud webhooks have a 30-second timeout. For long-running workflows: 1. Return response immediately with Respond to Webhook node 2. Continue processing after response --- ## Next Steps - [Create your checkout](https://app.xpay.sh/dashboard/pay-to-run/new) - [Universal Webhook Guide](/integrations/universal-webhook) - Deep dive on webhook format - [n8n Self-hosted Guide](/integrations/n8n) - Using the custom node ================================================================================ # Page: /en/integrations/n8n # Source: src/content/en/integrations/n8n.mdx ================================================================================ # n8n Integration Turn any n8n workflow into a paid service in 60 seconds. The \{xpay\} n8n community node creates a hosted payment form - when customers pay, your workflow runs automatically. ## Overview The **xpay pay-to-run trigger** node enables you to: - Accept USDC payments on Base network - Create hosted Pay to Run forms - no frontend required - Collect custom input from customers before payment - Receive payments directly to your wallet (non-custodial) - Test with sandbox mode before going live ## Installation ### n8n Cloud 1. Open **Settings > Community Nodes** 2. Click **Install a community node** 3. Enter `@xpaysh/n8n-nodes-xpay` 4. Click **Install** ### Self-Hosted n8n ```bash npm install @xpaysh/n8n-nodes-xpay ``` Or install via the n8n UI under **Settings > Community Nodes**. ## Quick Start ### Step 1: Get Your API Key 1. Sign up at [app.xpay.sh](https://app.xpay.sh) 2. Go to **Settings > API Keys** 3. Create a new API key 4. Copy the secret key ### Step 2: Add Credentials in n8n 1. Go to **Credentials > Add Credential** 2. Search for "xpay API" 3. Paste your API key 4. Select environment: - **Sandbox** - For testing (no real payments) - **Production** - For real USDC payments ### Step 3: Create Your First Paid Workflow 1. Create a new workflow in n8n 2. Add the **xpay pay-to-run trigger** node 3. Configure: - **Product Name**: e.g., "Premium SEO Audit" - **Price (USDC)**: e.g., 5.00 - **Recipient Wallet**: Your Base wallet address - **Customer Fields**: Add fields like "email", "website" 4. Connect your workflow nodes (HTTP Request, Send Email, etc.) 5. **Activate** the workflow ### Step 4: Get Your Pay to Run Form URL Send an empty POST request to your webhook URL: ```bash curl -X POST https://your-n8n-instance/webhook/abc123 ``` Response: ```json { "message": "xpay pay-to-run trigger is listening!", "form_url": "https://run.xpay.sh/p/chk_abc123", "test_mode": true } ``` Share the `form_url` with your customers. When they visit it, they'll see a payment form with your product details and custom fields. ## Node Properties | Property | Description | |----------|-------------| | **Product Name** | Display name shown on payment form | | **Description** | Brief description of what customer is paying for | | **Price (USDC)** | Amount in USDC (e.g., 5.00 = $5) | | **Network** | Base (production) or Base Sepolia (testnet) | | **Recipient Wallet** | Your wallet address for receiving payments | | **Customer Fields** | Custom input fields for customers to fill | | **Redirect URL** | Optional URL to redirect after payment | | **Test Mode** | Enable sandbox mode (no real payments) | ## Output Data When a customer pays, your workflow receives this data: ```json { "payment": { "txHash": "0x123...", "amount": 5.00, "currency": "USDC", "payer": "0xABC...", "network": "base", "timestamp": 1702841234 }, "input": { "email": "customer@example.com", "website": "https://example.com" }, "metadata": { "checkoutId": "chk_abc123", "receivedAt": "2024-12-17T10:00:00.000Z" } } ``` Use `{{ $json.payment.amount }}` or `{{ $json.input.email }}` in subsequent nodes to access this data. ## Test Mode vs Production Mode | Aspect | Test Mode | Production Mode | |--------|-----------|-----------------| | Payments | Simulated | Real USDC | | Network | Base Sepolia | Base Mainnet | | Signature verification | Skipped | Enforced | | Form URL | Temporary | Persistent | ### Testing Your Workflow With **Test Mode** enabled: 1. Click "Simulate Payment" on the Pay to Run form, or 2. POST test data directly to your webhook: ```bash curl -X POST https://your-n8n-instance/webhook/abc123 \ -H "Content-Type: application/json" \ -d '{"payment":{"amount":5},"input":{"email":"test@example.com"}}' ``` ### Important: URL Persistence - When **testing in n8n** (clicking "Execute workflow"), a temporary checkout is created. This expires when you stop testing. - When you **Activate** the workflow, the checkout URL persists as long as the workflow is active. ## Use Cases ### SEO Audit Service Charge $10 per website audit: 1. Customer enters website URL and email 2. After payment, workflow: - Runs SEO analysis via API - Generates PDF report - Emails report to customer ### API Monetization Sell API access per request: 1. Customer enters API parameters 2. After payment, workflow: - Makes API call with customer's parameters - Returns JSON response - Logs transaction ### Consultation Booking Accept payment before scheduling: 1. Customer enters preferred time and topic 2. After payment, workflow: - Creates calendar event - Sends confirmation email - Adds to CRM ### Digital Product Delivery Deliver files after payment: 1. Customer enters email 2. After payment, workflow: - Generates download link - Sends email with link - Updates inventory ## Security The \{xpay\} n8n node includes multiple security layers: - **Non-custodial**: Payments go directly to your wallet - we never hold your funds - **HMAC signatures**: Production webhooks are signed to prevent tampering - **Replay protection**: Each payment can only trigger your workflow once - **Timestamp validation**: Stale webhook requests are rejected ## Troubleshooting ### "Checkout not found" error The checkout may have expired. This happens when: - You were testing and stopped the test - The workflow was deactivated **Solution**: Activate the workflow to create a persistent checkout. ### Webhook not firing Check that: 1. The workflow is **Activated** (not just testing) 2. Your n8n instance has a public URL (for cloud deployments) 3. Test mode is enabled if you're simulating payments ### Payment went through but workflow didn't run 1. Check n8n execution logs for errors 2. Verify the webhook URL is correct 3. In production mode, check that webhook signature verification passed ## Resources - [GitHub Repository](https://github.com/xpaysh/n8n-nodes-xpay) - [npm Package](https://www.npmjs.com/package/@xpaysh/n8n-nodes-xpay) - [n8n Community Nodes Guide](https://docs.n8n.io/integrations/community-nodes/) --- Need help? [Open an issue](https://github.com/xpaysh/n8n-nodes-xpay/issues) or email xpaysh@gmail.com ================================================================================ # Page: /en/integrations/universal-webhook # Source: src/content/en/integrations/universal-webhook.mdx ================================================================================ # Universal Pay-to-Run Webhook Accept payments for any workflow using standard webhooks. Works with any automation platform - no custom integrations required. ## Overview Universal Pay-to-Run lets you monetize any automation workflow by: 1. Creating a checkout in your \{xpay\} dashboard 2. Getting a payment form URL and webhook secret 3. Adding a webhook node in your automation platform 4. Receiving signed webhook calls after each payment ### Supported Platforms | Platform | Integration Type | Setup Time | |----------|-----------------|------------| | n8n (self-hosted) | Custom node or webhook | ~2 min | | n8n Cloud | Standard webhook | ~5 min | | Activepieces | Webhook trigger | ~5 min | | Make (Integromat) | Custom webhook | ~5 min | | Zapier | Webhooks by Zapier | ~5 min | --- ## Quick Start ### Step 1: Create a Checkout Visit your [xpay dashboard](https://app.xpay.sh/dashboard/pay-to-run) and create a new checkout: 1. Set your product name and price 2. Enter your automation platform's webhook URL 3. Configure form fields to collect customer information 4. Save and copy your checkout URL ### Step 2: Set Up Your Webhook In your automation platform, create a webhook trigger node that listens for POST requests. Configure it with: - **Method**: POST - **Content-Type**: application/json - **Response**: Return 200 OK on success ### Step 3: Share Your Checkout URL Share your checkout URL (`https://run.xpay.sh/p/your-checkout-id`) with customers. After payment: 1. Customer pays on your checkout page 2. xpay sends a signed webhook to your callback URL 3. Your workflow executes with the payment data --- ## Webhook Payload When a payment is received, xpay sends a POST request to your callback URL with this payload: ```json { "payment": { "tx_hash": "0x1234...abcd", "payer_address": "0xabc...123", "amount": 5.00, "currency": "USDC", "network": "base", "timestamp": 1703001234567 }, "customer_input": { "email": "customer@example.com", "name": "John Doe" }, "metadata": { "checkout_id": "chk_abc123", "test_mode": false, "triggered_at": "2024-12-20T10:00:00Z" } } ``` ### Headers Each webhook request includes these headers for verification: | Header | Description | |--------|-------------| | `X-xPay-Signature` | HMAC-SHA256 signature of the payload | | `X-xPay-Timestamp` | Unix timestamp when the webhook was sent | | `X-xPay-Test` | "true" if this is a test webhook | --- ## Signature Verification For production use, verify webhook signatures to ensure requests come from xpay. ### Node.js Example ```javascript const crypto = require('crypto'); function verifyWebhookSignature(payload, signature, timestamp, secret) { const data = `${timestamp}.${JSON.stringify(payload)}`; const expectedSignature = crypto .createHmac('sha256', secret) .update(data) .digest('hex'); return crypto.timingSafeEquals( Buffer.from(signature), Buffer.from(`sha256=${expectedSignature}`) ); } // In your webhook handler: const isValid = verifyWebhookSignature( req.body, req.headers['x-xpay-signature'], req.headers['x-xpay-timestamp'], process.env.WEBHOOK_SECRET ); if (!isValid) { return res.status(401).send('Invalid signature'); } ``` ### Python Example ```python import hmac import hashlib import json def verify_webhook_signature(payload, signature, timestamp, secret): data = f"{timestamp}.{json.dumps(payload, separators=(',', ':'))}" expected = hmac.new( secret.encode(), data.encode(), hashlib.sha256 ).hexdigest() return hmac.compare_digest(signature, f"sha256={expected}") ``` --- ## Test Mode Use test mode to verify your integration without real payments: 1. Enable "Test Mode" when creating your checkout 2. Click "Test Webhook" in the checkout details page 3. Your workflow receives a test payload with `test_mode: true` Test webhooks have the same structure as production webhooks, with mock transaction data. --- ## Platform-Specific Guides - [n8n (self-hosted)](/integrations/n8n) - Use the custom xpay node - [n8n Cloud](/integrations/n8n-cloud) - Standard webhook approach - [Activepieces](/integrations/activepieces) - Webhook trigger guide --- ## Troubleshooting ### Webhook not received 1. Check your callback URL is publicly accessible 2. Verify your server returns 200 OK 3. Check for firewall or rate limiting issues 4. Use the "Test Webhook" button to debug ### Invalid signature 1. Ensure you're using the correct webhook secret 2. Check that you're parsing the JSON correctly 3. Verify timestamp is being read as a string ### Timeout errors xpay waits up to 10 seconds for a response. If your workflow takes longer: 1. Return 200 OK immediately 2. Process the workflow asynchronously 3. Use a message queue if needed --- ## Next Steps - [Create your first checkout](https://app.xpay.sh/dashboard/pay-to-run/new) - [Learn about the x402 protocol](/x402-protocol) - [View webhook examples on GitHub](https://github.com/xpaysh/xpay-examples) ================================================================================ # Page: /en/products/mcp-monetization # Source: src/content/en/products/mcp-monetization.mdx ================================================================================ # MCP Monetization Monetize any MCP (Model Context Protocol) server with pay-per-tool-call billing. Wrap your existing MCP server with an xpay proxy and start earning from every tool invocation. ## Overview MCP Monetization lets you place a payment layer in front of any MCP server. When an AI assistant (Claude, Cursor, Windsurf, etc.) calls a tool on your server, the payment is processed automatically via the x402 protocol before the tool executes. - **Zero code changes** - Your MCP server stays exactly as it is - **Per-tool pricing** - Set different prices for different tools - **Instant payouts** - Revenue flows directly to your wallet via USDC - **Works everywhere** - Compatible with any MCP client ## How It Works ```mermaid sequenceDiagram participant Client as AI Assistant participant Proxy as xpay MCP Proxy participant MCP as Your MCP Server participant Chain as Base (L2) Client->>Proxy: Call tool (e.g. search_web) Proxy->>Proxy: Check pricing for tool Proxy->>Client: 402 Payment Required Client->>Chain: Sign USDC payment Client->>Proxy: Retry with payment proof Proxy->>Proxy: Verify payment Proxy->>MCP: Forward tool call MCP->>Proxy: Tool result Proxy->>Client: Tool result ``` 1. You register your MCP server URL on xpay and set per-tool pricing 2. xpay gives you a proxy URL: `https://{slug}.mcp.xpay.sh/mcp` 3. Users connect their AI assistant to the proxy URL instead of your server directly 4. Every tool call is metered and paid for automatically ## Quick Start ### 1. Register Your MCP Server Go to [xpay.sh](https://xpay.sh) and create a new MCP monetization endpoint: - **Server URL**: Your MCP server's SSE or Streamable HTTP endpoint - **Receiving wallet**: Your USDC wallet address on Base - **Pricing**: Set a default price per tool call, or configure per-tool pricing ### 2. Configure Per-Tool Pricing Set different prices for each tool your server exposes: | Tool | Price | Description | |------|-------|-------------| | `search_web` | $0.01 | Basic web search | | `deep_research` | $0.10 | Multi-source research | | `generate_report` | $0.25 | Full report generation | You can also set a flat rate that applies to all tools. ### 3. Share Your Proxy URL Give users your proxy URL to connect in their AI assistant: ``` https://my-service.mcp.xpay.sh/mcp ``` ### 4. Connect in Claude Desktop Users add your monetized MCP server to their `claude_desktop_config.json`: ```json { "mcpServers": { "my-service": { "url": "https://my-service.mcp.xpay.sh/mcp", "headers": { "Authorization": "Bearer USER_API_KEY" } } } } ``` ### 5. Connect in Cursor / Windsurf In Cursor or Windsurf settings, add the MCP server URL: ``` https://my-service.mcp.xpay.sh/mcp ``` The AI assistant will automatically handle x402 payments when calling tools. ## Pricing Configuration ### Flat Rate Charge the same price for every tool call: ```json { "pricing": { "model": "flat", "price": 0.05, "currency": "USDC" } } ``` ### Per-Tool Pricing Set individual prices for each tool: ```json { "pricing": { "model": "per_tool", "currency": "USDC", "tools": { "search": 0.01, "analyze": 0.05, "generate": 0.10 }, "default": 0.02 } } ``` The `default` price applies to any tool not explicitly listed. ## API Key Management Buyers authenticate with an API key to track their usage and manage spending: - **Get an API key** from [hub.xpay.sh](https://hub.xpay.sh) - **Include it** in the `Authorization` header when connecting to the MCP proxy - **Track usage** and spending in the xpay dashboard - **Set spending limits** to control costs ## Billing Receipts After each tool call, the proxy includes billing metadata in the response: ```json { "result": { "...tool output..." }, "_billing": { "tool": "search_web", "cost": "0.01", "currency": "USDC", "txHash": "0xabc...", "network": "base", "timestamp": "2026-02-22T10:30:00Z" } } ``` ## Supported MCP Transports - **Streamable HTTP** (recommended) - Modern HTTP-based transport - **SSE (Server-Sent Events)** - Legacy streaming transport ## Use Cases - **Data providers** - Monetize search, enrichment, and lookup tools - **AI model wrappers** - Charge per inference via MCP tools - **SaaS integrations** - Expose your product's API as paid MCP tools - **Research services** - Charge for web scraping, analysis, and report generation --- Ready to monetize your MCP server? [Get started on xpay.sh](https://xpay.sh) or explore the [x402 Protocol](/x402-protocol) to understand the payment layer. ================================================================================ # Page: /en/products/paywall-service # Source: src/content/en/products/paywall-service.mdx ================================================================================ # Paywall-as-a-Service Transform any API into a revenue stream with x402-powered automatic payments. The Paywall Service provides instant API monetization with zero setup complexity. ## Overview The Paywall Service wraps your existing APIs with x402 payment requirements, enabling: - **Instant monetization** - Start earning from APIs immediately - **Zero integration complexity** - Works with any existing API - **Automatic payment processing** - Handles all payment logic - **Real-time revenue tracking** - Monitor earnings as they happen - **Flexible pricing models** - Per-request, tiered, subscription options ## Quick Start ### 1. Basic API Monetization Turn any endpoint into a paid service in minutes: ```typescript import { Paywall } from '@xpaysh/agent-kit' import express from 'express' const app = express() const paywall = new Paywall({ receivingWallet: '0x742d35Cc6634C0532925a3b8D3Ac2d00fBc1d555', facilitatorUrl: 'https://facilitator.xpay.sh' }) // Protect your valuable API app.get('/api/premium-data', paywall.middleware({ price: 0.10, // $0.10 per request description: 'Premium market data access' }), (req, res) => { // This code only runs after successful payment const marketData = { prices: { BTC: 45000, ETH: 3000 }, timestamp: new Date().toISOString(), premium: true } res.json(marketData) } ) app.listen(3000, () => { console.log('Monetized API running on port 3000') }) ``` ### 2. Advanced Pricing Configuration ```typescript // Tiered pricing based on usage app.post('/api/ai-analysis', paywall.middleware({ pricing: { model: 'tiered', basePrice: 0.01, tiers: [ { from: 0, to: 100, price: 0.05 }, // First 100 requests: $0.05 { from: 100, to: 1000, price: 0.03 }, // Next 900 requests: $0.03 { from: 1000, price: 0.01 } // Beyond 1000: $0.01 ] }, description: 'AI-powered data analysis' }), async (req, res) => { const analysis = await performAIAnalysis(req.body.data) res.json({ analysis, tier: req.paymentTier }) } ) // Token-based pricing for LLM APIs app.post('/api/llm-completion', paywall.middleware({ pricing: { model: 'per_token', basePrice: 0.0001, // $0.0001 per token estimateTokens: (req) => { // Estimate tokens from request return req.body.prompt.length / 4 // Rough estimation } } }), async (req, res) => { const completion = await callLLM(req.body.prompt) res.json({ completion, tokensUsed: completion.usage.total_tokens, cost: completion.usage.total_tokens * 0.0001 }) } ) ``` ## Pricing Models ### Per-Request Pricing Simple flat rate per API call: ```typescript const paywall = new Paywall({ receivingWallet: '0x...', defaultPricing: { model: 'per_request', basePrice: 0.05, // $0.05 per request currency: 'USDC' } }) ``` ### Tiered Pricing Progressive pricing based on usage volume: ```typescript app.use('/api/data', paywall.middleware({ pricing: { model: 'tiered', basePrice: 0.10, tiers: [ { from: 0, to: 50, price: 0.10 }, // First 50: $0.10 each { from: 50, to: 200, price: 0.08 }, // Next 150: $0.08 each { from: 200, to: 500, price: 0.06 }, // Next 300: $0.06 each { from: 500, price: 0.05 } // Beyond 500: $0.05 each ] }, // Reset tiers daily per customer tierReset: 'daily' })) ``` ### Token-Based Pricing Perfect for AI and LLM APIs: ```typescript app.post('/api/text-generation', paywall.middleware({ pricing: { model: 'per_token', inputTokenPrice: 0.00001, // $0.00001 per input token outputTokenPrice: 0.00003, // $0.00003 per output token minimumCharge: 0.001 // Minimum $0.001 per request } }), async (req, res) => { const result = await generateText(req.body.prompt) // Payment automatically calculated based on actual token usage res.json({ text: result.text, usage: { inputTokens: result.inputTokens, outputTokens: result.outputTokens, totalCost: result.inputTokens * 0.00001 + result.outputTokens * 0.00003 } }) }) ``` ### Time-Based Pricing Charge per minute or hour of usage: ```typescript app.ws('/api/realtime-stream', paywall.middleware({ pricing: { model: 'per_minute', basePrice: 0.02, // $0.02 per minute billingInterval: 60 // Bill every 60 seconds } }), (ws, req) => { // WebSocket connection with per-minute billing ws.on('message', (data) => { // Stream real-time data const streamData = processRealtimeData(data) ws.send(JSON.stringify(streamData)) }) }) ``` ## Revenue Optimization ### Dynamic Pricing Adjust prices based on demand, time, or customer tier: ```typescript app.get('/api/premium-content', paywall.middleware({ dynamicPricing: async (req) => { const hour = new Date().getHours() const isBusinessHours = hour >= 9 && hour <= 17 // Higher prices during business hours const basePrice = isBusinessHours ? 0.15 : 0.10 // Customer tier pricing const customerTier = await getCustomerTier(req.headers.authorization) const tierMultiplier = { 'basic': 1.0, 'premium': 0.8, // 20% discount 'enterprise': 0.6 // 40% discount }[customerTier] || 1.0 return { price: basePrice * tierMultiplier, description: `${customerTier} tier pricing` } } }), (req, res) => { res.json({ content: 'Premium content', tier: req.customerTier }) }) ``` ### Bundle Pricing Offer discounts for multiple API calls: ```typescript app.post('/api/batch-process', paywall.middleware({ bundlePricing: { singlePrice: 0.10, // $0.10 per individual request bundlePrice: 0.08, // $0.08 per request in bundle minimumBundle: 10, // Minimum 10 requests for bundle pricing maximumBundle: 100 // Maximum 100 requests per bundle } }), async (req, res) => { const { requests } = req.body if (requests.length >= 10) { // Process as discounted bundle const results = await processBatch(requests) res.json({ results, bundleDiscount: (0.10 - 0.08) * requests.length }) } else { // Process individual requests const results = await processIndividual(requests) res.json({ results }) } }) ``` ## Advanced Features ### Rate Limiting Integration Combine payment requirements with rate limiting: ```typescript import rateLimit from 'express-rate-limit' // Free tier with rate limits const freeTierLimit = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // 100 requests per window message: 'Free tier limit exceeded. Upgrade to paid tier for unlimited access.' }) // Paid tier with higher limits app.get('/api/free-data', freeTierLimit, (req, res) => { res.json({ data: 'Free tier data', limited: true }) }) app.get('/api/unlimited-data', paywall.middleware({ price: 0.01 }), (req, res) => { res.json({ data: 'Unlimited paid data', limited: false }) } ) ``` ### Customer Analytics Track customer usage patterns and optimize pricing: ```typescript app.use(paywall.analyticsMiddleware({ trackMetrics: [ 'request_count', 'revenue_per_customer', 'average_request_cost', 'customer_lifetime_value' ], webhookUrl: 'https://your-app.com/webhooks/analytics' })) // Get customer analytics app.get('/admin/customer-analytics', async (req, res) => { const analytics = await paywall.getCustomerAnalytics({ timeframe: '30d', includeChurn: true, includeRetention: true }) res.json({ totalCustomers: analytics.totalCustomers, avgRevenuePerCustomer: analytics.avgRevenuePerCustomer, topSpenders: analytics.topSpenders, churnRate: analytics.churnRate }) }) ``` ### Custom Payment Flow Handle complex payment scenarios: ```typescript app.post('/api/complex-service', async (req, res) => { try { // Pre-validate payment capability const paymentCheck = await paywall.checkPaymentCapability(req.headers, { estimatedCost: 0.50, currency: 'USDC' }) if (!paymentCheck.canPay) { return res.status(402).json({ error: 'Insufficient funds', required: 0.50, available: paymentCheck.availableBalance, topUpUrl: paymentCheck.topUpUrl }) } // Process service (expensive operation) const result = await performExpensiveOperation(req.body) // Calculate actual cost based on processing const actualCost = calculateActualCost(result.complexity) // Charge the actual cost const payment = await paywall.processPayment(req.headers, { amount: actualCost, description: `Complex service processing (${result.complexity} complexity)`, metadata: { requestId: req.id, complexity: result.complexity } }) res.json({ result: result.data, payment: { cost: actualCost, transactionId: payment.transactionId, complexity: result.complexity } }) } catch (error) { if (error.code === 'PAYMENT_FAILED') { res.status(402).json({ error: 'Payment failed', details: error.message }) } else { res.status(500).json({ error: 'Service error' }) } } }) ``` ## Webhook Integration Monitor payments and customer behavior in real-time: ```typescript // Configure webhooks for payment events await paywall.configureWebhooks({ endpoint: 'https://your-app.com/webhooks/paywall', events: [ 'payment.completed', 'payment.failed', 'customer.first_payment', 'revenue.milestone', 'pricing.tier_changed' ], secret: 'webhook_secret_key' }) // Handle webhook events app.post('/webhooks/paywall', (req, res) => { const { event, data } = req.body switch (event) { case 'payment.completed': // Track successful payment analytics.track('payment_completed', { customerId: data.customerId, amount: data.amount, endpoint: data.endpoint }) break case 'customer.first_payment': // Welcome new paying customer sendWelcomeEmail(data.customerId) break case 'revenue.milestone': // Celebrate revenue milestones if (data.milestone === 1000) { notifyTeam(`🎉 Hit $1000 in API revenue!`) } break } res.status(200).send('OK') }) ``` ## Security Best Practices ### Payment Verification Always verify payments on your server: ```typescript app.post('/api/secure-endpoint', async (req, res) => { // Verify payment headers const paymentValid = await paywall.verifyPayment(req.headers, { price: 0.25, tolerance: 0.001, // Allow 0.1% tolerance for gas fluctuations maxAge: 300 // Payment must be within 5 minutes }) if (!paymentValid.valid) { return res.status(402).json({ error: 'Invalid payment', reason: paymentValid.reason, required: paymentValid.expectedPayment }) } // Process request only after payment verification const secureData = await getSecureData() res.json(secureData) }) ``` ### Rate Limiting & DDoS Protection Protect against abuse while maintaining legitimate access: ```typescript // Implement progressive rate limiting const createRateLimit = (windowMs, max, price) => rateLimit({ windowMs, max, handler: (req, res) => { res.status(429).json({ error: 'Rate limit exceeded', resetTime: new Date(Date.now() + windowMs), upgradeOption: { price: price, description: 'Pay per request to bypass rate limits' } }) } }) // Free tier: 10 requests per minute app.use('/api/free', createRateLimit(60 * 1000, 10, 0.01)) // Paid tier: No rate limits app.use('/api/paid', paywall.middleware({ price: 0.01 })) ``` ### Wallet Security Protect your receiving wallet: ```typescript const paywall = new Paywall({ receivingWallet: process.env.XPAY_RECEIVING_WALLET, // Use environment variables facilitatorUrl: 'https://facilitator.xpay.sh', security: { requireHttps: true, // Only accept HTTPS requests validateOrigin: true, // Validate request origin maxPaymentAge: 300, // 5 minute payment window enableIPWhitelist: false, // Enable for high-security applications rateLimitByWallet: true // Rate limit per wallet address } }) ``` ## Deployment Guide ### Production Configuration ```typescript import { Paywall } from '@xpaysh/agent-kit' import Redis from 'ioredis' const redis = new Redis(process.env.REDIS_URL) const paywall = new Paywall({ receivingWallet: process.env.XPAY_RECEIVING_WALLET, facilitatorUrl: process.env.XPAY_FACILITATOR_URL, // Production optimizations cache: { provider: redis, paymentTTL: 300, // Cache payments for 5 minutes customerTTL: 3600 // Cache customer data for 1 hour }, monitoring: { enableMetrics: true, metricsPort: 9090, // Prometheus metrics healthCheckEndpoint: '/health' }, logging: { level: 'info', destination: 'datadog', // or 'console', 'file' apiKey: process.env.DATADOG_API_KEY } }) ``` ### Docker Deployment ```dockerfile FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . ENV NODE_ENV=production ENV XPAY_RECEIVING_WALLET=${XPAY_RECEIVING_WALLET} ENV XPAY_FACILITATOR_URL=${XPAY_FACILITATOR_URL} EXPOSE 3000 HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost:3000/health || exit 1 CMD ["npm", "start"] ``` ### Kubernetes Configuration ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: xpay-paywall-api spec: replicas: 3 selector: matchLabels: app: xpay-paywall-api template: metadata: labels: app: xpay-paywall-api spec: containers: - name: api image: your-registry/xpay-paywall:latest ports: - containerPort: 3000 env: - name: XPAY_RECEIVING_WALLET valueFrom: secretKeyRef: name: xpay-secrets key: receiving-wallet resources: requests: cpu: 100m memory: 128Mi limits: cpu: 500m memory: 512Mi livenessProbe: httpGet: path: /health port: 3000 initialDelaySeconds: 30 periodSeconds: 10 ``` ## Migration Guide ### From Free API to Paid Gradually migrate existing free APIs: ```typescript // Phase 1: Optional payments (donations) app.get('/api/data', async (req, res) => { const data = await getData() // Include payment information in response res.json({ data, support: { message: 'Support this API with a small payment', suggestedAmount: 0.01, paymentDetails: paywall.getPaymentDetails(0.01) } }) }) // Phase 2: Freemium model app.get('/api/data', async (req, res) => { const isPaid = await paywall.checkPayment(req.headers, { price: 0.05 }) if (isPaid) { // Full data for paying customers const fullData = await getFullData() res.json({ data: fullData, tier: 'premium' }) } else { // Limited data for free users const limitedData = await getLimitedData() res.json({ data: limitedData, tier: 'free', upgrade: paywall.getPaymentDetails(0.05) }) } }) // Phase 3: Fully paid app.get('/api/data', paywall.middleware({ price: 0.05 }), async (req, res) => { const data = await getData() res.json({ data }) } ) ``` --- Ready to start monetizing your APIs? Check our [getting started guide](/getting-started) or explore [advanced integration patterns](/developer-resources/integration-patterns). ================================================================================ # Page: /en/products/smart-proxy # Source: src/content/en/products/smart-proxy.mdx ================================================================================ # Smart Proxy The Smart Proxy is a cost control dashboard that provides developers with peace of mind when deploying autonomous agents. It acts as a proxy between your agents and x402-powered APIs, ensuring agents never overspend while maintaining full functionality. ## The Problem **Developers are terrified their agent will get stuck in a loop and spend thousands of dollars on x402-powered APIs.** Autonomous agents can make hundreds of API calls per minute. Without proper controls, a bug or unexpected behavior could result in: - 💸 Runaway spending from infinite loops - 📈 Unexpected cost spikes during high-traffic periods - 🚫 No visibility into real-time spending - ⏰ No way to stop spending once it starts ## The Solution The Smart Proxy provides an AWS-hosted proxy endpoint that sits between your agents and x402 APIs. It offers: ### 🛡️ Hard Spending Limits - **Per-request limits**: Maximum spend per API call - **Daily/monthly budgets**: Automatic shutoffs when limits reached - **Per-agent budgets**: Individual spending controls for each agent - **Global limits**: Organization-wide spending controls ### 📊 Real-time Monitoring - **Live spending dashboard**: Track costs as they happen - **Usage analytics**: Detailed breakdowns by agent, API, and time - **Cost forecasting**: Predict monthly costs based on current usage - **Anomaly detection**: Alerts for unusual spending patterns ### ⚡ Instant Alerts - **Slack/Discord notifications**: Real-time spending alerts - **Email alerts**: Daily/weekly spending summaries - **Webhook integration**: Custom alert handling - **Emergency shutoffs**: Automatic agent pausing when limits exceeded ## Features ### Multi-Agent Management Manage multiple agents from a single dashboard with complete lifecycle control: ```typescript import { SmartProxy } from '@xpaysh/agent-kit' const smartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-abc123.xpay.sh', apiKey: 'xpay_fw_...' }) // Create agents with complete configuration await smartProxy.createAgent({ id: 'customer-support-bot', name: 'Customer Support Agent', description: 'Handles customer inquiries and support tickets', walletAddress: '0x742d35Cc6634C0532925a3b8D3Ac2d00fBc1d555', dailyLimit: 50, // $50 USDC per day perCallLimit: 2, // $2 USDC per API call monthlyLimit: 1000, // $1000 USDC per month allowedAPIs: ['openai.com', 'anthropic.com'], status: 'active' }) await smartProxy.createAgent({ id: 'data-analysis-bot', name: 'Data Analysis Agent', description: 'Processes large datasets and generates reports', walletAddress: '0x853d46Dd7744C3dC23c3e8F3Bd2dF1e6fc1e8666', dailyLimit: 200, perCallLimit: 10, monthlyLimit: 5000, allowedAPIs: ['*'], // Allow all x402-enabled APIs status: 'active' }) // Update agent configuration await smartProxy.updateAgent('customer-support-bot', { dailyLimit: 75, // Increase daily limit perCallLimit: 3 }) // Pause agent temporarily await smartProxy.pauseAgent('data-analysis-bot') // Get agent status and spending const agent = await smartProxy.getAgent('customer-support-bot') console.log(`Agent spent: $${agent.totalSpent} / $${agent.dailyLimit}`) ``` ### Intelligent Routing The smart proxyintelligently routes requests based on agent configuration: ```typescript // Agent requests are automatically routed through smart proxy const response = await fetch('https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { 'X-Agent-ID': 'customer-support-bot', 'X-SmartProxy-Token': smartProxy.getToken(), 'Authorization': 'Bearer sk-...' }, body: JSON.stringify({ model: 'gpt-4', messages: [{ role: 'user', content: 'Hello' }] }) }) ``` ### Real-World Configuration Examples Here are common agent configuration patterns for different use cases: #### Customer Service Agent ```typescript await smartProxy.createAgent({ id: 'customer-service-v1', name: 'Customer Service Bot', description: 'Handles customer inquiries during business hours', walletAddress: '0x...', dailyLimit: 25, // Conservative limit for customer interactions perCallLimit: 0.50, // Small cost per interaction monthlyLimit: 500, // Monthly budget control allowedAPIs: ['openai.com'], // Only trusted LLM provider emergencyContact: 'devops@company.com', businessHours: { enabled: true, timezone: 'America/New_York', schedule: '09:00-17:00' // Only active during business hours } }) ``` #### Data Processing Agent ```typescript await smartProxy.createAgent({ id: 'data-processor-prod', name: 'Production Data Processor', description: 'Processes customer data and generates reports', walletAddress: '0x...', dailyLimit: 100, // Higher limit for data processing perCallLimit: 5, // Larger requests for bulk processing monthlyLimit: 2000, // Monthly budget for data operations allowedAPIs: ['*'], // Allow various data processing APIs rateLimiting: { maxConcurrentRequests: 3, // Prevent overwhelming APIs requestsPerMinute: 30 } }) ``` #### Development/Testing Agent ```typescript await smartProxy.createAgent({ id: 'dev-test-agent', name: 'Development Testing Agent', description: 'Agent for development and testing purposes', walletAddress: '0x...', dailyLimit: 10, // Low limit for testing perCallLimit: 1, // Small requests during development monthlyLimit: 200, // Development budget allowedAPIs: ['openai.com', 'anthropic.com'], autoShutoff: { enabled: true, threshold: 0.9 // Auto-pause at 90% of daily limit } }) ``` ### Advanced Controls #### Time-based Limits ```typescript await smartProxy.setScheduledLimits('trading-bot', { // Higher limits during market hours '09:00-16:00': { maxPerRequest: 5, maxHourly: 100 }, // Lower limits overnight '16:00-09:00': { maxPerRequest: 1, maxHourly: 20 } }) ``` #### API-specific Limits ```typescript await smartProxy.setAPILimits('data-bot', { 'openai.com': { maxPerRequest: 2, maxDaily: 50 }, 'anthropic.com': { maxPerRequest: 1, maxDaily: 30 }, 'huggingface.co': { maxPerRequest: 0.5, maxDaily: 20 } }) ``` #### Cost-based Routing ```typescript await smartProxy.setCostRouting('smart-bot', { // Use cheaper APIs first strategy: 'cost-optimized', fallbacks: [ { api: 'huggingface.co', maxCost: 0.01 }, { api: 'openai.com', maxCost: 0.05 }, { api: 'anthropic.com', maxCost: 0.10 } ] }) ``` ## Dashboard Features ### Real-time Overview The web dashboard provides instant visibility into agent spending: - **Live spending meter**: Current daily/monthly spend vs limits - **Active agents**: Which agents are currently making requests - **Top spenders**: Agents consuming the most budget - **Recent transactions**: Live feed of x402 payments ### Analytics & Insights Deep analytics help optimize agent performance: - **Cost per response**: Average cost by model and API - **Request patterns**: Usage patterns throughout the day - **Efficiency metrics**: Cost vs quality analysis - **Budget utilization**: How efficiently agents use their budgets ### Alert Configuration Flexible alerting keeps you informed: ```javascript // Configure alerts in dashboard or via API { "alerts": [ { "trigger": "daily_spend_80_percent", "channels": ["slack", "email"], "message": "Agent {agent_id} has spent 80% of daily budget" }, { "trigger": "unusual_spending_pattern", "channels": ["discord"], "message": "Anomalous spending detected for {agent_id}" } ] } ``` ## Pricing The Smart Proxy uses a freemium SaaS model: ### Free Tier - Up to 3 agents - $100/month total spending limit - Basic analytics (7-day history) - Email alerts only - Community support ### Pro Tier - $49/month - Up to 25 agents - $10,000/month total spending limit - Advanced analytics (90-day history) - All alert channels (Slack, Discord, webhooks) - Priority support - Custom API integrations ### Enterprise Tier - Custom pricing - Unlimited agents - Custom spending limits - 1-year+ analytics retention - White-label dashboard - SSO integration - Dedicated support - On-premise deployment options ## Getting Started ### 1. Create Smart Proxy Instance Sign up and create your first smart proxy: ```bash npx @xpaysh/cli smart-proxy create --name "my-agents" ``` This creates a unique endpoint: `https://smart-proxy-abc123.xpay.sh` ### 2. Configure Your First Agent ```typescript import { SmartProxy } from '@xpaysh/agent-kit' const smartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-abc123.xpay.sh', apiKey: process.env.XPAY_SMART_PROXY_KEY }) await smartProxy.configureAgent('my-first-agent', { maxDailySpend: 25, maxPerRequest: 1, alertThreshold: 0.8 // Alert at 80% }) ``` ### 3. Route Agent Requests Update your agent to use the smart proxy: ```typescript // Before: Direct API calls const response = await fetch('https://api.openai.com/v1/chat/completions', { // ... request config }) // After: Smart Proxy-protected calls const response = await smartProxy.protectedFetch('https://api.openai.com/v1/chat/completions', { agentId: 'my-first-agent', // ... request config }) ``` ### 4. Monitor in Dashboard Visit your dashboard to see real-time spending: `https://dashboard.xpay.sh/smart-proxy/abc123` ## Error Handling & Recovery ### Handling Spending Limit Errors ```typescript import { SmartProxy, SpendingLimitError } from '@xpaysh/agent-kit' async function makeProtectedRequest(agentId: string, apiCall: () => Promise) { try { return await smartProxy.protectedFetch(apiCall, { agentId }) } catch (error) { if (error instanceof SpendingLimitError) { switch (error.limitType) { case 'daily': console.log(`Agent ${agentId} hit daily limit. Retry tomorrow.`) // Queue request for next day await scheduleRetryTomorrow(agentId, apiCall) break case 'per_request': console.log(`Request too expensive for agent ${agentId}`) // Try with a cheaper model or reduce request size return await fallbackToSmallerModel(agentId, apiCall) case 'monthly': console.log(`Agent ${agentId} hit monthly budget`) // Alert administrators and pause agent await notifyAdmins(agentId, 'monthly_limit_exceeded') await smartProxy.pauseAgent(agentId) break } } throw error } } ``` ### Automatic Fallback Strategies ```typescript // Configure agents with fallback chains await smartProxy.createAgent({ id: 'smart-agent', name: 'Cost-Optimized Agent', walletAddress: '0x...', dailyLimit: 50, fallbackChain: [ { provider: 'openai.com', model: 'gpt-3.5-turbo', maxCost: 0.01 }, { provider: 'anthropic.com', model: 'claude-haiku', maxCost: 0.02 }, { provider: 'openai.com', model: 'gpt-4', maxCost: 0.05 } ], onLimitExceeded: 'pause_and_notify' }) ``` ### Real-time Monitoring ```typescript // Set up webhooks for real-time monitoring await smartProxy.configureWebhooks({ endpoint: 'https://your-app.com/webhooks/xpay', events: [ 'agent.spending.warning', // 80% of limit reached 'agent.spending.exceeded', // Limit exceeded 'agent.paused', // Agent automatically paused 'agent.request.failed', // Request failed 'agent.unusual_pattern' // Unusual spending pattern detected ], secret: 'webhook_secret_key' }) // Handle webhook in your application app.post('/webhooks/xpay', (req, res) => { const { event, data } = req.body switch (event) { case 'agent.spending.warning': // Notify team that agent is approaching limits notifySlack(`Agent ${data.agentId} at ${data.percentUsed}% of daily limit`) break case 'agent.spending.exceeded': // Log incident and review agent configuration logger.warn('Agent spending limit exceeded', data) reviewAgentLimits(data.agentId) break } res.status(200).send('OK') }) ``` ## Best Practices ### Agent Configuration - **Start conservative**: Begin with low limits and increase as needed - **Use agent-specific limits**: Different agents have different cost profiles - **Monitor for a week**: Establish baseline spending patterns before setting final limits - **Enable all alerts**: Early detection prevents costly surprises - **Set up webhooks**: Get real-time notifications for spending events - **Use descriptive names**: Clear agent names help with monitoring and debugging ### Cost Optimization - **Implement retries**: Handle temporary payment failures gracefully - **Cache responses**: Avoid repeated API calls for identical requests - **Use cheaper models**: Start with smaller models, escalate to larger ones only when needed - **Batch requests**: Combine multiple operations when APIs support it ### Security - **Rotate API keys**: Regular key rotation prevents unauthorized usage - **Use separate wallets**: Don't use your personal wallet for agent payments - **Monitor for unusual patterns**: Set up anomaly detection alerts - **Regular audits**: Review agent spending patterns monthly ## Integration Examples ### LangChain Integration ```typescript import { LLMChain } from 'langchain/chains' import { OpenAI } from 'langchain/llms/openai' import { SmartProxy } from '@xpaysh/agent-kit' const smartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-abc123.xpay.sh', apiKey: process.env.XPAY_SMART_PROXY_KEY }) // Create protected LLM const llm = new OpenAI({ openAIApiKey: process.env.OPENAI_API_KEY, // Override fetch to use smart proxy fetch: (url, init) => smartProxy.protectedFetch(url, { ...init, agentId: 'langchain-agent' }) }) const chain = new LLMChain({ llm, prompt }) ``` ### AutoGPT Integration ```python # Python example for AutoGPT from xpay import SmartProxy smartProxy = SmartProxy( endpoint='https://smart-proxy-abc123.xpay.sh', api_key=os.getenv('XPAY_SMART_PROXY_KEY') ) # Configure AutoGPT agent smartProxy.configure_agent('autogpt-main', { 'max_daily_spend': 100, 'max_per_request': 5, 'allowed_apis': ['openai.com', 'anthropic.com'] }) # Override HTTP client import requests session = requests.Session() session.request = smartProxy.protected_request ``` ## FAQ ### How does the smart proxyhandle API keys? The smart proxyacts as a transparent proxy - your API keys are passed through securely and never stored. The smart proxyonly adds spending controls and monitoring. ### What happens when limits are exceeded? When a limit is exceeded, the smart proxyreturns a `429 Too Many Requests` response with details about which limit was hit and when the agent can retry. ### Can I use the smart proxywith non-x402 APIs? Currently, the smart proxyis designed specifically for x402-enabled APIs. Support for traditional APIs with custom billing may be added in the future. ### Is there latency overhead? The smart proxyadds approximately 10-50ms of latency per request, depending on your geographic location and our nearest edge server. --- Ready to protect your agents? [Get started with the Smart Proxy →](https://dashboard.xpay.sh/smart-proxy/create) ================================================================================ # Page: /en/x402-protocol/facilitator # Source: src/content/en/x402-protocol/facilitator.mdx ================================================================================ # xpay Facilitator xpay operates a public x402 facilitator service at `https://facilitator.xpay.sh`. It handles USDC payment verification and settlement on Base, supporting both mainnet and testnet. ## What is a Facilitator? In the x402 protocol, a facilitator is a trusted intermediary that: 1. **Verifies** payment authorizations are valid and well-formed 2. **Settles** payments by submitting `transferWithAuthorization` (EIP-3009) transactions on-chain 3. **Reports** which networks and tokens it supports The facilitator never holds or custodies funds. Payments flow directly from buyer to seller via signed USDC authorization. ## Endpoints | Method | Path | Description | |--------|------|-------------| | `GET` | `/health` | Health check | | `GET` | `/supported` | List supported networks and tokens | | `POST` | `/verify` | Verify a payment authorization | | `POST` | `/settle` | Settle (execute) a payment on-chain | **Base URL:** `https://facilitator.xpay.sh` ### GET /health Returns the service status. ```bash curl https://facilitator.xpay.sh/health ``` ```json { "status": "ok" } ``` ### GET /supported Returns the networks and x402 protocol versions supported by this facilitator. ```bash curl https://facilitator.xpay.sh/supported ``` ```json { "supportedNetworks": [ { "networkId": "eip155:8453", "version": "v2" }, { "networkId": "eip155:84532", "version": "v2" }, { "networkId": "base", "version": "v1" }, { "networkId": "base-sepolia", "version": "v1" } ] } ``` ### POST /verify Verifies that a payment authorization is valid without executing it. Use this to confirm a buyer's payment before granting access to a resource. **Request body:** The x402 payment payload (as specified by the x402 protocol). ```bash curl -X POST https://facilitator.xpay.sh/verify \ -H "Content-Type: application/json" \ -d '{ "payment": "...", "paymentPayload": { ... } }' ``` **Response:** ```json { "valid": true } ``` Or on failure: ```json { "valid": false, "reason": "Payment authorization expired" } ``` ### POST /settle Settles a verified payment by submitting the `transferWithAuthorization` transaction on-chain. The USDC transfers directly from the buyer's wallet to the seller's wallet. **Request body:** The x402 payment payload. ```bash curl -X POST https://facilitator.xpay.sh/settle \ -H "Content-Type: application/json" \ -d '{ "payment": "...", "paymentPayload": { ... } }' ``` **Response:** ```json { "settled": true, "txHash": "0x..." } ``` ## Supported Networks | Network | Chain ID | x402 Version | Token | |---------|----------|-------------|-------| | Base Mainnet | `eip155:8453` | v2 | USDC | | Base Sepolia | `eip155:84532` | v2 | USDC | | Base Mainnet | `base` | v1 (legacy) | USDC | | Base Sepolia | `base-sepolia` | v1 (legacy) | USDC | ## Using the xpay Facilitator ### In a Paywall Server When building an x402-powered API, point your server to the xpay facilitator for payment verification and settlement: ```typescript import { wrapWithPaywall } from '@x402/express' const app = express() app.use( '/api/premium', wrapWithPaywall({ price: '$0.10', network: 'base', facilitatorUrl: 'https://facilitator.xpay.sh', receivingAddress: '0xYourWalletAddress', }) ) ``` ### In a Client When making requests to x402-protected resources, the facilitator URL is provided in the 402 response. Your client library handles the rest: ```typescript import { withX402 } from '@x402/fetch' const client = withX402(fetch, { walletPrivateKey: process.env.WALLET_KEY, }) // The client automatically pays via the facilitator specified in the 402 response const response = await client('https://api.example.com/premium-data') ``` ### Testing on Sepolia Use Base Sepolia for development and testing. The xpay facilitator supports Sepolia with no configuration changes - just use Sepolia USDC and a Sepolia wallet. ```typescript app.use( '/api/test', wrapWithPaywall({ price: '$0.01', network: 'base-sepolia', facilitatorUrl: 'https://facilitator.xpay.sh', receivingAddress: '0xYourTestWallet', }) ) ``` ## Comparison with Other Facilitators | Facilitator | Networks | Protocol Versions | Notes | |------------|----------|------------------|-------| | **xpay** | Base, Base Sepolia | v1, v2 | Free to use, optimized for Base | | Coinbase CDP | Base | v1 | Official Coinbase facilitator | | Base Facilitator | Base | v1 | `facilitator.base.org` | ## Rate Limits - **Verify**: 100 requests/minute - **Settle**: 50 requests/minute - **Health/Supported**: No limit --- Learn more about the [x402 Protocol](/x402-protocol) or explore the [Paywall Service](/products/paywall-service) to monetize your APIs. ================================================================================ # Page: /en/x402-protocol/index # Source: src/content/en/x402-protocol/index.mdx ================================================================================ # x402 Protocol Overview The x402 protocol revives the HTTP 402 "Payment Required" status code, enabling instant, automatic stablecoin payments directly over HTTP. It's the foundation that makes autonomous agent payments and API monetization possible. ## What is x402? x402 is an open payment protocol that extends HTTP to support native payments. When a client requests a protected resource, the server can respond with `402 Payment Required` along with payment instructions. The client can then submit payment and retry the request. ### Key Benefits - **💰 Micropayments**: Pay per API call, token, or second of usage - **⚡ Instant Settlement**: Payments settle in ~2 seconds on blockchain - **🤖 Agent-Native**: Designed for autonomous machine-to-machine payments - **🌐 Universal**: Works with any HTTP client or server - **🔗 Chain Agnostic**: Supports Ethereum, Base, Polygon, and more ## How It Works ```mermaid sequenceDiagram participant Client participant Server participant Facilitator participant Blockchain Client->>Server: GET /protected-resource Server->>Client: 402 Payment Required (with payment instructions) Client->>Facilitator: Submit payment Facilitator->>Blockchain: Process payment Blockchain->>Facilitator: Payment confirmed Client->>Server: GET /protected-resource (with payment proof) Server->>Facilitator: Verify payment Facilitator->>Server: Payment valid Server->>Client: 200 OK (protected resource) ``` ### Basic Flow Example 1. **Request**: Client requests a protected resource ```http GET /api/premium-data HTTP/1.1 Host: api.example.com ``` 2. **Payment Required**: Server responds with payment instructions ```http HTTP/1.1 402 Payment Required Content-Type: application/json { "type": "x402", "amount": "0.10", "currency": "USDC", "facilitator": "https://facilitator.xpay.sh", "recipient": "0x742d35Cc6635C0532925a3b8D" } ``` 3. **Payment**: Client submits payment to facilitator ```typescript const payment = await facilitator.pay({ amount: "0.10", currency: "USDC", recipient: "0x742d35Cc6635C0532925a3b8D" }) ``` 4. **Access**: Client retries request with payment proof ```http GET /api/premium-data HTTP/1.1 Host: api.example.com X-Payment-ID: payment_abc123 ``` ## Core Components ### Facilitators Facilitators handle the blockchain complexity so developers don't have to: - **Payment Processing**: Submit transactions to blockchain - **Verification**: Confirm payments without revealing private keys - **Settlement**: Transfer funds to recipients - **Standards**: Ensure interoperability between implementations Popular facilitators: - [xpay Facilitator](https://facilitator.xpay.sh) - Free, supports Base mainnet + Sepolia, v1 and v2 - [Coinbase Developer Platform](https://docs.cdp.coinbase.com/x402/) - [Base Facilitator](https://facilitator.base.org) ### Payment Instructions Servers include payment details in 402 responses: ```json { "type": "x402", "amount": "0.05", // Price in USD or token units "currency": "USDC", // Payment token "facilitator": "https://facilitator.xpay.sh", "recipient": "0x...", // Receiving wallet address "memo": "API access", // Optional payment description "expires": "2024-01-01T00:00:00Z" // Payment expiration } ``` ### Payment Verification Servers verify payments before granting access: ```typescript import { X402Facilitator } from '@x402/sdk' const facilitator = new X402Facilitator('https://facilitator.xpay.sh') async function verifyPayment(paymentId: string) { const payment = await facilitator.verify(paymentId) if (payment.status === 'completed' && payment.amount >= requiredAmount) { return true } return false } ``` ## Protocol Specifications ### Status Codes - **402 Payment Required**: Payment needed to access resource - **200 OK**: Payment verified, resource accessible - **400 Bad Request**: Invalid payment format - **409 Conflict**: Payment already processed - **410 Gone**: Payment expired ### Headers Standard headers for x402 payments: ```http # Request headers X-Payment-ID: payment_abc123 X-Payment-Token: eyJ0eXAiOiJKV1QiLCJhbGc... # Response headers X-Payment-Required: x402 X-Payment-Amount: 0.10 X-Payment-Currency: USDC X-Payment-Facilitator: https://facilitator.xpay.sh ``` ## Use Cases ### API Monetization Transform any API into a revenue stream: ```typescript app.get('/api/ai-completion', requirePayment(0.05), (req, res) => { // Only runs after $0.05 payment const completion = await openai.createCompletion(req.body) res.json(completion) }) ``` ### Agent Spending Controls Protect autonomous agents from overspending: ```typescript const agent = new Agent({ spendingLimits: { maxPerRequest: 1.00, maxDaily: 100.00 } }) // Agent automatically handles x402 payments within limits await agent.callAPI('https://expensive-ai-service.com/api') ``` ### Content Paywalls Monetize digital content per view: ```typescript // Pay $0.01 to read this article app.get('/article/:id', requirePayment(0.01), (req, res) => { const article = getArticle(req.params.id) res.json(article) }) ``` ### Machine-to-Machine Commerce Enable IoT devices to pay for services: ```typescript // Smart car pays for traffic data const trafficData = await iotDevice.x402Request('/traffic-api', { payment: { amount: 0.001, currency: 'USDC' } }) ``` ## Network Support x402 works on multiple blockchain networks: | Network | Currency | Settlement Time | Gas Costs | |---------|----------|----------------|-----------| | Base Mainnet | USDC | ~2 seconds | ~$0.001 | | Base Sepolia | USDC | ~2 seconds | Free | | Ethereum | USDC, ETH | ~12 seconds | ~$2-20 | | Polygon | USDC, MATIC | ~2 seconds | ~$0.01 | ## Getting Started Ready to integrate x402 payments? 1. **[Installation →](/getting-started/installation)** - Set up the x402 SDK 2. **[First Payment →](/getting-started/first-payment)** - Make your first x402 payment 3. **[Integration Patterns →](/x402-protocol/integration-patterns)** - Common implementation patterns ## Resources - **[Official Specification](https://x402.org)** - Complete protocol documentation - **[Coinbase x402 Docs](https://docs.cdp.coinbase.com/x402/)** - Coinbase's implementation guide - **[awesome-x402](https://github.com/xpaysh/awesome-x402)** - Community resources and tools - **[x402 Foundation](https://x402.org/foundation)** - Protocol governance and standards --- Continue reading: [x402 Fundamentals →](/x402-protocol/fundamentals)