Skip to content

uuzor/x402-ts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

ADK TypeScript Logo

ATP Micropayment Agent

Example agent demonstrating how to build monetized, pay-per-request AI workflows with ADK-TS and x402
LLM-powered β€’ x402 Micropayments β€’ IQ AI ATP Integration β€’ TypeScript

Example project showing how to build agents that access paid API endpoints using the x402 micropayment protocol. This sample demonstrates the complete pattern: an ADK-TS agent with payment-enabled tools, a local x402 server that proxies premium endpoints, and user-friendly pricing disclosure. Developers can use this as a foundation for building their own monetized AI services.

Features

  • πŸ’° x402 Micropayments: Automatic payment handling for premium API endpoints using the x402 protocol
  • πŸ”’ Payment-Gated Tools: Secure access to IQ AI's ATP data through a local payment server
  • πŸ’΅ Transparent Pricing: Upfront pricing disclosure with user confirmation before charges
  • 🌐 Local Payment Server: Hono-based x402 proxy that protects ATP endpoints
  • πŸ› οΈ Multi-Tool Architecture: Demonstrates building agents with multiple payment-enabled tools
  • πŸ“Š ATP Data Access: Fetch token prices, agent stats, wallet holdings, and leaderboards
  • 🎯 Extensible Pattern: Easy to adapt for your own monetized AI services
  • πŸ’¬ User-Friendly UX: Clear pricing communication and graceful fallbacks

Architecture and Workflow

This project demonstrates a complete micropayment-enabled agent architecture:

  1. ADK-TS Agent - Main conversational agent with x402-enabled tools
  2. Payment Server - Hono + x402 middleware proxy for ATP endpoints
  3. ATP API - IQ AI's premium data endpoints (token prices, stats, etc.)
  4. x402 Protocol - Handles automatic micropayments via wallet integration

Project Structure

atp-micropayment-agent/
β”œβ”€β”€ src/
β”‚   └── agents/
β”‚       └── atp-agent/
β”‚           β”œβ”€β”€ agent.ts            # Agent behaviour + instructions
β”‚           └── tools.ts            # Payment-enabled ATP tools
β”‚   β”œβ”€β”€ server/                         # Payment Server (Hono + x402)
β”‚   β”‚   └── index.ts                    # x402 middleware & ATP proxy routes
β”‚   └── env.ts                          # Shared environment configuration
β”œβ”€β”€ package.json                        # Dependencies and scripts
β”œβ”€β”€ tsconfig.json                       # TypeScript configuration
└── README.md

Data Flow

graph TB
    %% User Interaction
    User[πŸ‘€ User Query] --> Agent[πŸ€– ADK-TS Agent<br/>ATP Micropayment Agent]

    %% Initial Price Fetch (Free)
    Agent --> GetPrices[πŸ“‹ GET_PRICES Tool<br/>Free endpoint - no payment]
    GetPrices --> baseApiClient[πŸ“‘ Base Axios Client<br/>No payment interceptor]
    baseApiClient --> PriceListEndpoint[πŸ†“ /api/price-list<br/>Free endpoint on server]
    PriceListEndpoint --> PriceResponse[πŸ’° Price Information<br/>Returns endpoint costs]

    %% Agent shows prices to user
    PriceResponse --> Agent
    Agent --> ShowPrices[πŸ’¬ Disclose Costs<br/>Show pricing to user]

    %% User makes request for paid data
    ShowPrices --> UserRequest[πŸ‘€ User Requests Data]
    UserRequest --> ToolSelection[πŸ” Tool Selection<br/>Identifies required ATP endpoint]

    %% User Confirmation
    ToolSelection --> Confirmation{βœ… User Confirms Payment?}
    Confirmation -->|No| Cancel[❌ Operation Cancelled]
    Confirmation -->|Yes| Payment[πŸ’³ Payment Execution]

    %% Payment Flow via x402-axios
    Payment --> x402Client[πŸ” x402-axios Interceptor<br/>Adds payment headers]
    x402Client --> PaymentServer[πŸ›‘οΈ Payment Server<br/>Hono + x402 middleware]

    %% Server Processing
    PaymentServer --> Validate[βœ“ Validate Payment<br/>Check with facilitator]
    Validate -->|Invalid| PaymentError[❌ Payment Failed<br/>Return 402]
    Validate -->|Valid| ProxyRequest[πŸ“‘ Proxy Handler<br/>Forward to ATP API]

    %% ATP API
    ProxyRequest --> ATPAPI[🏒 IQ AI ATP API<br/>Token prices, stats, holdings]
    ATPAPI --> Response[πŸ“Š ATP Data Response]

    %% Return Flow
    Response --> PaymentServer
    PaymentServer --> x402Client
    x402Client --> Agent
    Agent --> Format[πŸ“ Format Response<br/>Present to user]
    Format --> UserResponse[πŸ’¬ Final Response<br/>ATP data with context]

    %% Styling
    classDef userLayer fill:#e1f5fe,color:#01579b
    classDef agentLayer fill:#fff3e0,color:#e65100
    classDef paymentLayer fill:#f3e5f5,color:#4a148c
    classDef serverLayer fill:#e8f5e9,color:#1b5e20
    classDef apiLayer fill:#fce4ec,color:#880e4f
    classDef freeLayer fill:#e8f5e9,color:#2e7d32

    class User,Confirmation,Cancel,UserRequest userLayer
    class Agent,ToolSelection,ShowPrices,Format,UserResponse agentLayer
    class Payment,x402Client,Validate,PaymentError paymentLayer
    class PaymentServer,ProxyRequest serverLayer
    class ATPAPI,Response apiLayer
    class GetPrices,baseApiClient,PriceListEndpoint,PriceResponse freeLayer
Loading

Getting Started

Prerequisites

  • Node.js 18+
  • Google AI API key (Gemini) for LLM access
  • Base Sepolia wallet funded with test ETH and USDC
  • Basic understanding of x402 payment flows

Installation

  1. Clone this repository
git clone https://github.com/IQAIcom/adk-ts-samples.git
cd adk-ts-samples/agents/atp-micropayment-agent
  1. Install dependencies
pnpm install
  1. Get Your API Keys

  2. Set up environment variables

cp .env.example .env

Edit .env with your configuration:

# === Agent Configuration ===
WALLET_PRIVATE_KEY=your_wallet_private_key_here
GOOGLE_API_KEY=your_google_api_key_here
LLM_MODEL=gemini-2.5-flash
API_SERVER_URL=http://localhost:3001
ADK_DEBUG=false

# === Server Configuration ===
FACILITATOR_URL=https://x402.org/facilitator
ADDRESS=your_wallet_address_here
NETWORK=base-sepolia
IQ_API_BASE_URL=https://app.iqai.com/api

Running the Agent

# Start both server and agent together
pnpm dev

# Or run separately
pnpm dev:server  # Terminal 1 - starts server on http://localhost:3001
pnpm dev:agent   # Terminal 2 - starts agent with ADK web interface

# Interactive testing with ADK CLI
adk run   # CLI chat interface
adk web   # Web interface

This will start:

  • Server on http://localhost:3001 - x402 payment proxy
  • Agent via adk web on https://adk-web.iqai.com - browser-based chat interface

Usage Examples

The agent demonstrates micropayment workflows for accessing ATP data. Here's a sample interaction:

πŸ‘€ User: Hi! Can you show me the top agents by market cap?
πŸ€– Agent: Hi there! I am your ATP Micropayment Agent. Please note that some actions may incur costs via the x402 protocol:
        - /api/prices: $0.01
        - /api/holdings: $0.05
        - /api/agents/info: $0.05
        - /api/agents/stats: $0.05
        - /api/agents/top: $0.10

        To get the top agents by market cap, I'll need to make a paid call ($0.10). Should I proceed?
πŸ‘€ User: Yes, proceed
πŸ€– Agent: [Executes x402 payment and retrieves data] Here are the top agents by market cap...

Example Queries:

  • "What are the current token prices?"
  • "Show me holdings for wallet address 0x..."
  • "Get information about agent at address 0x..."
  • "What are the performance stats for agent 0x...?"
  • "List the top 10 agents by number of holders"

Payment Flow:

  1. ✨ Agent displays pricing for available endpoints
  2. πŸ’¬ User requests paid data
  3. πŸ” Agent asks for explicit confirmation
  4. πŸ’Έ Wallet automatically pays via x402 protocol
  5. πŸ“Š Server proxies request to ATP API and returns data

Available Endpoints

Endpoint Price Description
/api/price-list Free Get endpoint pricing information
/api/prices $0.01 Get current token prices
/api/holdings $0.05 Get wallet holdings for IQ AI agents
/api/agents/info $0.05 Get agent metadata by contract address
/api/agents/stats $0.05 Get agent performance statistics
/api/agents/top $0.10 Get top agents by various metrics

Check Server Status

# Check if your server is running and view available endpoints
curl http://localhost:3001/api/price-list

Expected response showing endpoint prices:

{
	"prices": {
		"/api/prices": { "price": "$0.01", "network": "base-sepolia" },
		"/api/holdings": { "price": "$0.05", "network": "base-sepolia" },
		"/api/agents/info": { "price": "$0.05", "network": "base-sepolia" },
		"/api/agents/stats": { "price": "$0.05", "network": "base-sepolia" },
		"/api/agents/top": { "price": "$0.10", "network": "base-sepolia" }
	}
}

Useful Resources

ADK-TS Framework

x402 Protocol

IQ AI ATP

Community

Contributing

This ATP Micropayment Agent is part of the ADK-TS Samples repository, a collection of sample projects demonstrating ADK-TS capabilities.

We welcome contributions to the ADK-TS Samples repository! You can:

  • Add new sample projects showcasing different ADK-TS features
  • Improve existing samples with better documentation, new features, or optimizations
  • Fix bugs in current implementations
  • Update dependencies and keep samples current

Please see our Contributing Guide for detailed guidelines.

License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ’° Ready to build monetized AI workflows? This sample demonstrates the complete pattern for building pay-per-request agents with ADK-TS and x402.

About

Pay money

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors