> For the complete documentation index, see [llms.txt](https://docs.atlas-ai.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.atlas-ai.org/x402-protocol/how-it-works.md).

# How It Works

## The Query Flow

### Step 1: Agent Discovers Endpoint

An AI agent (or any client) discovers an ATLAS x402 endpoint through:

* API marketplace listings
* Direct URL knowledge
* Federation discovery (future)

### Step 2: Initial Request

```http
GET /x402/query?q=prediction+markets+mana HTTP/1.1
Host: your-atlas.example.com
```

### Step 3: Payment Required Response

If payment is needed, ATLAS returns:

```http
HTTP/1.1 402 Payment Required
X-Payment-Amount: 0.01
X-Payment-Currency: USDC
X-Payment-Network: solana
X-Payment-Address: <solana-wallet-address>
X-Payment-Memo: query-<unique-id>
Content-Type: application/json

{
  "status": "payment_required",
  "amount": "0.01",
  "currency": "USDC",
  "network": "solana",
  "payment_address": "<address>",
  "memo": "query-abc123",
  "preview": "Found 15 concepts related to prediction markets...",
  "expires": "2024-01-15T12:00:00Z"
}
```

### Step 4: Payment Submission

The agent submits payment on Solana with the memo field:

```
Transfer 0.01 USDC to <payment_address>
Memo: query-abc123
```

### Step 5: Payment Verification

ATLAS monitors for the transaction:

* Checks payment amount matches
* Verifies memo field
* Confirms transaction finality

### Step 6: Knowledge Delivery

Once payment confirms:

```http
HTTP/1.1 200 OK
Content-Type: application/json

{
  "status": "success",
  "query": "prediction markets mana",
  "results": {
    "concepts": [...],
    "insights": [...],
    "sources": [...]
  },
  "metadata": {
    "total_concepts": 15,
    "query_time_ms": 124,
    "payment_tx": "<solana-tx-signature>"
  }
}
```

***

## Payment Flow Diagram

```
┌─────────┐     ┌─────────┐     ┌──────────┐     ┌─────────┐
│  Agent  │────▶│  ATLAS  │────▶│  Solana  │────▶│  ATLAS  │
└─────────┘     └─────────┘     └──────────┘     └─────────┘
     │               │               │               │
     │   1. Query    │               │               │
     │──────────────▶│               │               │
     │               │               │               │
     │  2. 402 +     │               │               │
     │  Payment Info │               │               │
     │◀──────────────│               │               │
     │               │               │               │
     │         3. Send Payment       │               │
     │──────────────────────────────▶│               │
     │               │               │               │
     │               │  4. Verify    │               │
     │               │◀──────────────│               │
     │               │               │               │
     │  5. Deliver Knowledge         │               │
     │◀──────────────────────────────────────────────│
```

***

## Technical Components

### Payment Verification Module

ATLAS includes a Solana-integrated billing module:

```python
# Simplified flow
async def verify_payment(query_id: str, expected_amount: float):
    # Monitor Solana for transaction with memo
    tx = await solana_client.find_transaction(memo=f"query-{query_id}")
    
    if tx and tx.amount >= expected_amount:
        return PaymentVerified(tx_signature=tx.signature)
    
    return PaymentPending()
```

### Pricing Engine

Dynamic pricing based on query complexity:

| Factor        | Impact                         |
| ------------- | ------------------------------ |
| Concept count | More concepts = higher price   |
| Query depth   | Deeper analysis = higher price |
| Freshness     | Recent data = premium          |
| Exclusivity   | Rare knowledge = premium       |

### Caching Layer

Paid queries are cached:

* Same query from same payer = free replay (24h)
* Prevents double-charging for retries
* Optimizes ATLAS compute resources

***

## Security Considerations

### For Knowledge Providers

* **Wallet security** — Use dedicated payment-receiving wallet
* **Rate limiting** — Prevent query spam
* **Access control** — Choose what to expose via x402
* **Audit logging** — Track all paid queries

### For Knowledge Consumers

* **Payment limits** — Set per-query and daily caps
* **Preview validation** — Verify preview before paying
* **Receipt tracking** — Keep transaction records
* **Retry handling** — Protocol handles network issues

***

## API Reference

### Query Endpoint

```
GET /x402/query
Parameters:
  - q (required): Search query
  - depth (optional): "shallow" | "standard" | "deep"
  - format (optional): "json" | "markdown"
```

### Payment Status

```
GET /x402/payment/{query_id}
Returns:
  - status: "pending" | "verified" | "expired"
  - amount: payment amount
  - tx_signature: Solana transaction (if verified)
```

### Knowledge Domains

```
GET /x402/domains
Returns:
  - Available knowledge domains
  - Concept counts per domain
  - Pricing information
```

***

## Integration Examples

### Python Client

```python
import httpx
from solana.rpc.api import Client

async def query_atlas_x402(endpoint: str, query: str):
    # 1. Initial query
    response = await httpx.get(f"{endpoint}/x402/query", params={"q": query})
    
    if response.status_code == 402:
        payment_info = response.json()
        
        # 2. Send payment
        tx = await send_solana_payment(
            to=payment_info["payment_address"],
            amount=payment_info["amount"],
            memo=payment_info["memo"]
        )
        
        # 3. Poll for verification
        while True:
            status = await httpx.get(
                f"{endpoint}/x402/payment/{payment_info['memo']}"
            )
            if status.json()["status"] == "verified":
                break
            await asyncio.sleep(1)
        
        # 4. Retrieve results
        return await httpx.get(
            f"{endpoint}/x402/query",
            params={"q": query},
            headers={"X-Payment-Verified": payment_info["memo"]}
        )
    
    return response
```

### Agent Integration

AI agents using ATLAS can include x402 handling in their tool definitions:

```python
@tool
async def query_curated_knowledge(query: str) -> str:
    """Query verified human-curated knowledge via x402 protocol."""
    result = await query_atlas_x402(ATLAS_ENDPOINT, query)
    return result.json()
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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.atlas-ai.org/x402-protocol/how-it-works.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.
