Skip to content

x402-utils implements a PoC for an agentic system on top of a cross-chain token using LayerZero.

Notifications You must be signed in to change notification settings

anton-io/x402-utils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

13 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

x402 Utils - Pay-per-Execution with X-Chain Token

A blockchain-based pay-per-execution service implementing the x402 protocol (HTTP 402 Payment Required). Users pay with U tokens (or signature-based payment) on Base Sepolia to execute jobs, with results streamed back in real-time.

Powered by: LayerZero Β· Privy Β· Coinbase Base Β· x402

Live demo at: https://x402.utils.com/

Status: βœ… Production-ready PoC Β· All tests passing Β· Multiple frontends Β· Python agent

πŸš€ Built With Industry-Leading Technologies

This project showcases the integration of three powerful blockchain infrastructure providers:

πŸ”— LayerZero

Omnichain Interoperability Protocol - Powers the U token with seamless cross-chain transfers between Ethereum and Base. No wrapped tokens, no bridges to trustβ€”just native cross-chain fungibility.

πŸ” Privy

Embedded Wallet Infrastructure - Provides frictionless web3 onboarding with social logins, embedded wallets, and delegated transaction signing. Users can interact with blockchain apps without managing private keys.

πŸ’³ Coinbase

Enterprise Blockchain Platform - Leverages Base L2 for high-performance, low-cost transactions. Base provides the scalability needed for microtransactions in the x402 protocol.

Why This Stack?

  • LayerZero: Cross-chain liquidity without fragmentation
  • Privy: Web2-level UX for web3 applications
  • Base (Coinbase): Production-ready L2 with institutional backing

πŸ“Έ See It In Action

x402 Protocol Web Interface - Ping Job Execution
x402 web interface executing a ping job with real-time streaming results


🎯 Overview

Payment Flows:

  1. Traditional: User β†’ 402 Response β†’ ERC20 Transfer β†’ Payment Verified β†’ Job Executes β†’ Results Stream
  2. x402 Signature: User β†’ Sign EIP-712 β†’ X-PAYMENT Header β†’ Instant Authorization β†’ Job Executes β†’ Results Stream
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  2 Frontends    │────▢│  FastAPI Backend │────▢│  Base Sepolia      β”‚
β”‚  + 1 Agent      │◀────│  (x402 Server)   │◀────│  Blockchain        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  β€’ Vanilla JS            β€’ Payment verify        β€’ U Token (ERC20)
  β€’ React + Privy         β€’ EIP-712 sigs          β€’ Payment tracking
  β€’ Python Agent          β€’ SSE streaming         β€’ Smart contracts

πŸ’° U Token - Cross-Chain Payment Token

The x402 protocol uses U Token, a custom ERC20 token built with LayerZero's Omnichain Fungible Token (OFT) standard. This enables seamless cross-chain transfers between networks.

Why Cross-Chain?

  • Ethereum (Sepolia): Primary network for liquidity and token minting
  • Base (Sepolia): Optimized for high-performance, low-cost transactions
  • LayerZero Bridge: Automatic token bridging between chains in ~5-10 minutes

Getting Test Tokens

A public testnet faucet is available for anyone to experiment with the x402 protocol:

  • Faucet Address: 0x63b7eF0778143E23f7320ab5bB77344aE66e7a57 (Base Sepolia)
  • Distribution: 1 U token per address per day
  • Purpose: Free tokens for testing and development
  • Explorer: View on Blockscout

U Token Addresses:

  • Sepolia: 0x3edEa36d049fFeF9Ac3fC3646227ca81C9A87118
  • Base Sepolia: 0x7143401013282067926d25e316f055fF3bc6c3FD

For more details on the U token and faucet management, see the u-layerzero/ and u-faucet/ directories.

πŸš€ Quick Start (1 Minute)

Fastest Way - Use the Start Script

./start.sh

This automatically starts:

Manual Setup

  1. Configure backend:

    cd x402-backend
    cp .env.example .env
    # Edit .env: RECIPIENT_ADDRESS=0xYourWalletAddress
  2. Run backend:

    cd x402-backend
    python -m venv venv
    source venv/bin/activate  # Windows: venv\Scripts\activate
    pip install -r requirements.txt
    python main.py
  3. Choose your frontend:

    Option A: Vanilla JS (MetaMask/Coinbase Wallet)

    cd x402-js
    python -m http.server 3000
    # Visit: http://localhost:3000

    Option B: React + Privy (Recommended - Full x402)

    cd x402-privy
    npm install
    npm run dev
    # Visit: http://localhost:3001
  4. Or run the Python agent:

    cd x402-agent
    pip install -r requirements.txt
    python x402_agent.py  # Pings google.com every 3 minutes

πŸ“Š Frontend Comparison

Feature Frontend-JS (3000) Frontend-Privy (3001) ⭐ Agent
Tech Vanilla JS React + Privy Python
Wallet MetaMask/Coinbase Privy Embedded Generated
Payment ERC20 Transfer x402 + Traditional x402 Signature
Auto-Approve ❌ No βœ… Yes (Delegation) N/A
x402 Protocol ❌ No βœ… Full Support βœ… Yes
Best For Testing basics Production use Automation
Setup None npm install pip install

Recommendation: Use Frontend-Privy (3001) for full x402 features and best UX.

πŸ—οΈ Architecture

Backend (FastAPI)

  • Dual payment support: Traditional ERC20 transfers + x402 signature-based
  • EIP-712 verification: Validates signed payment authorizations
  • Extensible job system: Plugin-based registry for easy job type additions
  • Payment verification: Monitors Base Sepolia for ERC20 Transfer events
  • Real-time streaming: Server-Sent Events (SSE) for live output
  • Timeout management: 5-minute configurable payment windows

Frontend Options

1. Frontend-JS (Port 3000)

  • Vanilla JavaScript with Web3.js
  • MetaMask/Coinbase Wallet integration
  • Traditional ERC20 payment flow
  • Asta framework monospace UI
  • No build process required

2. Frontend-Privy (Port 3001) ⭐ Recommended

  • React + TypeScript with Vite
  • Privy embedded wallet support
  • Full x402 signature-based payment
  • Delegated actions for auto-approve
  • Dual payment method (x402 + traditional)
  • Best developer experience

3. Python Agent

  • Autonomous x402 client
  • Periodic job execution
  • EIP-712 signature creation
  • No blockchain transaction needed
  • Perfect for automation/monitoring

Configuration

  • Network: Base Sepolia (Chain ID: 84532)
  • RPC: https://base-sepolia-rpc.publicnode.com
  • Token: U at 0x7143401013282067926d25e316f055fF3bc6c3FD
  • Pricing: 0.01 U per ping
  • Payment timeout: 300s (configurable via PAYMENT_TIMEOUT env var)

API Endpoints

Endpoint Method Description Response
/ GET Health check Service status
/api/jobs GET List available jobs Jobs with pricing
/api/jobs/request POST Request job execution 402 with payment details
/api/jobs/verify-payment POST Verify blockchain payment Verification status
/api/jobs/execute/{id} GET Execute paid job SSE stream
/api/jobs/status/{id} GET Check job status Job state

Adding New Jobs

Create a job class inheriting from Job:

# x402-backend/jobs/my_job.py
from decimal import Decimal
from .base import Job

class MyJob(Job):
    @classmethod
    def get_name(cls) -> str:
        return "my_job"

    @classmethod
    def get_price(cls) -> Decimal:
        return Decimal("0.05")

    def validate_params(self) -> tuple[bool, str]:
        # Validate self.params
        return True, ""

    async def execute(self) -> AsyncIterator[str]:
        yield "Starting...\n"
        # ... do work ...
        yield "Complete!\n"

Register in x402-backend/jobs/registry.py:

from .my_job import MyJob

class JobRegistry:
    def _register_default_jobs(self):
        self.register(PingJob)
        self.register(MyJob)  # Add this

Test Results

Date: 2025-11-22 Β· Status: βœ… All tests passed

  • βœ… Backend: Server startup, Base Sepolia connection (no warnings)
  • βœ… API: 7/7 endpoint tests passed
    • Health check, job listing, x402 flow, status, execution blocking
    • Input validation, error handling
  • βœ… Jobs: Ping execution successful (8.8.8.8, 0% packet loss)
  • βœ… Protocol: Complete x402 flow verified (request β†’ 402 β†’ verify β†’ execute)
  • βœ… Code: Python 3.12+ compatible, timezone-aware, lifespan context manager
  • βœ… Network: Base Sepolia RPC connected, token contract accessible

Environment: Linux Β· Python 3.12.12 Β· FastAPI 0.109.0 Β· Web3.py 6.15.1

Future Enhancements

  • Job result caching and storage
  • User accounts and history
  • Webhook notifications
  • Comprehensive test suite

License

MIT License

Resources

Blockchain Infrastructure

Development Tools

πŸ’¬ Feedback & Contributions

We'd love to hear from you! This project is open for ideas, suggestions, and contributions.

Share Your Thoughts

  • πŸ’‘ Ideas: Have a feature idea or improvement suggestion? We want to hear it!
  • πŸ› Issues: Found a bug or something not working as expected? Let us know!
  • πŸ’¬ Feedback: General comments, questions, or thoughts about the x402 protocol? Reach out!
  • 🀝 Contributions: Pull requests are welcome! Whether it's code, documentation, or examples.

Get In Touch πŸ“§

  • Share Use Cases. Show us what you've built or plan to build with the x402 protocol.

  • Open an issue on this repository or submit a pull request. All contributions and feedback are appreciated! πŸ™


About

x402-utils implements a PoC for an agentic system on top of a cross-chain token using LayerZero.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published