← Back to home

Stableburn x402

AI agent available on the base app w/ XMTP, shares data, and x402 income is used to buy&burn token

Problem Statement

Stableburn: A helpful AI agent available on Base app (at agentprotocol.eth) with x402-powered USDC revenue going into the agent's treasury with buy&burn deflationary tokenomics.Built on a platform of CoinbaseDev tools, XMTP, x402, and the new Opensea MCP server (MSeaP).Core ComponentsMulti-Channel AI Agent System The heart of the project is an AI agent powered by GPT-5 that operates 24/7 across multiple communication channels:XMTP Protocol Integration: The agent maintains a persistent presence on the XMTP decentralized messaging network, enabling direct conversations with users and other agents on the Base app beta and xmtp.chat. It uses the Coinbase AgentKit for enhanced capabilities including on-chain transactions. HTTP API Service: A Hono-based web server provides RESTful endpoints for programmatic access, with built-in x402 micropayment requirements for premium features.OpenSea MCP Integration: Through the newly release MSeaP server beta, the agent has access to 17 specialized tools for NFT marketplace operations, including collection searches, floor price queries, trending data, swap quotes, and wallet balance checks.Micropayment Infrastructure (x402 Protocol)The project implements Coinbase's x402 payment protocol to monetize API access:Pay-per-request Model: Premium endpoints require micropayments (typically $0.001-$0.005 per request).Automatic Payment Processing: Smart contract-based receiver automatically processes incoming payments.Multi-token Support: Accepts USDC and PYUSD (soon) stablecoins on Base network.Zero-friction Integration: Clients can make payments programmatically without manual intervention$DATABURN Deflationary Token SystemA unique tokenomics model creates sustainable value accrual:Automatic Token Burning: All incoming revenue (from x402 payments, tips, and future NFT sales) is automatically converted to $DATABURN tokens and burnedTwo-step Swap Mechanism:USDC/PYUSD → ETH via Uniswap V3 (0.05% fee tier pool)ETH → $DATABURN via Flaunch contracts for Uni v4$DATABURN → Burn address (0x000...dead)Deflationary Pressure: Every API call and service usage permanently reduces token supplySmart Contract Architecture: DataBurnReceiverV3 contract handles all conversions autonomouslyDiscovery and Data ServicesThe agent serves as a value-add layer for blockchain data:Discovery Service: Aggregates and enhances x402 Facilitator resources with rich formatting (JSON, Markdown, visualizations)OpenSea Data Proxy: Re-serves OpenSea's NFT data through MCP protocol with added caching and formattingDynamic Service Registry: Maintains a real-time catalog of available services and their pricingMulti-format Responses: Automatically formats data based on client preferencesTechnical Architecture Frontend Application (apps/web)Next.js 14 with TypeScript for type safetyBase Account SDK integration for spend permissionsAI-powered chat interface for natural language interactionsWallet connection and authentication systemAgent Service (apps/agent-base-eth)Node.js/Bun runtime for high performanceXMTP SDK v4.0.3+ for decentralized messagingOpenAI GPT-4 for intelligent responsesHono framework for HTTP serverx402-hono middleware for payment processingSmart ContractsDataBurnReceiverV3.sol: Main payment receiver and token burnerImplements ReentrancyGuard, Pausable, and Ownable patternsIntegrates with Uniswap V3 SwapRouter02Connects to Flaunch pairs for final token swapEmits events for transparency and trackingShared InfrastructureTurborepo for monorepo managementShared TypeScript types and utilitiesReusable MCP tools and x402 client librariesCentralized configuration managementUse CasesNFT Market Intelligence: Traders and collectors access real-time NFT data through natural language queriesAgent-to-Agent Commerce: AI agents pay each other for services using x402 micropaymentsAutomated Trading: Bots consume API endpoints for algorithmic NFT trading strategiesData Aggregation: Developers build applications on top of the enriched data servicesToken Value Accrual: $DATABURN holders benefit from continuous supply reduction

Solution

Core Technology StackRuntime & Framework DecisionsBun + Node.js Hybrid Approach: We chose Bun as our primary runtime for its blazing-fast startup times and native TypeScript support, crucial for an always-on agent. However, we discovered certain XMTP SDK components required Node.js compatibility, leading to a hybrid approach where Bun handles the build process and package management while maintaining Node.js compatibility for execution.Hono over Express: Initially built with Express, we migrated to Hono for its lightweight footprint (5KB vs Express's 500KB+) and native Web Standards API support. This was particularly important for edge deployment compatibility and reduced cold start times. The migration required rewriting middleware but resulted in 3x faster request handling.TypeScript Everywhere: Full type safety across the monorepo with shared type definitions in packages/shared-types. This caught numerous potential runtime errors during development, especially around the complex MCP tool interfaces.Blockchain Integration ArchitectureSmart Contract Design Evolution.Deployed Contract: https://basescan.org/address/0x76a6ed9dece032d227b713010022c5e43a307d8aV1 → V3 Contract Rewrite: Our initial DataBurnReceiver contract used BaseSwap's router, but we discovered liquidity limitations. The V3 rewrite implements a two-step swap:// Routing through multiple DEXsl to go from USDC to Eth (deep Uni v3 pool) to DATABURN (v4):function _swapAndBurn(address tokenIn, uint256 amountIn) private { // Step 1: Leverage Uniswap V3's concentrated liquidity uint256 ethReceived = _swapToETH(tokenIn, amountIn);// Step 2: Use Flaunch's meme token pools uint256 databurnReceived = _swapETHToToken(ethReceived); // Step 3: Permanent burn _burn(databurnReceived);}Uniswap V3 Integration Challenges:Implemented custom quoter integration for slippage protectionDiscovered we needed to handle both exactInputSingle and multi-hop swapsBuilt fallback mechanisms for failed swapsAdded minimum output calculations to prevent sandwich attacksFlaunch Protocol Integration: We added Flaunch contracts as a git submodule and directly integrated with their pair contracts. This required reverse-engineering their swap interface since documentation was limited: // Had to decode Flaunch's swap mechanism const swapData = encodeFunctionData({ abi: FLAUNCH_PAIR_ABI, functionName: 'swap', args: [0, expectedTokenOut, receiverAddress, '0x'] })XMTP Integration Deep DiveDatabase Encryption Architecture: XMTP requires persistent storage for message history. We implemented SQLCipher encryption with a deterministic key derivation:// Generate encryption key from wallet private key const encryptionKey = createHash('sha256') .update(privateKey) .digest('hex') .slice(0, 64)Signer Creation Complexity: The XMTP SDK v4 migration broke our initial implementation. We had to create a custom signer wrapper:// Complex signer initialization for XMTP v4 const signer = { getAddress: async () => wallet.address, signMessage: async (message: string | Uint8Array) => { const signature = await wallet.signMessage(message) return hexToBytes(signature) } }Message Streaming Architecture: Built a robust message handler that prevents infinite loops: // Critical loop prevention if (message.senderInboxId === client.inboxId) returnOpenSea MCP Integration via AI SDKExperimental Features Usage: We're using Vercel AI SDK's experimental MCP client, which required extensive workarounds:// Had to patch the MCP client for SSE transport const client = await experimental_createMCPClient({ transport: { type: 'sse', url: 'https://mcp-server-opensea-production.vercel.app/sse', // Custom headers for beta access headers: { 'Authorization':Bearer ${OPENSEA_ACCESS_TOKEN}, 'anthropic-dangerous-direct-browser-access': 'true' } } })Tool Registration System: Dynamically registered 17 OpenSea tools with the AI SDK: // Dynamic tool mapping for (const tool of tools) { registry.register(tool.name, { description: tool.description, parameters: tool.inputSchema, execute: async (args) => { return await client.callTool(tool.name, args) } })Hacky Solutions & WorkaroundsGlobal Wallet Persistence// Hack to persist CDP wallet across hot reloads declare global { var __cdpWallet: any } global.__cdpWallet = walletSSE Endpoint ProxyingThe OpenSea MCP server only provides SSE transport, but we needed JSON-RPC. Built a custom proxy: // Convert SSE stream to JSON-RPC const sseToJsonRpc = (stream: ReadableStream) => { return new Response(stream).json() }Foundry Version CompatibilityFoundry's latest version used "prague" EVM version which caused compilation errors. Had to downgrade: evm_version = "paris" # prague breaks OpenZeppelinPartner Technology BenefitsCoinbase Developer Platform (CDP):Gas sponsorship eliminated user frictionSmart account abstraction simplified wallet managementBuilt-in paymaster saves ~$50/day in gas costsOpenSea's MCP Server:17 pre-built tools saved weeks of API integrationBeta access provided rate limit exemptionsSSE transport enabled real-time data streamingVercel AI SDK:Experimental MCP client provided tool orchestrationBuilt-in GPT-5 streaming reduced response latencyTool calling abstraction simplified complex flowsBase Network:2-second block times enable near-instant paymentsLow fees (~$0.001) make micropayments viable, even though x402 fees are currently waived.Performance OptimizationsCaching Layer: Implemented 15-minute cache for OpenSea data to reduce API callsConnection Pooling: Reused XMTP client connections across messagesLazy Loading: Deferred MCP tool initialization until first useDatabase Indexing: Added indexes on conversation IDs for faster message retrievalSecurity MeasuresReentrancyGuard: Protected all swap functions against reentrancy attacksSlippage Protection: Implemented 2% max slippage on all swapsAccess Control: Used OpenZeppelin's Ownable for admin functionsInput Validation: Sanitized all user inputs before AI processingKey Rotation: Supported hot-swapping API keys without downtime

Hackathon

ETHGlobal New York 2025

2025

Contributors