Menu

Explorer & Settings

Tempo Explorer Submit Project
Back to all projects

payflow-x402

by minalkharat-cmd · Updated 5 months ago

AI Agent Payment Protocol for Cronos x402 Paytech Hackathon - Autonomous x402 payments on Cronos blockchain

In the AI payments ecosystem

payflow-x402 is an early-stage Solidity project in the AI payments / x402 ecosystem. It currently has 0 GitHub stars and 0 forks.

README.md View on GitHub →

PayFlow x402 - AI Agent Payment Protocol 🤖💰

Cronos Testnet x402 Protocol License: MIT

🏆 Cronos x402 Paytech Hackathon Submission

PayFlow is a decentralized payment orchestration protocol that enables AI agents to autonomously pay for premium services using the x402 (HTTP 402 Payment Required) standard on the Cronos blockchain.


🎯 Problem We Solve

How can AI agents pay for services without human intervention?

As AI agents become more autonomous, they need the ability to access premium APIs, data feeds, and services independently. PayFlow bridges this gap by implementing the x402 protocol standard.

The Flow

  1. 🔍 AI Agent requests a protected resource
  2. 💳 Server returns HTTP 402 Payment Required with x402 challenge
  3. 🧠 Agent autonomously decides whether to pay (budget/rules)
  4. ⛓️ Agent executes on-chain payment via PayFlowOrchestrator
  5. ✅ Agent receives access to premium data

🏗️ Architecture

┌─────────────────┐     HTTP 402      ┌─────────────────┐
│    AI Agent     │◄──────────────────│   x402 Backend  │
│  (client.js)    │                   │   (server.js)   │
└────────┬────────┘                   └────────┬────────┘
         │                                     │
         │  executePayment()                   │  verifyPayment()
         ▼                                     ▼
┌──────────────────────────────────────────────────────────┐
│              PayFlowOrchestrator Contract                │
│     Cronos Testnet: 0x8A0918149BD77326db99Da1...         │
└──────────────────────────────────────────────────────────┘

📦 Components

Component Description
contracts/PayFlowOrchestrator.sol On-chain payment router with agent registry
backend/server.js x402 Gateway - returns 402 challenges for unpaid requests
agent/client.js Autonomous AI agent with payment decision logic

🚀 Quick Start

Prerequisites

  • Node.js v18+
  • npm or yarn
  • (Optional) Cronos Testnet wallet with TCRO

1. Clone & Install

git clone https://github.com/minalkharat-cmd/payflow-x402.git
cd payflow-x402

2. Start the x402 Backend Gateway

cd backend
npm install
npm start
# ✅ Server runs on http://localhost:3402

3. Run the AI Agent (Demo Mode)

cd agent
npm install
npm start
# 📡 Shows x402 flow without requiring wallet

4. Run with Real Wallet (Full Flow)

# Create agent/.env file
echo "PRIVATE_KEY=your_cronos_testnet_private_key" > agent/.env
npm start
# 💰 Executes real on-chain payments!

📋 Deployed Contract

Field Value
Network Cronos Testnet (Chain ID: 338)
Contract Address 0x8A0918149BD77326db99Da12703D4aEd2df507Ae
Fee Collector 0xA812cF8ED517B6e8B70E2405FaBE88ab83AB6f1C
Compiler Solidity v0.8.20
Optimizer Enabled (200 runs)
Explorer View on Cronos Explorer

🔄 x402 Protocol Flow

// 1️⃣ Agent requests premium data
GET /api/premium/ai-market-analysis

// 2️⃣ Server returns 402 with x402 challenge
HTTP 402 Payment Required
{
  "error": "Payment Required",
  "x402Challenge": {
    "x402Version": "1.0",
    "contractAddress": "0x8A0918149BD77326db99Da12703D4aEd2df507Ae",
    "network": "cronos-testnet",
    "chainId": 338,
    "serviceId": "ai-market-analysis",
    "priceWei": "10000000000000000",
    "priceFormatted": "0.01 TCRO"
  }
}

// 3️⃣ Agent executes on-chain payment
const tx = await contract.executePayment("ai-market-analysis", { 
  value: ethers.parseEther("0.01") 
});
await tx.wait();

// 4️⃣ Agent verifies payment with backend
POST /api/verify-payment
{ "txHash": "0x...", "serviceId": "ai-market-analysis" }

// 5️⃣ Agent retries with payment proof
GET /api/premium/ai-market-analysis
Headers: { "x-payment-proof": "0x...txhash" }

// 6️⃣ Server returns premium data!
HTTP 200 OK
{
  "service": "ai-market-analysis",
  "data": {
    "analysis": "BULLISH",
    "confidence": 0.85,
    "signals": ["RSI oversold", "MACD crossover"],
    "recommendation": "BUY"
  }
}

🧪 API Endpoints

Endpoint Method Description
/ GET Health check & gateway info
/api/services GET List available premium services
/api/premium/:serviceId GET Premium data (returns 402 if unpaid)
/api/verify-payment POST Verify on-chain payment

🔐 Smart Contract Features

  • Agent Registry: Agents register on-chain with unique IDs
  • Service Registry: Providers list services with TCRO/ERC-20 pricing
  • Payment Execution: Secure, reentrancy-protected payments
  • Platform Fee: Configurable fee (default 0.5%)
  • Pausable: Emergency pause functionality
  • Reputation System: Track agent/service reputation scores

🏆 Hackathon Tracks

This project targets:

  • Main Track: x402 Applications - Broad use cases
  • Best x402 AI Agentic Finance: Autonomous agent payments

🛠️ Tech Stack

  • Blockchain: Cronos Testnet
  • Smart Contracts: Solidity 0.8.20, OpenZeppelin
  • Backend: Node.js, Express.js, ethers.js v6
  • Agent: Node.js, axios, ethers.js v6
  • Decision Brain: Custom AI decision layer

🧠 Decision Brain - Intelligent Payment Decisions

PayFlow includes a Decision Brain - an intelligent Economic Decision Layer that transforms agents from simple price-threshold payers into sophisticated economic decision-makers.

Components

Component Purpose
ValueEstimator Estimates data value based on service type & market volatility
ROICalculator Calculates expected return on investment
ReputationChecker Queries on-chain provider reputation
BudgetManager Enforces daily/per-service spending limits
StrategyEngine Combines factors using configurable strategies

Strategies

# Configure via environment variable
STRATEGY=conservative  # More cautious, higher threshold (70)
STRATEGY=balanced      # Default, moderate threshold (55)
STRATEGY=aggressive    # More willing to pay, lower threshold (45)

Decision Output

🧠 Decision Brain Analysis:
─────────────────────────────────────────────
   ├─ Value Score: 78/100
   ├─ ROI Score: 65/100 (Expected: 145.0%)
   ├─ Reputation: 92/100
   ├─ Budget: 85/100
   └─ Final Score: 79/100 (threshold: 55)
─────────────────────────────────────────────

✅ Decision: PAY
   Confidence: 79.0%
   Reasoning: Approved: Reputation score strong (92/100)

Configuration

# agent/.env
PRIVATE_KEY=your_key
STRATEGY=balanced           # aggressive, balanced, conservative
DAILY_BUDGET=0.1           # Daily limit in TCRO
MARKET_VOLATILITY=0.5      # 0-1, higher = data more valuable

🤖 Autonomous Mode

PayFlow supports full autonomous operation with goal-based execution:

Features

Module Capability
ServicePipeline Chain multiple services in parallel/sequential
ServiceDiscovery Auto-discover on-chain services
SelfHealingEngine Retry, circuit breaker, fallback
AutonomousAgent Goal-based orchestration

Usage

# Run in autonomous mode
node client.js --autonomous

# Or shorthand
node client.js -a

Goal Execution

const result = await autonomousAgent.executeGoal({
    objective: 'Analyze market conditions for trading decision',
    budget: ethers.parseEther('0.03'),
    constraints: ['ROI > 1.5', 'confidence > 0.6']
});

Dashboard Output

╔════════════════════════════════════════════════════════════╗
║              🤖 PayFlow Autonomous Agent                    ║
╠════════════════════════════════════════════════════════════╣
║  Mode: AUTONOMOUS                                           ║
║  Budget: 0.05 TCRO                                          ║
╠════════════════════════════════════════════════════════════╣
║  📡 Discovery    Services: 3     Active: 3                  ║
║  🛡️ Self-Healing  Success: 95%   Circuit Breaks: 0          ║
╚════════════════════════════════════════════════════════════╝

📁 Project Structure

PayFlow-x402/
├── contracts/
│   └── PayFlowOrchestrator.sol    # Main contract
├── backend/
│   ├── server.js                   # x402 Gateway
│   └── package.json
├── agent/
│   ├── client.js                   # AI Agent
│   ├── decision-brain.js           # 🧠 Decision Brain
│   ├── decision-history.json       # Learning history
│   └── package.json
├── README.md
└── hardhat.config.js

🤝 Contributing

Contributions welcome! Please open an issue or PR.

📄 License

MIT License - see LICENSE for details.


Built with ❤️ for the Cronos x402 Paytech Hackathon 🚀

GitHubContract Explorer

All x402 projects →