Skip to content

HeimLabs/anyspend-x402-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

30 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

AnySpend x402 Fullstack Demo

A complete fullstack application demonstrating AnySpend x402 - a payment protocol that lets customers pay with any token (ETH, DAI, any ERC-20) while sellers receive USDC. This demo features a React frontend with browser wallet integration and Express backend with two working API endpoints.

πŸ› οΈ Tech Stack

Node.js TypeScript React Vite Express TailwindCSS Ethereum Base pnpm

🌟 Features

✨ Multi-Token Payments - Accept payments in various ERC-20 tokens (ETH, USDT, DAI, etc.), not just USDC
πŸŒ‰ Cross-Chain Support - Users pay on any supported network (Ethereum, Arbitrum, Optimism, Polygon, etc.)
πŸ”„ Automatic Conversion - AnySpend facilitator handles all swaps and bridging
πŸ’° You Receive USDC - All payments are automatically converted and settled to your address in USDC on Base
🎯 Browser Wallet Integration - Connect with MetaMask, WalletConnect, and other popular wallets
πŸ“Š Two Working APIs - TAAPI.io technical indicators and Twitter search endpoints

πŸ—οΈ Architecture

This demo showcases two distinct payment patterns using AnySpend x402:

Dual-Demo Architecture

flowchart TB
    subgraph Browser["Browser"]
        UI["React Frontend"]
        Wallet["Web3 Wallet"]
    end

    subgraph ProxyDemo["Demo 1: Proxy Endpoints"]
        Server["Express Server"]
        TAAPI["TAAPI.io"]
        Twitter["RapidAPI Twitter"]
    end

    subgraph A2ADemo["Demo 2: Agent-to-Agent"]
        ClientAgent["TradingAnalyst AI"]
        MerchantIndicator["IndicatorAPI"]
        MerchantTwitter["TwitterDataAPI"]
    end

    subgraph Payment["AnySpend x402"]
        Facilitator["Facilitator"]
        Swap["Token Swap & Bridge"]
    end

    subgraph Chains["Multi-Chain Support"]
        Base["Base"]
        Polygon["Polygon"]
        Arbitrum["Arbitrum"]
        BSC["BSC"]
    end

    subgraph Tokens["Multi-Token Payment"]
        UserTokens["User Pays:<br/>ETH, USDC, DAI, WETH"]
        MerchantTokens["Merchants Receive:<br/>USDC on Base"]
    end

    UI --> Server
    UI --> ClientAgent
    Wallet -->|"Any Token"| UI

    Server --> TAAPI
    Server --> Twitter
    Server -.-> Facilitator

    ClientAgent --> MerchantIndicator
    ClientAgent --> MerchantTwitter

    MerchantIndicator -.-> Facilitator
    MerchantTwitter -.-> Facilitator

    UserTokens --> Facilitator
    Facilitator --> Swap
    Swap --> MerchantTokens

    Facilitator --> Chains
    Chains --> Base
Loading

Key Features

  • πŸ’° Pay with Any Token: Users can pay in ETH, USDC, DAI, WETH, or any ERC-20
  • πŸŒ‰ Cross-Chain Payments: Support for Base, Polygon, Arbitrum, BSC, and more
  • πŸ”„ Automatic Conversion: AnySpend handles all token swaps and bridging
  • πŸ’΅ Receive USDC: Merchants receive USDC on Base regardless of payment token
  • ⚑ Gas-less Approvals: EIP-2612 permit support for one-click payments
  • πŸ€– AI Agent Integration: Autonomous agents with multi-chain wallets

πŸ“¦ Project Structure

This monorepo contains two complete demos: Proxy Endpoints (client + server) and Agent-to-Agent (3 AI agents).

anyspend-x402-demo/
β”œβ”€β”€ apps/
β”‚   β”œβ”€β”€ client/                        # React frontend (Proxy + A2A UI)
β”‚   β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”‚   β”œβ”€β”€ components/            # UI components
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ PaymentModal.tsx   # x402 payment approval UI
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ FundingModal.tsx   # Agent wallet funding
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ TaapiCard.tsx      # TAAPI demo card
β”‚   β”‚   β”‚   β”‚   └── TwitterCard.tsx    # Twitter demo card
β”‚   β”‚   β”‚   β”œβ”€β”€ config/                # Wagmi, RPC configs
β”‚   β”‚   β”‚   β”œβ”€β”€ hooks/                 # Custom React hooks
β”‚   β”‚   β”‚   β”œβ”€β”€ pages/
β”‚   β”‚   β”‚   β”‚   └── AgentDemo.tsx      # A2A demo page
β”‚   β”‚   β”‚   └── utils/                 # Utility functions
β”‚   β”‚   β”œβ”€β”€ vite.config.ts
β”‚   β”‚   └── [README](./apps/client/README.md)
β”‚   β”‚
β”‚   β”œβ”€β”€ server/                        # Express backend (Proxy Endpoints)
β”‚   β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”‚   β”œβ”€β”€ routes/                # API routes
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ taapi.ts           # Technical indicators
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ twitter.ts         # Twitter search
β”‚   β”‚   β”‚   β”‚   └── index.ts           # Balance fetching
β”‚   β”‚   β”‚   β”œβ”€β”€ services/              # External API clients
β”‚   β”‚   β”‚   β”œβ”€β”€ lib/                   # HTTP caching
β”‚   β”‚   β”‚   └── server/                # Express app + x402 middleware
β”‚   β”‚   └── [README](./apps/server/README.md)
β”‚   β”‚
β”‚   β”œβ”€β”€ client-agent/                  # TradingAnalyst AI (orchestrator)
β”‚   β”‚   β”œβ”€β”€ agent.ts                   # Main agent (1,613 lines)
β”‚   β”‚   β”œβ”€β”€ config.ts                  # Environment config
β”‚   β”‚   β”œβ”€β”€ server.ts                  # HTTP server
β”‚   β”‚   └── [README](./apps/client-agent/README.md)
β”‚   β”‚
β”‚   β”œβ”€β”€ merchant-agent-indicator/      # IndicatorAPI (TAAPI merchant)
β”‚   β”‚   β”œβ”€β”€ agent.ts                   # Agent definition
β”‚   β”‚   β”œβ”€β”€ server.ts                  # x402-protected server
β”‚   β”‚   └── [README](./apps/merchant-agent-indicator/README.md)
β”‚   β”‚
β”‚   β”œβ”€β”€ merchant-agent-twitter/        # TwitterDataAPI (RapidAPI merchant)
β”‚   β”‚   β”œβ”€β”€ agent.ts                   # Agent definition
β”‚   β”‚   β”œβ”€β”€ wrapped-agent.ts           # x402 wrapper
β”‚   β”‚   └── [README](./apps/merchant-agent-twitter/README.md)
β”‚   β”‚
β”‚   └── shared/                        # Shared code across all apps
β”‚       β”œβ”€β”€ config/
β”‚       β”‚   └── networks.ts            # EVM network definitions
β”‚       β”œβ”€β”€ utils/
β”‚       β”‚   └── permitDetection.ts     # EIP-2612 detection
β”‚       └── [README](./apps/shared/README.md)
β”‚
β”œβ”€β”€ .gitignore
β”œβ”€β”€ package.json                       # Root workspace config
β”œβ”€β”€ pnpm-workspace.yaml                # PNPM monorepo setup
β”œβ”€β”€ CONTRIBUTING.md                    # Development guidelines
└── README.md                          # This file

Key Directories

  • apps/client: React frontend with dual demos (Proxy + A2A)
  • apps/server: Express backend for Proxy Endpoints demo
  • apps/client-agent: AI orchestrator that calls merchant agents
  • apps/merchant-agent-*: x402-protected services (indicators, Twitter)
  • apps/shared: Reusable utilities and configurations

See individual app READMEs for detailed setup instructions.

πŸš€ Quick Start

Prerequisites

  • Node.js 18+ and pnpm
  • A wallet with funds on Base or Base Sepolia for testing
  • API keys for TAAPI.io and RapidAPI (Twitter)

1. Install Dependencies

From the root directory:

pnpm install

2. Configure Server

Create apps/server/.env (copy from .env.example):

# AnySpend x402 Configuration
ANYSPEND_FACILITATOR_URL=https://mainnet.anyspend.com/x402
ANYSPEND_NETWORK=base
ANYSPEND_RECEIVER_ADDRESS=0xYourWalletAddress  # Your address (receives USDC)
ANYSPEND_PRICE_USD=$0.01

# TAAPI Configuration
TAAPI_BASE_URL=https://api.taapi.io
TAAPI_SECRET_KEY=your_taapi_secret_key

# RapidAPI Twitter Configuration
RAPIDAPI_KEY=your_rapidapi_key
TWITTER_RAPIDAPI_HOST=twitter-v24.p.rapidapi.com

# Server Configuration
PORT=4021
NODE_ENV=development
CORS_ORIGIN=http://localhost:5173

3. Configure Client (Optional)

Create apps/client/.env:

VITE_API_URL=http://localhost:4021
VITE_CHAIN_ID=84532
VITE_WALLETCONNECT_PROJECT_ID=your_project_id_here

4. Run the Application

Start both client and server with hot reload:

pnpm dev

This will start:

  • React client at http://localhost:5173
  • Express server at http://localhost:4021

Or run individually:

# Server only
pnpm dev:server

# Client only
pnpm dev:client

🎯 How It Works

Payment Flow

  1. Connect Wallet - User connects browser wallet (MetaMask, WalletConnect, etc.)
  2. Select API - User chooses TAAPI indicators or Twitter search
  3. Initial Request - Frontend makes request to API endpoint
  4. 402 Payment Required - Server responds with payment requirements
  5. Sign Payment - User signs EIP-712 permit with their wallet
  6. Retry with Payment - Frontend retries request with X-PAYMENT header
  7. Verify & Swap - AnySpend facilitator verifies and swaps user's token to USDC
  8. Receive Data - Server returns API data after payment settlement

Multi-Token Support

The key power of AnySpend x402 is users can pay with any token they want:

  • Your server advertises: "$0.01 in USDC on Base"
  • User's wallet queries AnySpend facilitator for supported tokens
  • User sees 50+ payment options across multiple chains
  • User pays with their preferred token (ETH, DAI, USDC, or any ERC-20)
  • Facilitator automatically swaps to USDC and settles to your address
  • You receive exactly $0.01 in USDC

πŸ› οΈ API Endpoints

TAAPI Indicators (/api/taapi/:indicator)

Get real-time technical analysis indicators for crypto trading pairs.

Example: GET /api/taapi/rsi?symbol=BTC/USDT&exchange=binance&interval=1h

Twitter Search (/api/twitter/search)

Search Twitter for tweets, trends, and social mentions.

Example: GET /api/twitter/search?query=bitcoin&limit=10&section=latest

Both endpoints require x402 payment before returning data.

πŸ§ͺ Testing

  1. Get Base Sepolia testnet ETH from a faucet
  2. Get test USDC on Base Sepolia (contract: 0x036CbD53842c5426634e7929541eC2318f3dCF7e)
  3. Open http://localhost:5173
  4. Click "Connect Wallet" and connect your wallet
  5. Try either API demo by filling in parameters
  6. Click the button to trigger payment flow
  7. Sign the transaction in your wallet
  8. Watch as payment is verified and data is returned

πŸ“¦ Building for Production

pnpm build

This builds both apps:

  • Server β†’ apps/server/dist/
  • Client β†’ apps/client/dist/

πŸ” Security Notes

  • Private keys never leave the browser
  • Server only receives signed payment permits
  • Remote facilitator verifies signatures and balances
  • Use HTTPS in production for all communication
  • Payment amounts are verified before settlement

πŸ“š Resources

πŸ€– A2A Agent Demo

This project includes an Agent-to-Agent (A2A) payment demo with three AI agents:

Architecture

sequenceDiagram
    actor User
    participant UI as Web UI
    participant Client as TradingAnalyst AI
    participant Indicator as IndicatorAPI
    participant Twitter as TwitterDataAPI
    participant Facilitator as AnySpend Facilitator
    participant Chain as Blockchain

    User->>UI: Ask question
    UI->>Client: Send request
    Client->>Client: Analyze request
    Client->>UI: Request approval
    UI->>User: Show approval
    User->>UI: Approve
    UI->>Client: Confirmed

    par Call Services
        Client->>Indicator: POST with x402 header
        Indicator->>Facilitator: Verify payment
        Facilitator->>Chain: Check settlement
        Chain-->>Facilitator: Valid
        Facilitator-->>Indicator: Verified
        Indicator-->>Client: Return data
    and
        Client->>Twitter: POST with x402 header
        Twitter->>Facilitator: Verify payment
        Facilitator->>Chain: Check settlement
        Chain-->>Facilitator: Valid
        Facilitator-->>Twitter: Verified
        Twitter-->>Client: Return data
    end

    Client->>Client: Synthesize results
    Client->>UI: Return analysis
    UI->>User: Display results
Loading

Agents

  1. IndicatorAPI (Merchant Agent)

    • Provides technical analysis indicators from TAAPI.io
    • Accepts: USDC on Base, Polygon, Arbitrum
    • Port: 4022
  2. TwitterDataAPI (Merchant Agent)

    • Provides Twitter search and sentiment analysis
    • Accepts: USDC/Base, WETH/Arbitrum, DAI/Polygon
    • Port: 4023
  3. TradingAnalyst AI (Client Agent)

    • AI orchestrator with multi-chain wallets
    • Automatically pays merchants for data
    • Provides comprehensive crypto analysis
    • Port: 4024

Running the Agent Demo

  1. Install all dependencies:

    pnpm install
  2. Configure environment variables:

    Create .env files in each agent directory:

    • apps/merchant-agent-indicator/.env
    • apps/merchant-agent-twitter/.env
    • apps/client-agent/.env

    See README files in each agent directory for configuration details.

  3. Start all agents:

    # Terminal 1 - Merchant Agent 1
    pnpm dev:merchant1
    
    # Terminal 2 - Merchant Agent 2
    pnpm dev:merchant2
    
    # Terminal 3 - Client Agent
    pnpm dev:client-agent
    
    # Terminal 4 - Web UI
    pnpm dev:client

    Or start everything at once:

    pnpm dev:all
  4. Access the demo:

    • Open http://localhost:5173/agent-demo
    • Ask questions like:
      • "Should I buy BTC?"
      • "What's the sentiment on ETH?"
      • "Give me a full analysis on SOL"

Demo Scenarios

Scenario 1: Technical Analysis (BTC)

  • User: "Should I buy BTC?"
  • Agent calls IndicatorAPI
  • Pays $0.01 in USDC on Base
  • Returns RSI, MACD, and analysis

Scenario 2: Sentiment Analysis (ETH)

  • User: "What's sentiment on ETH?"
  • Agent calls TwitterDataAPI
  • Pays ~0.000003 WETH on Arbitrum (converted from $0.01)
  • Returns Twitter sentiment analysis

Scenario 3: Full Analysis (SOL)

  • User: "Full analysis on SOL"
  • Agent calls BOTH merchants
  • Makes TWO payments (different chains)
  • Returns combined technical + sentiment analysis

Payment Activity Log

TradingAnalyst keeps a live ledger of every x402 payment:

  • Amount, token, and network (e.g., 0.000003 WETH on arbitrum)
  • Preferred payment options requested by the client agent
  • Settlement status (pending β†’ settled / failed)
  • Transaction hash & payer when the facilitator returns a receipt

The frontend surfaces this under Payment Activity, while the client agent’s /run API returns { events, payments } for programmatic consumption.

Token Configuration

Supported tokens across chains:

Base:

  • USDC: 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913

Polygon:

  • USDC: 0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359
  • DAI: 0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063

Arbitrum:

  • USDC: 0xaf88d065e77c8cC2239327C5EDb3A432268e5831
  • WETH: 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1

Agent Details

For detailed configuration and usage, see:


πŸš€ Running the Demo

Development Mode (All Services)

# Install dependencies
pnpm install

# Run everything in parallel (client + server + all agents)
pnpm dev:all

Production Mode (Local Testing)

# Build all services
pnpm build

# Run all services (with nice colored output)
pnpm start:demo

Individual Services

pnpm dev:client        # React frontend only
pnpm dev:server        # Express backend only
pnpm dev:agents        # All 3 agents only
pnpm dev:client-agent  # TradingAnalyst AI only
pnpm dev:merchant1     # Indicator agent only
pnpm dev:merchant2     # Twitter agent only

πŸ“š Additional Resources

Documentation

External Links

About

No description, website, or topics provided.

Resources

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors