# API Flow

### <br>

### 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

<br>

#### Phase 1: Initial Request (Chat/Query)

**Step 1: Client Sends Natural Language Query**

**Endpoint:** `POST /api/x402/process`

**Request Body:**

```json
{
  "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**

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

#### Phase 2: Payment Request

**Step 1: Client Requests Payment Info**<br>

**Endpoint:** `POST api.hashhunter.app/api/process`\ <br>

\
\
**Request Body:**

```json
{
  "operationId": "clxxx123456789"
}
```

\
\
**Step 2: Middleware Routing**<br>

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:

```javascript
{
  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**<br>

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

####

#### Phase 3: Payment Verification & Transaction Retrieval

\
\
**Step 1: Client Submits Payment Proof**<br>

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

**Headers:**<br>

```
X-PAYMENT: <payment_proof_string>
```

**Request Body:**

```json
{
  "operationId": "clxxx123456789"
}
```

**Step 2: Middleware Routing**<br>

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`

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

\
**Step 4: Update Database**<br>

If payment is valid:

* Marks operation as `paid`
* Stores payment transaction hash
* Timestamps the payment

\
**Step 5: Format Transactions**<br>

Prepares transactions for execution:

```javascript
// 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**<br>

```json
{
  "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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.hashhunter.ai/hash-hunter-x402-endpoint/api-flow.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
