The best way to monetize AI applications & MCP, using x402, MCP & CDP Smart Wallets. Users pay 0.01 USDC per MCP query, showcasing how to monetize AI services with seamless Web3 payments.
This application demonstrates a pay-per-use AI system where:
- Users connect their wallet (Smart Wallet with passkeys or non-custodial wallets)
- Ask AI questions through a chat interface
- Pay 0.01 USDC per query automatically via x402
- Receive AI-powered responses after successful payment
- Interact with dynamic UI components generated by AI
Perfect for developers wanting to build monetized AI applications with Web3 payments (x402).
- π Dual Wallet Support: Smart Wallets with Passkeys (CDP) or non-custodial wallets
- π³ x402 Payment Gates: HTTP 402 Payment Required implementation for API access
- π Passkey Authentication: Biometric login with Smart Wallets (most secure, no seed phrases)
- β½ Gas Sponsorship: Transaction fee sponsorship via paymaster for Smart Wallets
- π€ Tambo AI Integration: Generative UI with React component registry
- π MCP Protocol Support: Model Context Protocol for extensible AI functionality
- π Base Network: Supports both Base testnet (default) and Base mainnet
- π‘οΈ Production Ready: Clean architecture with proper error handling
- π¨ Dynamic UI: AI can generate and render React components on demand
- Node.js 18+ and npm
- A Tambo AI API key (free tier available)
- A wallet address to receive payments
-
Clone and install:
git clone https://github.com/aaronjmars/tweazy cd tweazy npm install
-
Configure environment:
# Copy the example environment file cp example.env.local .env.local
-
Add your API keys to
.env.local
:# Required: Get from https://tambo.co/dashboard NEXT_PUBLIC_TAMBO_API_KEY=your-tambo-api-key # Required: Your wallet address to receive payments NEXT_PUBLIC_PAYMENT_RECIPIENT=0x0000CE08fa224696A819877070BF378e8B131ACF # Optional: Network mode (defaults to Base testnet for safety) NEXT_PUBLIC_NETWORK_MODE=testnet # or 'mainnet' for production # Optional: CDP Wallet credentials (for enhanced wallet features) CDP_API_KEY_NAME=your-cdp-key-name CDP_API_KEY_PRIVATE_KEY=your-cdp-private-key CDP_PROJECT_ID=your-cdp-project-id CDP_WALLET_SECRET=your-cdp-wallet-secret CDP_PAYMASTER_SERVICE=your-paymaster-service-url
-
Start the development server:
npm run dev
-
Open your browser to http://localhost:3000
- Connect a wallet (Smart Wallet with passkeys recommended for gas-free transactions)
- Ask a question in the chat interface
- Confirm the 0.01 USDC payment when prompted (gas fees may be sponsored)
- See your AI response after successful payment!
This app uses a security-first configuration approach:
- Secrets (API keys, wallet addresses) β Environment variables
- Non-secrets (RPC URLs, contract addresses, gas settings) β
src/lib/config.ts
NEXT_PUBLIC_TAMBO_API_KEY
: Your Tambo AI API key (Get one here)NEXT_PUBLIC_PAYMENT_RECIPIENT
: Wallet address that will receive the 0.01 USDC payments
NEXT_PUBLIC_NETWORK_MODE
:testnet
(default) ormainnet
- CDP credentials for enhanced wallet features (see
example.env.local
)
The app automatically switches between Base networks based on NEXT_PUBLIC_NETWORK_MODE
:
- Network: Base Sepolia (Chain ID: 84532)
- USDC Contract:
0x036CbD53842c5426634e7929541eC2318f3dCF7e
- RPC URL:
https://sepolia.base.org
- Features: Free testnet tokens, no real money at risk
- Network: Base Mainnet (Chain ID: 8453)
- USDC Contract:
0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
- RPC URL:
https://mainnet.base.org
- Features: Real USDC transactions, production-ready
Change one environment variable to switch networks:
# For development (safe, uses testnet)
NEXT_PUBLIC_NETWORK_MODE=testnet
# For production (real money!)
NEXT_PUBLIC_NETWORK_MODE=mainnet
All network-specific settings (RPC URLs, contract addresses, chain IDs) update automatically.
Smart Wallets benefit from transaction fee sponsorship via paymaster integration:
- Smart Wallet Selection: When users choose Smart Wallet with passkeys
- Automatic Detection: System detects Smart Wallet capability for gas sponsorship
- Paymaster Integration: Gas fees for USDC payments are sponsored via CDP paymaster
- User Experience: Users only pay the 0.01 USDC for AI queries, no gas fees required
- Fallback: If paymaster fails, transaction proceeds with user-paid gas
- π Gas-free transactions for Smart Wallet users
- π Automatic handling - no user configuration needed
- π‘οΈ Reliable fallback - always works even if sponsorship unavailable
- π° Cost effective - users only pay for AI queries, not network fees
- Paymaster URL: Configured via
CDP_PAYMASTER_SERVICE
environment variable - Sponsorship Logic: Implemented in
src/lib/payment.ts
- User Operations: ERC-4337 compatible Smart Account transactions
- Base Network: Works on both Base Sepolia (testnet) and Base Mainnet
- π Connect Wallet: Choose from Smart Wallet (passkeys) or non-custodial wallet
- π¬ Ask Questions: Type your question in the chat interface
- π³ Payment Prompt: App shows payment modal for 0.01 USDC
- β Confirm Payment: Approve the blockchain transaction (gas fees sponsored for Smart Wallets)
- π€ AI Response: Receive AI-generated answer with dynamic UI components
- π Repeat: Ask more questions, each requiring a new payment
graph TD
A[User asks question] --> B[AI service returns x402]
B --> C[Payment modal appears]
C --> D[User approves 0.01 USDC payment]
D --> E[Transaction confirmed on blockchain]
E --> F[Request retried with payment proof]
F --> G[AI response delivered]
Best for: New users, gas-free transactions, maximum security
- β No setup required - Wallet created automatically via CDP
- β Biometric authentication - Use fingerprint, Face ID, or device passkeys
- β Most secure - No seed phrases or private keys to manage
- β Gas sponsorship - Transaction fees sponsored via paymaster
- β Instant setup - Ready in seconds
- β Auto-configured - Works on Base Sepolia/Mainnet out of the box
Best for: Existing wallet users (MetaMask, Rabby, Coinbase Wallet, etc.)
- π§ Any injected Web3 wallet (MetaMask, Rabby, Coinbase Wallet, etc.)
- π Auto-switches to Base Sepolia network (Chain ID: 84532)
- π§ Get testnet ETH from Base Sepolia Faucet for gas fees
- πͺ Get testnet USDC: Contract
0x036CbD53842c5426634e7929541eC2318f3dCF7e
src/
βββ app/ # Next.js App Router
β βββ api/ # API routes for CDP wallet operations
β βββ mcp-config/ # MCP server configuration page
β βββ page.tsx # Main application page
βββ components/ # React components
β βββ ui/ # Reusable UI components
β βββ WalletProvider.tsx # Multi-wallet context
β βββ PaymentModal.tsx # Payment confirmation UI
β βββ EnhancedMessageInput.tsx # Chat input with payment
βββ lib/ # Core business logic
β βββ config.ts # Configuration management
β βββ payment.ts # Universal payment handling
β βββ smart-wallet.ts # Smart wallet integration
β βββ cdp-wallet.ts # Coinbase CDP integration
β βββ x402.ts # HTTP 402 handling
β βββ tambo.ts # AI component registry
βββ styles/ # Global styles and Tailwind
- Universal payment handling for both wallet types
- x402 integration for payment-gated API calls
- Paymaster integration for gas sponsorship on Smart Wallets
- Transaction validation and error handling
- USDC transfers on Base network
- Smart Wallet (
src/lib/smart-wallet.ts
): CDP-based passkey authentication with gas sponsorship - non-custodial wallet (via wagmi): Support for all injected Web3 wallets
- Wallet Provider (
src/components/WalletProvider.tsx
): Dual-wallet context management
- Tambo AI: React component registry for AI-driven UI
- MCP Protocol: Model Context Protocol for extensible AI
- Dynamic Components: AI generates and renders React components
- Payment Gates: x402 responses trigger payment flows
POST /api/cdp/create-wallet
- Create new Smart Wallet via CDPPOST /api/cdp/balance
- Check USDC balancePOST /api/cdp/transfer
- Execute USDC payments with optional gas sponsorshipPOST /api/cdp/fund-wallet
- Fund wallet with testnet tokensPOST /api/paymaster
- Handle paymaster gas sponsorship for Smart Wallets
- Network switching: Automatic testnet/mainnet configuration
- Contract addresses: Network-specific USDC contracts
- RPC endpoints: Reliable Base network connections
- Gas settings: Optimized transaction parameters
# Development
npm run dev # Start development server at localhost:3000
npm run build # Build production application
npm run start # Start production server
npm run lint # Run ESLint for code linting
### Development Workflow
1. **Fork the repository** and clone your fork
2. **Create a feature branch**: `git checkout -b feature/your-feature`
3. **Install dependencies**: `npm install`
4. **Set up environment**: Copy `example.env.local` to `.env.local`
5. **Start development**: `npm run dev`
6. **Make your changes** and test thoroughly
7. **Run linting**: `npm run lint`
8. **Build to verify**: `npm run build`
9. **Commit and push**: Follow conventional commit format
10. **Create a pull request** with detailed description
### Code Style
- **TypeScript**: Strict mode enabled
- **ESLint**: Configured for Next.js and React
- **Prettier**: Code formatting (run with `npm run format`)
- **Conventional Commits**: Use conventional commit format
### Test Scenarios
#### Core Payment Flow
1. **Smart Wallet (Recommended)**:
- Create passkey β Ask question β Confirm payment (gas-free) β See AI response
2. **non-custodial wallet**:
- Connect wallet β Switch to Base Sepolia β Ask question β Pay (with gas fees) β See response
### Getting Testnet Tokens
#### For Smart Wallet Users
- **No setup required** - Smart Wallets with gas sponsorship don't need ETH for gas fees
- **USDC only** - Get testnet USDC for payments (contract: `0x036CbD53842c5426634e7929541eC2318f3dCF7e`)
#### For non-custodial wallet Users
- **Base Sepolia ETH (for gas fees)**:
- [Alchemy Base Sepolia Faucet](https://www.alchemy.com/faucets/base-sepolia)
- [Coinbase Faucet](https://www.coinbase.com/faucets/base-sepolia-faucet)
- **Base Sepolia USDC (for payments)**:
- Contract: `0x036CbD53842c5426634e7929541eC2318f3dCF7e`
- Use a testnet USDC faucet or bridge testnet ETH to USDC
## π§ Technical Details
### Wallet Architecture
#### Smart Wallet (CDP with Passkeys)
- **SDK**: Coinbase CDP SDK with Smart Wallet integration
- **Authentication**: WebAuthn passkeys (biometric authentication)
- **Security**: No private keys or seed phrases, device-based authentication
- **Gas Sponsorship**: ERC-4337 paymaster integration for transaction fee sponsorship
- **Network**: Base Sepolia/Mainnet with automatic configuration
#### non-custodial wallet Integration
- **Library**: wagmi + viem for Web3 wallet connections
- **Supported Wallets**: MetaMask, Rabby, Coinbase Wallet, and all injected wallets
- **Network**: Base Sepolia/Mainnet with manual gas fee payment
- **Features**: Standard Web3 wallet connection with user-controlled private keys
### x402 Payment Protocol
```mermaid
sequenceDiagram
participant User
participant App
participant AI
participant Blockchain
User->>App: Ask question
App->>AI: Send query
AI-->>App: 402 Payment Required
App->>User: Show payment modal
User->>Blockchain: Send 0.01 USDC
Blockchain-->>App: Transaction confirmed
App->>AI: Retry with payment proof
AI-->>App: Return AI response
App->>User: Display answer
Testnet (Base Sepolia):
- Address:
0x036CbD53842c5426634e7929541eC2318f3dCF7e
- Chain ID: 84532
- Decimals: 6
Mainnet (Base):
- Address:
0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
- Chain ID: 8453
- Decimals: 6
The app automatically switches contracts and RPC endpoints based on NEXT_PUBLIC_NETWORK_MODE
.
- Testnet mode: All payments use test tokens (no real value)
- Mainnet mode: Real USDC transactions - use with caution
- Always verify
NEXT_PUBLIC_NETWORK_MODE
before deployment
- Smart Wallets: Most secure - use passkeys, no private keys, gas sponsorship included
- non-custodial wallets: User-controlled private keys, manual gas fee management
- Payment validation: All transactions verified on-chain
- Gas sponsorship: Smart Wallets benefit from paymaster-sponsored transactions
We welcome contributions! Here's how to get started:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature
- Make your changes
- Test thoroughly (run
npm run build
andnpm run lint
) - Commit using conventional commits:
feat: add amazing feature
- Push to your fork:
git push origin feature/amazing-feature
- Create a Pull Request with detailed description
- π Bug fixes and improvements
- β¨ New AI components for the registry
- π§ Wallet integrations (new wallet types)
- π Documentation improvements
- π§ͺ Test coverage enhancements
- π¨ UI/UX improvements
- TypeScript: Use strict typing
- Testing: Add tests for new features
- Documentation: Update README for new features
- Code style: Follow existing patterns
- Commits: Use conventional commit format
- Tambo AI: Generative UI framework with MCP support
- Tambo GitHub: Component registry and MCP integration
- Next.js: React framework for production
- Tailwind CSS: Utility-first CSS framework
- Coinbase CDP: Coinbase Developer Platform
- Base Network: Ethereum L2 network
- wagmi: React hooks for Ethereum
- viem: TypeScript interface for Ethereum
- x402 Standard: HTTP 402 Payment Required
- MCP Protocol: Model Context Protocol
- WebAuthn: Web Authentication API (for passkeys)
- Set
NEXT_PUBLIC_PAYMENT_RECIPIENT
in.env.local
- Use a valid Ethereum address
- Get API key from tambo.co/dashboard
- Set
NEXT_PUBLIC_TAMBO_API_KEY
in.env.local
- Get testnet tokens from Base Sepolia faucets
- Ensure you have both ETH (gas) and USDC (payments)
- Check MetaMask is connected to Base Sepolia (Chain ID: 84532)
- Verify
NEXT_PUBLIC_NETWORK_MODE
setting
- π Check the docs above for detailed information
- π Open an issue for bugs or feature requests
- π¬ Start a discussion for questions or ideas
- π Check console logs for detailed error information
Enable debug logging by adding to .env.local
:
NEXT_PUBLIC_DEBUG=true
This project demonstrates the future of monetized AI applications with seamless Web3 payments. Fork it, customize it, and build the next generation of payment-gated AI services!
Happy coding! π