4️⃣API Flow

Table of Contents

  1. Architecture

  2. Flow Diagrams

  3. Detailed Step-by-Step Flow Architecture

  4. β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚   Client    β”‚
    β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
           β”‚
           β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚  POST /api/process              β”‚
    β”‚  (x402Middleware)               β”‚
    β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚
           β”œβ”€β”€β”€ Has X-PAYMENT Header? ──► handlePaymentVerification()
           β”‚                                    β”‚
           β”‚                                    β”œβ”€β–Ί Verify with Facilitator
           β”‚                                    β”œβ”€β–Ί Retrieve Transaction
           β”‚                                    └─► Return for Execution
           β”‚
           β”œβ”€β”€β”€ Has operationId? ──────────► handlePaymentRequest()
           β”‚                                    β”‚
           β”‚                                    β”œβ”€β–Ί Retrieve Operation from DB
           β”‚                                    └─► Return 402 Payment Required
           β”‚
           └─── Neither? ─────────────────► X402Controller.handleQuery()
                                                β”‚
                                                β”œβ”€β–Ί Validate Input
                                                β”œβ”€β–Ί Process with AI
                                                β”œβ”€β–Ί Generate Transaction
                                                └─► Save to DB & Return operationId

    Flow Diagrams

    Flow 1: Initial Chat/Query Request

    Client                     API                      AI Service              Database
      β”‚                        β”‚                            β”‚                      β”‚
      │──POST {messages}──────►│                            β”‚                      β”‚
      β”‚   wallet, chain        β”‚                            β”‚                      β”‚
      β”‚                        │──Validate Input───────────►│                      β”‚
      β”‚                        β”‚                            β”‚                      β”‚
      β”‚                        │──Process Query────────────►│                      β”‚
      β”‚                        β”‚                            β”‚                      β”‚
      β”‚                        │◄─AI Response────────────────                      β”‚
      β”‚                        β”‚  (transaction data)        β”‚                      β”‚
      β”‚                        β”‚                            β”‚                      β”‚
      β”‚                        │──Save Operation───────────────────────────────────►│
      β”‚                        β”‚                            β”‚                      β”‚
      │◄─Response with──────────                            β”‚                      β”‚
      β”‚  operationId           β”‚                            β”‚                      β”‚
      β”‚                        β”‚                            β”‚                      β”‚

    Flow 2: Payment Request

    Client                     API                    Database              Facilitator
      β”‚                        β”‚                         β”‚                      β”‚
      │──POST {operationId}───►│                         β”‚                      β”‚
      β”‚                        β”‚                         β”‚                      β”‚
      β”‚                        │──Get Operation─────────►│                      β”‚
      β”‚                        β”‚                         β”‚                      β”‚
      β”‚                        │◄─Operation Data──────────                      β”‚
      β”‚                        β”‚                         β”‚                      β”‚
      │◄─402 Payment Required───                         β”‚                      β”‚
      β”‚  (payment config)      β”‚                         β”‚                      β”‚
      β”‚                        β”‚                         β”‚                      β”‚

    Flow 3: Payment Verification & Execution

    Client                     API                    Database              Facilitator
      β”‚                        β”‚                         β”‚                      β”‚
      │──POST {operationId}───►│                         β”‚                      β”‚
      β”‚  X-PAYMENT: xxx        β”‚                         β”‚                      β”‚
      β”‚                        │──Verify Payment────────────────────────────────►│
      β”‚                        β”‚                         β”‚                      β”‚
      β”‚                        │◄─Payment Valid───────────────────────────────────
      β”‚                        β”‚                         β”‚                      β”‚
      β”‚                        │──Mark as Paid──────────►│                      β”‚
      β”‚                        β”‚                         β”‚                      β”‚
      β”‚                        │──Get Transaction────────►│                      β”‚
      β”‚                        β”‚                         β”‚                      β”‚
      │◄─Transaction Data───────                         β”‚                      β”‚
      β”‚  (ready to execute)    β”‚                         β”‚                      β”‚
      β”‚                        β”‚                         β”‚                      β”‚

    Detailed Step-by-Step Flow

    Phase 1: Initial Request (Chat/Query)

    Step 1: Client Sends Natural Language Query

    Endpoint: POST /api/x402/process

    Request Body:

    {
      "messages": [
        { "role": "user", "content": "Send 10 USDC to 0xRecipientAddress" }
      ],
      "wallet": "0xYourWalletAddress",
      "chain": "base"
    }

    Step 2: Middleware Check

    The x402Middleware checks the request:

    • ❌ No X-PAYMENT header β†’ Continue

    • ❌ No operationId β†’ Continue

    • βœ… Pass to controller

    Step 3: Input Validation

    The controller validates:

    • Messages Array: Must be non-empty array with role and content

    • Chain: Must be one of base, polygon, avalanche, or solana

    • Wallet Address: Must match the chain type format

      • EVM chains: 0x + 40 hex characters

      • Solana: Base58, 32-44 characters

    Step 4: AI Processing

    The X402Service processes the query:

    1. Sends messages to AI (OpenAI)

    2. AI analyzes the intent

    3. Generates appropriate blockchain transaction(s)

    Step 5: Save to Database

    • Creates a new Operation record

    • Stores: messages, wallet, chain, transactions, status

    • Generates unique operationId

    Step 6: Response

    {
      "status": "success",
      "operationId": "clxxx123456789",
      "message": "Transaction prepared",
      "requiresPayment": true
    }

    Phase 2: Payment Request

    Step 1: Client Requests Payment Info

    Endpoint: POST api.hashhunter.app/api/process

    Request Body:

    {
      "operationId": "clxxx123456789"
    }

    Step 2: Middleware Routing

    The x402Middleware detects:

    • βœ… Has operationId

    • ❌ No X-PAYMENT header

    • β†’ Routes to handlePaymentRequest()

    Step 3: Retrieve Operation

    • Queries database for operation by ID

    • Validates operation exists

    • Extracts chain information

    Step 4: Generate Payment Configuration

    Creates X402 payment requirements:

    {
      scheme: "exact",
      network: "base", // or polygon, avalanche, solana
      resource: "https://api.hashhunter.app/api/process",
      payTo: "0x5bc818f625cad773d35c6b81e944cc820a00bfc0",
      asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC
      maxAmountRequired: "0",
      maxTimeoutSeconds: 300
    }

    Step 5: Return 402 Response

    {
      "x402Version": 1,
      "error": "Token payment required",
      "accepts": [
        {
          /* payment config */
        }
      ],
      "operationId": "clxxx123456789"
    }

    Phase 3: Payment Verification & Transaction Retrieval

    Step 1: Client Submits Payment Proof

    Endpoint: POST api.hashhunter.app/api/process

    Headers:

    X-PAYMENT: <payment_proof_string>

    Request Body:

    {
      "operationId": "clxxx123456789"
    }

    Step 2: Middleware Routing

    The x402Middleware detects:

    • βœ… Has X-PAYMENT header

    • β†’ Routes to handlePaymentVerification()

    Step 3: Payment Verification

    1. Decode Payment: Parses X-PAYMENT header

    2. Retrieve Operation: Gets operation from database

    3. Build Payment Config: Creates verification requirements

    4. Verify with Facilitator: Calls facilitator service at https://facilitator.payai.network

      const settleResponse = await settle(payment, paymentConfig);
    5. Check Result: Validates settleResponse.success

    Step 4: Update Database

    If payment is valid:

    • Marks operation as paid

    • Stores payment transaction hash

    • Timestamps the payment

    Step 5: Format Transactions

    Prepares transactions for execution:

    // EVM Transaction
    {
      type: "evm",
      data: {
        to: "0x...",
        data: "0x...",
        value: "0",
        chainId: 8453
      }
    }
    
    // Solana Transaction
    {
      type: "svm",
      data: "base64_encoded_transaction"
    }

    Step 6: Return Transaction

    {
      "status": "success",
      "message": "Payment verified. Transaction ready for execution.",
      "operationId": "clxxx123456789",
      "transactions": [
        {
          "type": "evm",
          "data": {
            /* transaction object */
          }
        }
      ]
    }

    Step 7: Client Executes Transaction

    The client now has the transaction data and can:

    1. Sign the transaction with their wallet

    2. Broadcast to the blockchain

    3. Wait for confirmation

Last updated