Skip to content

HeimLabs/anyspend-x402-image-agent-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

17 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

AI Image Generator with x402 (Solana)

Node.js React TypeScript Tailwind CSS Vite Express Solana

A professional AI image generation demo with crypto payments on Solana using the x402 HTTP payment protocol.

🎨 What It Does

Generate stunning AI images for just 0.15 USDC per image - pay with USDC on Solana!

  • πŸ€– AI-Powered: Google Gemini 2.5 Flash Image for high-quality generation
  • πŸ’° Crypto Payments: Accept USDC on Solana via x402 protocol
  • ⚑ Fast Settlement: Solana's 400ms transaction finality
  • πŸ”— Single-Chain: Focused on Solana for simplicity
  • 🎯 Client-Server: Traditional architecture (no A2A complexity)
  • πŸ“Š Helius Integration: Fast SPL token balance fetching via DAS API

πŸ—οΈ Architecture

graph TB
    subgraph Client["React Client (Port 5173)"]
        UI[React UI]
        Wallet[Solana Wallet Adapter]
        X402Client[x402 Payment Client]
    end

    subgraph Server["Express Server (Port 4024)"]
        API[Express API]
        X402Middleware[x402 Payment Middleware]
        Gemini[Gemini 2.5 Flash Image]
    end

    subgraph External["External Services"]
        SolanaNet[Solana Mainnet]
        Facilitator[AnySpend Facilitator]
        HeliusRPC[Helius RPC/DAS]
    end

    UI --> Wallet
    Wallet --> X402Client
    X402Client -->|HTTP + Payment| X402Middleware
    X402Middleware --> API
    API --> Gemini

    X402Client <-->|Payment Verification| Facilitator
    X402Middleware <-->|Payment Settlement| Facilitator
    Facilitator <-->|USDC Transfer| SolanaNet
    Wallet <-->|Token Balances| HeliusRPC

    style Client fill:#3B82F6,stroke:#1E40AF,color:#fff
    style Server fill:#10B981,stroke:#047857,color:#fff
    style External fill:#8B5CF6,stroke:#6D28D9,color:#fff
Loading

Payment Flow

sequenceDiagram
    participant User
    participant Client
    participant Wallet
    participant Server
    participant Facilitator
    participant Solana

    User->>Client: Enter prompt & click Generate
    Client->>Wallet: Request wallet connection
    Wallet-->>Client: Connected (public key)

    Client->>Server: GET /api/generate (no payment)
    Server-->>Client: 402 Payment Required (0.15 USDC)

    Client->>Wallet: Sign USDC payment (0.15)
    Wallet-->>Client: Signed transaction

    Client->>Server: POST /api/generate + Payment Header
    Server->>Facilitator: Verify payment signature
    Facilitator-->>Server: Payment verified βœ“

    Server->>Solana: Submit USDC transfer
    Solana-->>Server: Transaction confirmed

    Server->>Server: Generate AI image (Gemini)
    Server-->>Client: Image data + tx hash

    Client->>User: Display image + Solscan link
Loading

πŸš€ Quick Start

1. Install Dependencies

pnpm install

2. Configure Environment Variables

Server (apps/server/.env):

# Gemini API Configuration
GEMINI_API_KEY=your_gemini_api_key_here

# x402 Payment Configuration
# IMPORTANT: Must be a Solana wallet address (base58 format)
RECEIVER_ADDRESS=your_solana_wallet_address_here
FACILITATOR_URL=https://mainnet.anyspend.com/x402

# Server Configuration
PORT=4024
NODE_ENV=development

Client (apps/client/.env):

# Helius API Configuration
VITE_HELIUS_API_KEY=your_helius_api_key_here

# Solana Network (mainnet or devnet)
VITE_SOLANA_NETWORK=mainnet

# API URL (optional - defaults to local server)
VITE_API_URL=http://localhost:4024

3. Start Development

# Start both server and client
pnpm dev

# Or start individually:
pnpm dev:server  # Server on port 4024
pnpm dev:client  # Client on port 5173

4. Test the App

  1. Open http://localhost:5173
  2. Connect your Solana wallet (Phantom, Solflare, or Backpack)
  3. Ensure wallet has at least 0.15 USDC on Solana mainnet
  4. Enter the test prompt below and click "Generate Image"
  5. Confirm the USDC payment in the modal
  6. Watch your AI image get generated!

πŸ“‹ Prerequisites

  • Node.js Node.js 18+ and pnpm
  • Google Google Gemini API key (Get one)
  • Helius Helius API key (Get one)
  • Wallet Solana wallet with USDC (Phantom, Solflare, or Backpack)

🎯 Features

For Users

  • 🎨 Generate AI images with natural language prompts
  • πŸ“ Multiple aspect ratios (1:1, 16:9, 9:16, 4:3, 3:4)
  • πŸ’³ Simple USDC payments on Solana (0.15 USDC per image)
  • πŸ“₯ Download generated images instantly
  • ⚑ Fast Solana transaction finality (~400ms)
  • πŸ” Transaction tracking with Solscan links

For Developers

  • πŸ”Œ Clean x402 integration example for Solana
  • πŸ’° Single-token (USDC) payment handling
  • πŸ“¦ Complete TypeScript codebase
  • πŸ—οΈ Simple client-server architecture
  • πŸš€ Helius RPC & DAS API integration
  • 🎯 Production-ready payment flow
  • πŸ“ Comprehensive documentation

πŸ’‘ Use Cases

This demo showcases patterns for:

  • Paid API Services: Monetize any HTTP API with crypto payments
  • Solana Payments: Accept USDC payments on Solana
  • AI Service Monetization: Charge for AI model inference
  • x402 Protocol: HTTP payment protocol integration
  • Micro-transactions: Enable sub-dollar payments efficiently

πŸ› οΈ Technology Stack

Frontend

React TypeScript Tailwind Vite

Libraries:

  • @solana/wallet-adapter-react - Phantom, Solflare, Backpack support
  • @solana/web3.js - Solana blockchain interaction
  • @b3dotfun/anyspend-x402-fetch - x402 payment client
  • @tanstack/react-query - Data fetching and caching

Backend

Node.js Express TypeScript

Libraries:

  • @b3dotfun/anyspend-x402-express - x402 payment middleware
  • @google/genai - Gemini 2.5 Flash Image API
  • express - HTTP server with 32KB header size for Solana

Blockchain

Solana USDC

  • Network: Solana Mainnet
  • Token: USDC SPL Token (EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v)
  • RPC: Helius RPC for fast transaction processing
  • Explorer: Solscan for transaction tracking

Infrastructure

  • Payment Protocol: x402 - HTTP-based crypto payments
  • AI Engine: Google Gemini 2.5 Flash Image
  • RPC Provider: Helius - Fast Solana RPC & DAS API

πŸ“ Project Structure

ai-image-generator-x402/
β”œβ”€β”€ apps/
β”‚   β”œβ”€β”€ server/                # Express server (Port 4024)
β”‚   β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”‚   β”‚   └── gemini.ts  # Gemini AI integration
β”‚   β”‚   β”‚   β”œβ”€β”€ middleware/
β”‚   β”‚   β”‚   β”‚   └── x402.ts    # x402 payment middleware
β”‚   β”‚   β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”‚   β”‚   └── generate.ts # Image generation endpoint
β”‚   β”‚   β”‚   └── server.ts      # Main server setup
β”‚   β”‚   └── .env.example
β”‚   β”‚
β”‚   └── client/                # React web UI (Port 5173)
β”‚       β”œβ”€β”€ src/
β”‚       β”‚   β”œβ”€β”€ components/
β”‚       β”‚   β”‚   β”œβ”€β”€ Header.tsx
β”‚       β”‚   β”‚   β”œβ”€β”€ Footer.tsx
β”‚       β”‚   β”‚   └── PaymentModal.tsx  # USDC payment modal
β”‚       β”‚   β”œβ”€β”€ pages/
β”‚       β”‚   β”‚   └── ImageGenerator.tsx # Main page
β”‚       β”‚   β”œβ”€β”€ lib/
β”‚       β”‚   β”‚   β”œβ”€β”€ createSolanaSigner.ts # Wallet adapter bridge
β”‚       β”‚   β”‚   β”œβ”€β”€ heliusClient.ts       # Helius DAS API
β”‚       β”‚   β”‚   β”œβ”€β”€ balanceCache.ts       # Balance caching
β”‚       β”‚   β”‚   └── formatAmount.ts       # Token formatting
β”‚       β”‚   └── config/
β”‚       β”‚       └── solana.ts             # Wallet adapter config
β”‚       └── .env.example
β”‚
└── README.md                  # This file

πŸ” Security Notes

  • Receiver Address: Use a separate Solana wallet for receiving payments
  • Git: Private keys are in .gitignore, never commit them
  • Testing: Start with small amounts (0.15-1 USDC)
  • Production: Use proper key management (AWS KMS, HashiCorp Vault, etc.)
  • Monitoring: Implement payment reconciliation and monitoring

πŸ§ͺ Testing

⭐ Featured Demo Prompt

Perfect for showcasing the app:

A serene Japanese zen garden at sunset, featuring a traditional stone lantern beside a koi pond with cherry blossom petals floating on the water, mountains in the background, photorealistic style, warm golden hour lighting, 4K quality

Recommended Aspect Ratio: 16:9 (Widescreen landscape) or 4:3 (Standard landscape)

This prompt creates a stunning, professional-quality image perfect for demos and social sharing!

Additional Test Prompts

Try these for variety:

  • "A cat wearing a space suit on Mars, photorealistic, 4K"
  • "Cyberpunk cityscape at night, neon lights, rain, cinematic"
  • "Watercolor painting of a serene mountain landscape"
  • "Abstract geometric art with vibrant colors and gradients"

Troubleshooting

"USDC not found in wallet"

  • Ensure you have USDC SPL token on Solana mainnet
  • Check your wallet on Solscan
  • USDC mint: EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v

Server errors

  • Verify GEMINI_API_KEY is set and valid
  • Check RECEIVER_ADDRESS is a valid Solana address (base58 format)
  • Ensure port 4024 is not in use

Client connection issues

  • Verify VITE_HELIUS_API_KEY is set
  • Check that server is running on port 4024
  • Ensure wallet is connected and on Solana mainnet

πŸ“š Learn More

🀝 Contributing

This is a demonstration project. For production use, consider:

Essential Enhancements

  • βœ… Proper error handling and retries
  • βœ… Rate limiting and abuse prevention
  • βœ… Monitoring and logging (Datadog, Sentry, etc.)
  • βœ… Secure key management (AWS KMS, HashiCorp Vault)
  • βœ… Comprehensive test suite
  • βœ… Payment verification and reconciliation
  • βœ… User authentication and session management
  • βœ… Image storage (IPFS, S3, etc.)

Scalability

  • Load balancing for multiple server instances
  • Redis for distributed caching
  • Queue system for image generation (Bull, BullMQ)
  • CDN for serving generated images

πŸ™ Acknowledgments

Built with amazing tools and services:

  • Google Gemini - AI image generation
  • AnySpend x402 - Payment protocol
  • Helius - Fast Solana RPC & DAS API
  • Solana - Blockchain infrastructure
  • Circle - USDC stablecoin

Built with ❀️ to demonstrate Solana payments with x402

🌟 Star this repo if you found it helpful!

For questions or issues, check the troubleshooting section above!

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors