Skip to content

aaronjmars/tweazy

Repository files navigation

Tweazy - The best way to read tweets onchain / Powered by x402, MCP & CDP Smart Wallets

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.

πŸš€ What This App Does

This application demonstrates a pay-per-use AI system where:

  1. Users connect their wallet (Smart Wallet with passkeys or non-custodial wallets)
  2. Ask AI questions through a chat interface
  3. Pay 0.01 USDC per query automatically via x402
  4. Receive AI-powered responses after successful payment
  5. Interact with dynamic UI components generated by AI

Perfect for developers wanting to build monetized AI applications with Web3 payments (x402).

✨ Key Features

  • πŸ” 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

πŸš€ Quick Start

Prerequisites

  • Node.js 18+ and npm
  • A Tambo AI API key (free tier available)
  • A wallet address to receive payments

Setup

  1. Clone and install:

    git clone https://github.com/aaronjmars/tweazy
    cd tweazy
    npm install
  2. Configure environment:

    # Copy the example environment file
    cp example.env.local .env.local
  3. 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
  4. Start the development server:

    npm run dev
  5. Open your browser to http://localhost:3000

First Steps

  1. Connect a wallet (Smart Wallet with passkeys recommended for gas-free transactions)
  2. Ask a question in the chat interface
  3. Confirm the 0.01 USDC payment when prompted (gas fees may be sponsored)
  4. See your AI response after successful payment!

βš™οΈ Configuration

Environment Variables

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

Required Environment Variables

  • 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

Optional Environment Variables

  • NEXT_PUBLIC_NETWORK_MODE: testnet (default) or mainnet
  • CDP credentials for enhanced wallet features (see example.env.local)

Network Configuration

The app automatically switches between Base networks based on NEXT_PUBLIC_NETWORK_MODE:

Testnet Mode (Default - Safe for Development)

  • Network: Base Sepolia (Chain ID: 84532)
  • USDC Contract: 0x036CbD53842c5426634e7929541eC2318f3dCF7e
  • RPC URL: https://sepolia.base.org
  • Features: Free testnet tokens, no real money at risk

Mainnet Mode (Production)

  • Network: Base Mainnet (Chain ID: 8453)
  • USDC Contract: 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
  • RPC URL: https://mainnet.base.org
  • Features: Real USDC transactions, production-ready

Easy Network Switching

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.

β›½ Gas Sponsorship (Paymaster)

Smart Wallets benefit from transaction fee sponsorship via paymaster integration:

How Gas Sponsorship Works

  1. Smart Wallet Selection: When users choose Smart Wallet with passkeys
  2. Automatic Detection: System detects Smart Wallet capability for gas sponsorship
  3. Paymaster Integration: Gas fees for USDC payments are sponsored via CDP paymaster
  4. User Experience: Users only pay the 0.01 USDC for AI queries, no gas fees required
  5. Fallback: If paymaster fails, transaction proceeds with user-paid gas

Benefits

  • πŸ†“ 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

Technical Implementation

  • 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

πŸ”„ How It Works

User Flow

  1. πŸ”— Connect Wallet: Choose from Smart Wallet (passkeys) or non-custodial wallet
  2. πŸ’¬ Ask Questions: Type your question in the chat interface
  3. πŸ’³ Payment Prompt: App shows payment modal for 0.01 USDC
  4. βœ… Confirm Payment: Approve the blockchain transaction (gas fees sponsored for Smart Wallets)
  5. πŸ€– AI Response: Receive AI-generated answer with dynamic UI components
  6. πŸ”„ Repeat: Ask more questions, each requiring a new payment

Payment Flow (x402 Implementation)

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]
Loading

πŸ’Ό Wallet Options

πŸ”’ Smart Wallet with Passkeys (Recommended)

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

πŸ”— non-custodial wallet

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

πŸ—οΈ Architecture

Project Structure

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

Core Systems

πŸ’³ Payment System (src/lib/payment.ts)

  • 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

πŸ” Wallet Management

  • 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

πŸ€– AI Integration

  • 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

API Routes

Smart Wallet (CDP) Operations

  • POST /api/cdp/create-wallet - Create new Smart Wallet via CDP
  • POST /api/cdp/balance - Check USDC balance
  • POST /api/cdp/transfer - Execute USDC payments with optional gas sponsorship
  • POST /api/cdp/fund-wallet - Fund wallet with testnet tokens
  • POST /api/paymaster - Handle paymaster gas sponsorship for Smart Wallets

Configuration System

Environment-Based Config (src/lib/config.ts)

  • Network switching: Automatic testnet/mainnet configuration
  • Contract addresses: Network-specific USDC contracts
  • RPC endpoints: Reliable Base network connections
  • Gas settings: Optimized transaction parameters

πŸ› οΈ Development

Commands

# 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

Smart Contracts

USDC Contracts

Testnet (Base Sepolia):

  • Address: 0x036CbD53842c5426634e7929541eC2318f3dCF7e
  • Chain ID: 84532
  • Decimals: 6

Mainnet (Base):

  • Address: 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
  • Chain ID: 8453
  • Decimals: 6

Network Configuration

The app automatically switches contracts and RPC endpoints based on NEXT_PUBLIC_NETWORK_MODE.

πŸ”’ Security Considerations

Network Safety

⚠️ Defaults to testnet for safety - no real money at risk

  • 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

Wallet Security

  • 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

🀝 Contributing

We welcome contributions! Here's how to get started:

Quick Contribution Guide

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes
  4. Test thoroughly (run npm run build and npm run lint)
  5. Commit using conventional commits: feat: add amazing feature
  6. Push to your fork: git push origin feature/amazing-feature
  7. Create a Pull Request with detailed description

What We're Looking For

  • πŸ› Bug fixes and improvements
  • ✨ New AI components for the registry
  • πŸ”§ Wallet integrations (new wallet types)
  • πŸ“š Documentation improvements
  • πŸ§ͺ Test coverage enhancements
  • 🎨 UI/UX improvements

Development Guidelines

  • 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

πŸ“š Resources & Documentation

Core Technologies

Web3 & Blockchain

Protocols & Standards

πŸ†˜ Support & Troubleshooting

Common Issues

"Payment recipient not configured"

  • Set NEXT_PUBLIC_PAYMENT_RECIPIENT in .env.local
  • Use a valid Ethereum address

"Tambo API key not found"

"Insufficient balance"

  • Get testnet tokens from Base Sepolia faucets
  • Ensure you have both ETH (gas) and USDC (payments)

"Network not supported"

  • Check MetaMask is connected to Base Sepolia (Chain ID: 84532)
  • Verify NEXT_PUBLIC_NETWORK_MODE setting

Getting Help

  • πŸ“– 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

Debug Mode

Enable debug logging by adding to .env.local:

NEXT_PUBLIC_DEBUG=true

πŸš€ Ready to Build?

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! πŸŽ‰

About

The best way to monetize AI applications & MCP, using x402, CDP Smart Wallets & Paymaster

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published