# Access Tokens
Source: https://docs.xenarch.com/api-reference/access-tokens
Verify x402 access tokens issued after USDC payment — bearer token validation, expiration, and gate-scoped authorization for AI agents.
## Verify token
```
POST /v1/access-tokens/verify
```
Verify that an access token is valid for a specific site.
```bash theme={null}
curl -X POST https://xenarch.dev/v1/access-tokens/verify \
-H "X-Site-Token: st_abc123..." \
-H "Content-Type: application/json" \
-d '{"token": "eyJhbGciOiJIUzI1NiJ9..."}'
```
```json 200 theme={null}
{
"valid": true
}
```
## Token format
Access tokens are HMAC-SHA256 signed payloads: `base64url(payload).base64url(signature)`.
The payload contains:
* `gate_id` — the gate this token was issued for
* `site_id` — the site the gate belongs to
* `exp` — expiration timestamp (default: 30 minutes after issuance)
## Local verification
Publishers can verify tokens locally without calling the API. The Python SDK provides this:
```python theme={null}
from xenarch.token import verify_access_token
result = verify_access_token(
token="eyJhbGciOiJIUzI1NiJ9...",
site_id="your-site-uuid",
secret="your_access_token_secret",
)
if result:
print(f"Valid — gate: {result['gate_id']}")
else:
print("Invalid or expired")
```
The middleware (`XenarchMiddleware` and `require_payment` decorator) handles this automatically.
# Get Agent Profile
Source: https://docs.xenarch.com/api-reference/agents/get-profile
GET /v1/agents/me
Get the authenticated AI agent profile by wallet address — returns registration details, USDC balance, and x402 payment history summary.
```bash theme={null}
curl https://xenarch.dev/v1/agents/me \
-H "X-Wallet-Address: 0x1234...abcd"
```
## Notes
* Also available via `GET /v1/agents/wallet/{wallet_address}` (public lookup)
# Register Agent
Source: https://docs.xenarch.com/api-reference/agents/register
POST /v1/agents
Register an AI agent with Xenarch by wallet address — one-time registration for agents making USDC micropayments via the x402 protocol.
```bash theme={null}
curl -X POST https://xenarch.dev/v1/agents \
-H "Content-Type: application/json" \
-d '{"wallet_address": "0x1234...abcd", "name": "my-research-agent"}'
```
```json 201 theme={null}
{
"id": "c3d4e5f6-a7b8-9012-cdef-345678901234",
"wallet_address": "0x1234...abcd",
"name": "my-research-agent",
"created_at": "2026-04-10T14:00:00Z"
}
```
## Notes
* Registration is optional — agents can pay without registering
* Registering lets agents have a named profile and be discoverable
* `name` is optional
# Authentication
Source: https://docs.xenarch.com/api-reference/authentication
Xenarch API authentication — API key, site token, and wallet address auth methods for publishers and AI agents on the x402 payment API.
## Publisher API key
Used by publishers to manage their account, sites, and settings.
```bash theme={null}
curl https://xenarch.dev/v1/publishers/me \
-H "Authorization: Bearer xk_pub_abc123..."
```
* Prefix: `xk_pub_`
* Generated at registration and on login (key rotation)
* Stored as SHA-256 hash — the plaintext is returned once and cannot be retrieved
* Rotate via `POST /v1/publishers/me/api-key/rotate`
## Site token
Used by server middleware to create gates and verify access tokens.
```bash theme={null}
curl -X POST https://xenarch.dev/v1/gates \
-H "X-Site-Token: st_abc123..." \
-H "Content-Type: application/json" \
-d '{"url": "/premium-article"}'
```
* Prefix: `st_`
* Generated when a site is registered
* Stored as SHA-256 hash — the plaintext is returned once
* Scoped to a single site
## Wallet address
Used by agents to query their profile and payment history. No cryptographic proof required — used for lookup only.
```bash theme={null}
curl https://xenarch.dev/v1/agents/me \
-H "X-Wallet-Address: 0x1234...abcd"
```
* Must be a valid EVM address: `0x` followed by 40 hex characters
* No signature verification in MVP
# Create Gate
Source: https://docs.xenarch.com/api-reference/gates/create
POST /v1/gates
Create an x402 payment gate session — returns HTTP 402 with payment instructions. The core API call for charging AI agents for content access.
```bash theme={null}
curl -X POST https://xenarch.dev/v1/gates \
-H "X-Site-Token: st_abc123..." \
-H "Content-Type: application/json" \
-d '{"url": "/premium-article", "detection_method": "ua_match"}'
```
```json 402 theme={null}
{
"xenarch": true,
"gate_id": "7f3a1b2c-9d4e-4a8b-b6f1-2c3d4e5f6a7b",
"price_usd": "0.003",
"splitter": "0xC6D3a6B6fcCD6319432CDB72819cf317E88662ae",
"collector": "0xabc123...publisher_wallet",
"network": "base",
"asset": "USDC",
"protocol": "x402",
"verify_url": "https://xenarch.dev/v1/gates/7f3a1b2c.../verify",
"expires": "2026-04-10T15:00:00Z"
}
```
## Notes
* Returns HTTP 402 (Payment Required), not 200
* `collector` is the publisher's payout wallet address
* `splitter` is the Xenarch splitter contract address on Base
* Gates expire after 30 minutes by default (`GATE_TTL_SECONDS`)
* Price is resolved from path-specific rules or site default
* Origin/Referer header must match the registered site domain
# Get Domain Gate
Source: https://docs.xenarch.com/api-reference/gates/get-domain
GET /v1/gates/domain/{domain}
Get active x402 gate configuration for a domain — returns pay-per-crawl pricing rules, payment gate settings, and publisher access controls.
```bash theme={null}
curl https://xenarch.dev/v1/gates/domain/example.com
```
## Notes
* Public endpoint for agent discovery
* Returns the gate configuration if the domain has active gating
* Alternative to checking via HTTP 402 — useful when agents want to discover pricing without making a request to the publisher's server
# Get Gate Status
Source: https://docs.xenarch.com/api-reference/gates/get-status
GET /v1/gates/{gate_id}
Check the status of an x402 payment gate — verify if payment required, received, or an access token has already been issued for this gate.
```bash theme={null}
curl https://xenarch.dev/v1/gates/7f3a1b2c-9d4e-4a8b-b6f1-2c3d4e5f6a7b
```
```json 200 theme={null}
{
"gate_id": "7f3a1b2c-9d4e-4a8b-b6f1-2c3d4e5f6a7b",
"status": "pending",
"price_usd": "0.003",
"created_at": "2026-04-10T14:30:00Z",
"paid_at": null
}
```
## Notes
* Public endpoint — no authentication required (gate IDs are UUIDs, unguessable)
* Status values: `pending`, `paid`, `expired`
* Expired gates return status `expired` (auto-detected when `expires_at` has passed)
# Verify Payment
Source: https://docs.xenarch.com/api-reference/gates/verify-payment
POST /v1/gates/{gate_id}/verify
Submit an on-chain transaction hash to verify x402 USDC payment on Base and receive a time-limited bearer access token for gated content.
```bash theme={null}
curl -X POST https://xenarch.dev/v1/gates/7f3a1b2c.../verify \
-H "Content-Type: application/json" \
-d '{"tx_hash": "0xdef456...abc789"}'
```
```json 200 theme={null}
{
"access_token": "eyJhbGciOiJIUzI1NiJ9...",
"expires_at": "2026-04-10T15:05:00Z"
}
```
## Verification process
1. Fetches the transaction receipt from Base RPC
2. Confirms the transaction was sent to the splitter contract and succeeded
3. Parses the `Split` event logs
4. Verifies the collector matches the publisher's registered wallet
5. Verifies the amount meets or exceeds the gate price
6. Creates a `VerifiedPayment` record
7. Returns an HMAC-SHA256 access token
## Notes
* **Idempotent**: submitting the same `tx_hash` again returns the cached token
* **Replay-safe**: a `tx_hash` used for one gate cannot be reused for another
* Gate must be `pending` and not expired
* Access tokens expire after 30 minutes by default
# API Overview
Source: https://docs.xenarch.com/api-reference/overview
x402 REST API reference — payment gates, USDC micropayments on Base, publisher registration, and AI agent management. Complete x402 API docs.
## Base URL
```
https://xenarch.dev/v1
```
All endpoints are prefixed with `/v1`. The API returns JSON responses.
## Authentication
Three authentication methods depending on the caller:
| Method | Header | Format | Used by |
| ----------------- | ------------------ | ------------------- | -------------------------------- |
| Publisher API key | `Authorization` | `Bearer xk_pub_...` | Publishers managing sites |
| Site token | `X-Site-Token` | `st_...` | Server middleware creating gates |
| Wallet address | `X-Wallet-Address` | `0x...` | Agents querying profiles |
See [Authentication](/api-reference/authentication) for details.
## Rate limits
| Endpoint | Limit | Scope |
| ------------------------------ | ------- | -------------- |
| `POST /v1/publishers/register` | 5/min | Per IP |
| `POST /v1/publishers/login` | 5/min | Per IP |
| `POST /v1/gates` | 200/min | Per site token |
| `POST /v1/gates/{id}/verify` | 50/min | Per gate |
| All other endpoints | 100/min | Per credential |
Rate-limited responses return HTTP 429 with a `Retry-After` header.
## Error format
```json theme={null}
{
"detail": "Gate not found or expired"
}
```
All errors include a `detail` field with a human-readable message.
## Common status codes
| Code | Meaning |
| ---- | -------------------------------- |
| 200 | Success |
| 201 | Created |
| 400 | Bad request (validation error) |
| 401 | Invalid or missing credentials |
| 402 | Payment required (gate response) |
| 404 | Resource not found |
| 409 | Conflict (duplicate resource) |
| 429 | Rate limited |
| 500 | Server error |
# Payment History
Source: https://docs.xenarch.com/api-reference/payments/history
GET /v1/payments/history
Get x402 payment history for a wallet address — paginated USDC transactions on Base with gate URLs, amounts, and timestamps per payment.
```bash theme={null}
curl "https://xenarch.dev/v1/payments/history?wallet=0x1234...abcd&domain=example.com&limit=10"
```
```json 200 theme={null}
[
{
"url": "/premium-article",
"domain": "example.com",
"amount_usd": "0.003",
"tx_hash": "0xdef456...abc789",
"paid_at": "2026-04-10T14:35:00Z"
}
]
```
## Query parameters
| Parameter | Type | Description |
| --------- | ------- | --------------------------- |
| `wallet` | string | Wallet address (required) |
| `domain` | string | Filter by domain (optional) |
| `limit` | integer | Max results (default 10) |
# Get Profile
Source: https://docs.xenarch.com/api-reference/publishers/get-profile
GET /v1/publishers/me
Get the authenticated Xenarch publisher profile — returns publisher details, payout wallet, registered sites, and x402 pay-per-crawl configuration.
```bash theme={null}
curl https://xenarch.dev/v1/publishers/me \
-H "Authorization: Bearer xk_pub_abc123..."
```
## Notes
* Returns publisher profile including email, payout wallet, and email verification status
* Requires publisher API key authentication
# Login
Source: https://docs.xenarch.com/api-reference/publishers/login
POST /v1/publishers/login
Authenticate as a Xenarch publisher and rotate API key — receive a new key that invalidates the previous one. Rate-limited 5 requests per minute per IP.
```bash theme={null}
curl -X POST https://xenarch.dev/v1/publishers/login \
-H "Content-Type: application/json" \
-d '{"email": "publisher@example.com", "password": "secure_password"}'
```
```json 200 theme={null}
{
"api_key": "xk_pub_new_key..."
}
```
## Notes
* **Rotates the API key** — the previous key is invalidated immediately
* Rate limited: 5 requests/min per IP, 5 attempts then 15-minute lockout
# Register Publisher
Source: https://docs.xenarch.com/api-reference/publishers/register
POST /v1/publishers
Create a new Xenarch publisher account — the entry point for charging AI bots with x402 USDC micropayments and setting pay-per-crawl pricing.
```bash theme={null}
curl -X POST https://xenarch.dev/v1/publishers \
-H "Content-Type: application/json" \
-d '{"email": "publisher@example.com", "password": "secure_password"}'
```
```json 201 theme={null}
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"api_key": "xk_pub_abc123..."
}
```
## Notes
* **Save the `api_key`** — it is returned once and stored as a SHA-256 hash. It cannot be retrieved later.
* Rate limited: 5 requests/min per IP
* Email does not require verification to use the API (verification is optional)
# Update Payout Wallet
Source: https://docs.xenarch.com/api-reference/publishers/update-payout
PUT /v1/publishers/me/payout
Update the publisher's USDC payout wallet address — all future x402 pay-per-crawl payments for this publisher will route to the new wallet on Base.
```bash theme={null}
curl -X PUT https://xenarch.dev/v1/publishers/me/payout \
-H "Authorization: Bearer xk_pub_abc123..." \
-H "Content-Type: application/json" \
-d '{"payout_wallet": "0xnew_wallet_address..."}'
```
## Notes
* Wallet changes may have a 48-hour delay before activation (security measure)
* The pending wallet is stored in `payout_wallet_pending` until the delay passes
* Cancel a pending change via `POST /v1/publishers/me/payout/cancel`
# Create Service
Source: https://docs.xenarch.com/api-reference/services/create
POST /v1/services
Register a discoverable x402 service on Xenarch — make your API or data accessible to AI agents with machine-readable pricing and USDC gates.
```bash theme={null}
curl -X POST https://xenarch.dev/v1/services \
-H "Authorization: Bearer xk_pub_abc123..." \
-H "Content-Type: application/json" \
-d '{
"name": "Premium News API",
"url": "https://example.com/api",
"description": "Real-time news articles with full text",
"price_per_request": "0.05",
"category": "api",
"pay_json_url": "https://example.com/.well-known/pay.json"
}'
```
## Categories
| Value | Description |
| --------- | --------------------------------- |
| `api` | REST or GraphQL API |
| `docs` | Documentation or knowledge base |
| `data` | Data feeds or datasets |
| `content` | Articles, media, or other content |
# List Services
Source: https://docs.xenarch.com/api-reference/services/list
GET /v1/services
List all active x402 services on Xenarch — a discovery endpoint for AI agents looking for paid APIs, data feeds, and content services.
```bash theme={null}
curl "https://xenarch.dev/v1/services?limit=20&offset=0"
```
## Notes
* Public endpoint — no authentication required
* Returns only active services (`is_active = true`)
* Paginated with `limit` and `offset` query parameters
# Search Services
Source: https://docs.xenarch.com/api-reference/services/search
GET /v1/services/search
Search x402 services by category, keyword, or price range — agent-facing discovery endpoint for finding paid APIs and gated content.
```bash theme={null}
curl "https://xenarch.dev/v1/services/search?category=api&q=news&min_price=0.01&max_price=0.10"
```
## Query parameters
| Parameter | Type | Description |
| ----------- | ------- | ---------------------------------------------------- |
| `category` | string | Filter by category: `api`, `docs`, `data`, `content` |
| `q` | string | Keyword search in name and description |
| `min_price` | decimal | Minimum price per request |
| `max_price` | decimal | Maximum price per request |
| `limit` | integer | Max results (default 20) |
| `offset` | integer | Pagination offset |
# Create Site
Source: https://docs.xenarch.com/api-reference/sites/create
POST /v1/sites
Register a new site (domain) under the publisher account — first step to enable x402 pay-per-crawl with USDC micropayments for AI agents.
```bash theme={null}
curl -X POST https://xenarch.dev/v1/sites \
-H "Authorization: Bearer xk_pub_abc123..." \
-H "Content-Type: application/json" \
-d '{"domain": "example.com"}'
```
```json 201 theme={null}
{
"id": "b2c3d4e5-f6a7-8901-bcde-f23456789012",
"site_token": "st_xyz789..."
}
```
## Notes
* **Save the `site_token`** — it is returned once and stored as a SHA-256 hash
* Domain must be unique across all publishers
* The site token is used by your middleware to create gates
# Get Stats
Source: https://docs.xenarch.com/api-reference/sites/get-stats
GET /v1/sites/{site_id}/stats
Revenue analytics for a Xenarch publisher site — top pages, top paying agents, and time-bucketed USDC earnings from x402 pay-per-crawl.
```bash theme={null}
# Overview stats
curl https://xenarch.dev/v1/sites/b2c3d4e5.../stats \
-H "Authorization: Bearer xk_pub_abc123..."
# Time-bucketed stats
curl "https://xenarch.dev/v1/sites/b2c3d4e5.../stats?bucketed=true" \
-H "Authorization: Bearer xk_pub_abc123..."
```
## Notes
* Default view returns top pages and top agents by revenue
* Add `?bucketed=true` for time-bucketed stats (today, this month, all time)
# Get Transactions
Source: https://docs.xenarch.com/api-reference/sites/get-transactions
GET /v1/sites/{site_id}/transactions
Paginated x402 USDC transaction history for a publisher site — agent wallet, amount, timestamp, and gate URL per on-chain transaction.
```bash theme={null}
curl "https://xenarch.dev/v1/sites/b2c3d4e5.../transactions?period=7d&status=paid&page=1&per_page=20" \
-H "Authorization: Bearer xk_pub_abc123..."
```
## Query parameters
| Parameter | Values | Default |
| ---------- | ------------------------------------ | ------- |
| `period` | `24h`, `7d`, `30d`, `all` | `all` |
| `status` | `paid`, `blocked`, `withdraw`, `all` | `all` |
| `page` | Integer | `1` |
| `per_page` | Integer | `20` |
# List Sites
Source: https://docs.xenarch.com/api-reference/sites/list
GET /v1/sites
List all sites belonging to the authenticated Xenarch publisher — returns domain, pay-per-crawl pricing rules, and revenue summary per site.
```bash theme={null}
curl https://xenarch.dev/v1/sites \
-H "Authorization: Bearer xk_pub_abc123..."
```
# Update Pricing
Source: https://docs.xenarch.com/api-reference/sites/update-pricing
PUT /v1/sites/{site_id}/pricing
Update x402 pay-per-crawl pricing for a site — set the default USDC price and path-specific pricing rules for AI agent content access.
```bash theme={null}
curl -X PUT https://xenarch.dev/v1/sites/b2c3d4e5.../pricing \
-H "Authorization: Bearer xk_pub_abc123..." \
-H "Content-Type: application/json" \
-d '{
"default_price_usd": "0.003",
"rules": [
{"path_pattern": "/premium/*", "price_usd": "0.01"},
{"path_pattern": "/api/*", "price_usd": "0.05"},
{"path_pattern": "/public/*", "price_usd": "0"}
]
}'
```
## Notes
* `path_pattern` uses fnmatch-style globs: `*` matches a single segment, `**` is not supported at the API level
* Rules are evaluated in order — first match wins
* A price of `"0"` makes the path free for bots
* Replaces all existing rules for the site
# Smart Contract
Source: https://docs.xenarch.com/contract/overview
XenarchSplitter smart contract — non-custodial USDC payment splitter on Base L2 for x402 micropayments. Verifiable on Basescan, 0% fee.
The XenarchSplitter is a minimal Solidity contract that splits incoming USDC payments between content publishers and the Xenarch treasury. It is the single settlement mechanism for all Xenarch payments.
## Deployments
| Network | Address | USDC |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| **Base Mainnet** | [`0xC6D3a6B6fcCD6319432CDB72819cf317E88662ae`](https://basescan.org/address/0xC6D3a6B6fcCD6319432CDB72819cf317E88662ae) | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` |
| **Base Sepolia** | [`0x7ecfe8f83eab6ba170063d1f1fe7c33695a9ce1d`](https://sepolia.basescan.org/address/0x7ecfe8f83eab6ba170063d1f1fe7c33695a9ce1d) | `0xc5aDdd66Da733101A5468857Aa3C6689Af9d1DDc` (mock) |
Both contracts are verified on Basescan.
## How it works
1. Agent approves USDC on the splitter contract
2. Agent calls `split(collector, amount)` where `collector` is the publisher's wallet
3. Contract calculates fee: `fee = (amount * feeBps) / 10_000`
4. Contract transfers `amount - fee` to publisher, `fee` to treasury
5. Contract emits a `Split` event with payer, collector, amount, and fee
## Key properties
| Property | Value |
| --------------- | ---------------------------------------------------------- |
| **Fee** | 0% (currently), capped at 0.99% forever |
| **Max payment** | \$1.00 (1,000,000 USDC satoshis) |
| **Min payment** | \$0.000001 (1 USDC satoshi) |
| **Fee cap** | `MAX_FEE_BPS = 99` — immutable constant, cannot be changed |
| **Pausable** | Owner can pause splits for emergencies |
| **USDC only** | Hardcoded to USDC on Base |
## Security
* **Immutable fee cap**: The `MAX_FEE_BPS` constant cannot be changed after deployment. Publishers are guaranteed fees will never exceed 0.99%.
* **SafeERC20**: Uses OpenZeppelin's SafeERC20 for all USDC transfers.
* **No reentrancy risk**: No external calls before state changes.
* **Verified source**: Bytecode published and verified on Basescan.
* **Minimal surface**: 57 lines of Solidity. Single responsibility.
## Building from source
```bash theme={null}
# Install Foundry
curl -L https://foundry.paradigm.xyz | bash
foundryup
# Clone and build
git clone https://github.com/xenarch-ai/xenarch-contract
cd xenarch-contract
forge build
# Run tests
forge test -vvv
```
# Contract Reference
Source: https://docs.xenarch.com/contract/reference
XenarchSplitter Solidity interface — functions, events, and constants for the non-custodial x402 USDC payment splitter contract on Base L2.
## Constructor
```solidity theme={null}
constructor(address _usdc, address _treasury)
```
| Parameter | Description |
| ----------- | ---------------------------------- |
| `_usdc` | USDC token address |
| `_treasury` | Treasury wallet for fee collection |
Sets `owner` to `msg.sender`. Fee starts at 0%.
## Functions
### split
```solidity theme={null}
function split(address collector, uint256 amount) external
```
Split a USDC payment between the publisher (`collector`) and treasury.
| Parameter | Type | Description |
| ----------- | ------- | ------------------------------------ |
| `collector` | address | Publisher's wallet address |
| `amount` | uint256 | USDC amount in satoshis (6 decimals) |
**Requirements:**
* Not paused
* `amount` between 1 and 1,000,000 (inclusive)
* Caller has approved sufficient USDC on the splitter
**Behavior:**
* Transfers `amount - fee` to `collector`
* Transfers `fee` to treasury (if fee > 0)
* Emits `Split` event
### setFee
```solidity theme={null}
function setFee(uint256 _newFeeBps) external
```
Update the fee in basis points. Owner only.
| Parameter | Type | Description |
| ------------ | ------- | -------------------------------- |
| `_newFeeBps` | uint256 | New fee in basis points (max 99) |
### setTreasury
```solidity theme={null}
function setTreasury(address _newTreasury) external
```
Update the treasury address. Owner only.
### setPaused
```solidity theme={null}
function setPaused(bool _paused) external
```
Pause or unpause the contract. Owner only.
## Events
### Split
```solidity theme={null}
event Split(
address indexed payer,
address indexed collector,
uint256 amount,
uint256 fee
)
```
Emitted on every successful `split()` call.
| Field | Description |
| ----------- | ------------------------------------------ |
| `payer` | Agent wallet that sent the payment |
| `collector` | Publisher wallet that received the payment |
| `amount` | Gross USDC amount (satoshis) |
| `fee` | Fee deducted (satoshis) |
## Constants
```solidity theme={null}
uint256 public constant MAX_FEE_BPS = 99; // 0.99% — immutable
```
## State variables
| Variable | Type | Description |
| ---------- | ------------------ | --------------------------- |
| `owner` | address | Contract owner |
| `treasury` | address | Fee collection wallet |
| `usdc` | IERC20 (immutable) | USDC token |
| `paused` | bool | Pause flag |
| `feeBps` | uint256 | Current fee in basis points |
## ABI (human-readable)
```typescript theme={null}
const SPLITTER_ABI = [
"function split(address collector, uint256 amount) external",
"function setFee(uint256 _newFeeBps) external",
"function setTreasury(address _newTreasury) external",
"function setPaused(bool _paused) external",
"function owner() view returns (address)",
"function treasury() view returns (address)",
"function feeBps() view returns (uint256)",
"function paused() view returns (bool)",
"function MAX_FEE_BPS() view returns (uint256)",
"event Split(address indexed payer, address indexed collector, uint256 amount, uint256 fee)",
];
```
## Fee calculation
```
fee = (amount * feeBps) / 10_000
net = amount - fee
```
**Examples** (at 99 bps / 0.99%):
| Amount (USD) | USDC units | Fee | Net |
| ------------ | ---------- | ----- | ------- |
| \$0.003 | 3,000 | 29 | 2,971 |
| \$0.01 | 10,000 | 99 | 9,901 |
| \$0.10 | 100,000 | 990 | 99,010 |
| \$1.00 | 1,000,000 | 9,900 | 990,100 |
At the current fee of 0%, all amounts go directly to the publisher.
# CrewAI Agent
Source: https://docs.xenarch.com/examples/crewai-agent
CrewAI agent example — a research crew that pays for x402-gated content with USDC micropayments on Base using Xenarch payment tools.
A CrewAI crew with a specialized Research Agent role that handles Xenarch payments autonomously.
## Setup
```bash theme={null}
pip install xenarch[agent,crewai] crewai>=0.80.0 python-dotenv
```
Create `.env`:
```bash theme={null}
XENARCH_PRIVATE_KEY=0xYOUR_PRIVATE_KEY
OPENAI_API_KEY=sk-...
```
## Code
```python main.py theme={null}
"""CrewAI crew with Xenarch payment tools."""
from dotenv import load_dotenv
from crewai import Agent, Crew, Task
from xenarch.tools.crewai import check_gate, get_history, pay
load_dotenv()
researcher = Agent(
role="Research Agent",
goal="Access and summarize gated web content by paying for it when needed",
backstory=(
"You are a research agent that can pay for gated content using "
"Xenarch micropayments. When you encounter a payment gate, you "
"check the price, pay with USDC on Base, and use the access token "
"to retrieve the content."
),
tools=[check_gate, pay, get_history],
verbose=True,
)
task = Task(
description=(
"Check if https://gate.xenarch.dev/hello-world/ has a Xenarch payment gate. "
"If it does, pay for access and report what you found."
),
expected_output="A summary of the gate status and any payment made.",
agent=researcher,
)
crew = Crew(agents=[researcher], tasks=[task], verbose=True)
if __name__ == "__main__":
result = crew.kickoff()
print(result)
```
## Run
```bash theme={null}
python main.py
```
# FastAPI Publisher
Source: https://docs.xenarch.com/examples/fastapi-publisher
FastAPI publisher example — gate AI agents behind x402 USDC payments in a FastAPI app with pay-per-crawl middleware and bot detection.
Shows both integration patterns: site-wide middleware and per-route decorator.
## Setup
```bash theme={null}
pip install xenarch[fastapi] fastapi>=0.115.0 uvicorn>=0.30.0 python-dotenv
```
Create `.env`:
```bash theme={null}
XENARCH_SITE_TOKEN=st_your_site_token
XENARCH_SITE_ID=your-site-uuid
XENARCH_ACCESS_TOKEN_SECRET=your_secret
```
## Code
```python main.py theme={null}
"""FastAPI publisher — gate AI agents behind Xenarch payments."""
import os
from dotenv import load_dotenv
from fastapi import FastAPI, Request
from xenarch.decorator import require_payment
from xenarch.middleware import XenarchMiddleware
load_dotenv()
SITE_TOKEN = os.environ["XENARCH_SITE_TOKEN"]
SITE_ID = os.environ["XENARCH_SITE_ID"]
ACCESS_TOKEN_SECRET = os.environ["XENARCH_ACCESS_TOKEN_SECRET"]
app = FastAPI(title="Xenarch Publisher Example")
# Pattern 1: Site-wide middleware
app.add_middleware(
XenarchMiddleware,
site_token=SITE_TOKEN,
site_id=SITE_ID,
access_token_secret=ACCESS_TOKEN_SECRET,
excluded_paths={"/healthz", "/docs", "/openapi.json", "/"},
)
# Pattern 2: Per-route decorator
gate = require_payment(
site_token=SITE_TOKEN,
site_id=SITE_ID,
access_token_secret=ACCESS_TOKEN_SECRET,
)
@app.get("/")
async def home():
"""Free — not gated."""
return {"message": "Welcome! This content is free for everyone."}
@app.get("/healthz")
async def health():
"""Excluded from gating."""
return {"status": "ok"}
@app.get("/articles")
async def articles():
"""Gated by site-wide middleware."""
return {
"articles": [
{"title": "Understanding AI Payments", "id": 1},
{"title": "Micropayments at Scale", "id": 2},
]
}
@app.get("/premium")
@gate
async def premium(request: Request):
"""Gated by per-route decorator."""
return {"content": "This is premium content worth paying for."}
```
## Run
```bash theme={null}
uvicorn main:app --reload
```
## Test
```bash theme={null}
# Human request — passes through
curl http://localhost:8000/
# Bot without token — returns 402
curl -H "User-Agent: GPTBot/1.0" http://localhost:8000/articles
# Bot with valid token — passes through
curl -H "User-Agent: GPTBot/1.0" \
-H "Authorization: Bearer " \
http://localhost:8000/articles
```
## Response examples
**Free route:**
```json theme={null}
{"message": "Welcome! This content is free for everyone."}
```
**Bot without token (402):**
```json theme={null}
{
"xenarch": true,
"gate_id": "...",
"price_usd": "0.003",
"splitter": "0xC6D3...",
"collector": "0xabc1...",
"network": "base",
"asset": "USDC",
"protocol": "x402",
"verify_url": "https://xenarch.dev/v1/gates/.../verify"
}
```
**Bot with valid token:**
```json theme={null}
{"content": "This is premium content worth paying for."}
```
# LangChain Agent
Source: https://docs.xenarch.com/examples/langchain-agent
Autonomous LangChain agent example — uses Xenarch payment tools to pay for x402-gated content with USDC micropayments on Base.
A LangChain ReAct agent that autonomously decides when to check gates, pay for content, and review payment history.
## Setup
```bash theme={null}
pip install xenarch[agent,langchain] langchain>=0.3.0 langchain-openai>=0.3.0 python-dotenv
```
Create `.env`:
```bash theme={null}
XENARCH_PRIVATE_KEY=0xYOUR_PRIVATE_KEY
OPENAI_API_KEY=sk-...
```
## Code
```python main.py theme={null}
"""LangChain agent with Xenarch payment tools."""
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from xenarch.tools.langchain import CheckGateTool, GetHistoryTool, PayTool
load_dotenv()
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
tools = [CheckGateTool(), PayTool(), GetHistoryTool()]
agent = create_react_agent(
llm,
tools,
prompt=(
"You are a helpful assistant with access to Xenarch payment tools. "
"You can check if URLs have payment gates, pay for gated content "
"using USDC micropayments on Base, and review payment history. "
"When asked to access gated content, check the gate first, then pay if needed."
),
)
if __name__ == "__main__":
result = agent.invoke(
{"messages": [{"role": "user", "content": "Check if https://gate.xenarch.dev/sample-page/ has a paywall. If it does, pay for access."}]}
)
for msg in result["messages"]:
print(f"[{msg.type}] {msg.content if isinstance(msg.content, str) else msg.content}")
```
## Run
```bash theme={null}
python main.py
```
## Using other LLMs
Swap the LLM by changing the import:
```python theme={null}
# Anthropic Claude
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(model="claude-sonnet-4-20250514")
# Local model via Ollama
from langchain_community.llms import Ollama
llm = Ollama(model="llama3")
```
# MCP (Claude Desktop & Code)
Source: https://docs.xenarch.com/examples/mcp-claude
Claude Desktop MCP example — add Xenarch x402 payment tools to Claude with zero code. Auto-checks payment gates and pays in USDC on Base.
Configuration-only setup. No code to write.
## Claude Code
```bash theme={null}
claude mcp add xenarch -- npx @xenarch/agent-mcp
```
Done. The three Xenarch tools are now available.
## Claude Desktop
Edit your config file:
```
~/Library/Application Support/Claude/claude_desktop_config.json
```
```
%APPDATA%\Claude\claude_desktop_config.json
```
Add the Xenarch server:
```json theme={null}
{
"mcpServers": {
"xenarch": {
"command": "npx",
"args": ["@xenarch/agent-mcp"],
"env": {
"XENARCH_PRIVATE_KEY": "0xYOUR_PRIVATE_KEY"
}
}
}
}
```
Restart Claude Desktop.
## Test it
Try these prompts:
* "Check if example.com has a Xenarch payment gate"
* "Pay for access to example.com and show me the content"
* "Show my Xenarch payment history"
## Testnet
For testing without real funds:
```json theme={null}
{
"mcpServers": {
"xenarch": {
"command": "npx",
"args": ["@xenarch/agent-mcp"],
"env": {
"XENARCH_PRIVATE_KEY": "0xYOUR_PRIVATE_KEY",
"XENARCH_NETWORK": "base-sepolia",
"XENARCH_RPC_URL": "https://sepolia.base.org"
}
}
}
}
```
## Troubleshooting
| Issue | Fix |
| ---------------------- | ------------------------------------------------------------------------------------- |
| Tools not appearing | Restart Claude Desktop. Run `npx @xenarch/agent-mcp` in terminal to check for errors. |
| "No wallet configured" | Set `XENARCH_PRIVATE_KEY` in the env block or create `~/.xenarch/wallet.json`. |
| "Insufficient USDC" | Fund your wallet with USDC on Base. Need \~\$0.01 ETH for gas too. |
# Examples
Source: https://docs.xenarch.com/examples/overview
Working x402 code examples — Python agents, LangChain, CrewAI, MCP with Claude Desktop, FastAPI publishers. Copy-paste ready for USDC micropayments.
Complete, runnable examples for every integration pattern. Each example follows the same setup:
```bash theme={null}
cd
pip install -r requirements.txt
cp .env.example .env # edit with your keys
python main.py
```
## For agents
Minimal agent: check gate, pay USDC, fetch content. No framework.
ReAct agent with autonomous payment decisions.
Multi-agent crew with specialized research agent.
Zero-code setup for Claude Desktop and Claude Code.
## For publishers
Server-side gating with middleware and per-route decorator.
## Prerequisites
* Python 3.10+
* A funded wallet on Base (USDC + small ETH for gas)
* For testnet: use `base-sepolia` network with mock USDC
Source code: [github.com/xenarch-ai/xenarch-examples](https://github.com/xenarch-ai/xenarch-examples)
# Python Agent
Source: https://docs.xenarch.com/examples/python-agent
Minimal Python x402 agent example — check the payment gate, pay a USDC micropayment on Base, and fetch gated content. Copy-paste ready.
The simplest possible Xenarch agent. No frameworks, no abstractions — raw SDK calls showing the complete payment flow.
## Setup
```bash theme={null}
pip install xenarch[agent] python-dotenv httpx
```
Create `.env`:
```bash theme={null}
XENARCH_PRIVATE_KEY=0xYOUR_PRIVATE_KEY
```
## Code
```python main.py theme={null}
"""Minimal Xenarch agent: check gate, pay, get content."""
import sys
import httpx
from dotenv import load_dotenv
from xenarch.agent_client import check_gate, verify_payment
from xenarch.payment import execute_payment
from xenarch.wallet import load_wallet_or_create
load_dotenv()
def main(url: str) -> None:
wallet = load_wallet_or_create()
print(f"Wallet: {wallet.address}")
print(f"Network: {wallet.network}\n")
# 1. Check if the URL has a payment gate
print(f"Checking gate for: {url}")
gate = check_gate(url)
if not gate:
print("No Xenarch gate found — content is free.")
return
print(f"Gate found! Price: ${gate.price_usd} ({gate.asset} on {gate.network})\n")
# 2. Execute on-chain USDC payment
print("Executing payment...")
result = execute_payment(
wallet=wallet,
splitter_address=gate.splitter,
collector_address=gate.collector,
price_usd=gate.price_usd,
)
print(f"Payment confirmed!")
print(f" TX: {result.tx_hash}")
print(f" Block: {result.block_number}\n")
# 3. Verify payment and get access token
print("Verifying payment...")
verification = verify_payment(gate.verify_url, result.tx_hash)
access_token = verification["access_token"]
expires_at = verification["expires_at"]
print(f"Access token received (expires: {expires_at})\n")
# 4. Fetch the gated content with the access token
print("Fetching gated content...")
resp = httpx.get(
url,
headers={
"Authorization": f"Bearer {access_token}",
"User-Agent": "xenarch-example/1.0",
},
)
print(f"Content retrieved successfully ({len(resp.content):,} bytes)")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python main.py ")
sys.exit(1)
main(sys.argv[1])
```
## Run
```bash theme={null}
python main.py https://example.com/premium-article
```
## Output
```
Wallet: 0x1234...abcd
Network: base
Checking gate for: https://example.com/premium-article
Gate found! Price: $0.003 (USDC on base)
Executing payment...
Payment confirmed!
TX: 0xabc123...
Block: 28451023
Verifying payment...
Access token received (expires: 2026-04-10T15:05:00Z)
Fetching gated content...
Content retrieved successfully (1,234 bytes)
```
## What each step does
1. **`load_wallet_or_create()`** — loads your private key from env or `~/.xenarch/wallet.json`. Creates a new wallet on first run.
2. **`check_gate(url)`** — makes an HTTP request to the URL. If the server returns 402, parses the gate details.
3. **`execute_payment()`** — approves USDC and calls `split()` on the splitter contract. Waits for on-chain confirmation.
4. **`verify_payment()`** — submits the tx hash to Xenarch. Returns a time-limited access token.
5. **Content fetch** — re-requests the URL with the Bearer token. Server validates locally and returns content.
# How It Works
Source: https://docs.xenarch.com/how-it-works
How x402 resolves HTTP 402 — complete AI agent payment flow from 402 status code detection to USDC settlement on Base L2. x402 protocol guide.
## The x402 protocol
x402 uses HTTP status code `402 Payment Required` to signal that content requires payment. When an AI agent hits a gated URL, the server returns a 402 response with payment instructions instead of content.
## Payment flow
An AI agent requests a URL. The server detects the bot (via User-Agent), calls the Xenarch API to create a payment gate, and returns HTTP 402 with gate details: price, splitter contract address, publisher wallet, and a verify URL.
The agent approves USDC and calls `split(collector, amount)` on the Xenarch splitter contract. The contract transfers USDC directly to the publisher wallet (minus any platform fee). A `Split` event is emitted on-chain.
The agent sends the transaction hash to the verify endpoint. Xenarch fetches the tx receipt from Base, parses the `Split` event, confirms the amount and recipient match, and returns a time-limited HMAC access token.
The agent re-requests the URL with `Authorization: Bearer `. The server validates the token locally (no API call needed) and returns the content.
## What each party does
### Publisher (server-side)
1. Register on Xenarch, add your site, set pricing
2. Install middleware (Python SDK, WordPress plugin, or Cloudflare Worker)
3. Middleware handles bot detection, gate creation, and token verification automatically
### Agent (client-side)
1. Request a URL, receive HTTP 402
2. Parse the 402 response for payment details
3. Send USDC on Base via the splitter contract
4. Submit tx hash, receive access token
5. Re-request with the token
Or use the SDK/MCP server and the flow is handled automatically.
## Architecture
```
┌─────────┐ HTTP 402 ┌──────────────┐
│ Agent │ ───────────────→ │ Publisher │
│ │ ←─────────────── │ (middleware) │
│ │ └──────┬───────┘
│ │ │ create gate
│ │ ┌──────▼───────┐
│ │ │ Xenarch │
│ │ │ Platform │
│ │ └──────────────┘
│ │
│ │ USDC transfer ┌──────────────┐
│ │ ────────────────→ │ Splitter │
│ │ │ Contract │
│ │ └──────┬───────┘
│ │ │ split to publisher
│ │ ┌──────▼───────┐
│ │ │ Publisher │
│ │ │ Wallet │
│ │ └──────────────┘
│ │
│ │ verify tx_hash ┌──────────────┐
│ │ ────────────────→ │ Xenarch │
│ │ ←──────────────── │ Platform │
│ │ access_token └──────────────┘
└─────────┘
```
## Security model
* **Non-custodial**: Xenarch never holds funds. USDC goes directly from agent to publisher via the splitter contract.
* **On-chain verification**: Every payment is verifiable on Basescan. No trust required.
* **Immutable fee cap**: The splitter contract has a `MAX_FEE_BPS = 99` constant (0.99%) that cannot be changed after deployment.
* **Replay protection**: Each transaction hash can only be used once per gate. Duplicate submissions return the cached token.
* **Token expiry**: Access tokens expire after 120 minutes by default. Tokens are HMAC-signed and verified locally by the publisher's middleware — no API call needed.
# CrewAI
Source: https://docs.xenarch.com/integrations/crewai
CrewAI payment tools — let CrewAI crews pay for x402-gated content with USDC micropayments on Base. MCP-compatible drop-in tools.
## Installation
```bash theme={null}
pip install xenarch[agent,crewai]
```
Requires `crewai>=0.80.0`.
## Tools
The SDK provides three CrewAI tool functions:
```python theme={null}
from xenarch.tools.crewai import check_gate, pay, get_history
```
| Tool | Description |
| ------------- | -------------------------------------------- |
| `check_gate` | Check if a URL has an x402 payment gate |
| `pay` | Execute USDC payment and return access token |
| `get_history` | View past payments for this wallet |
## Usage
```python theme={null}
from dotenv import load_dotenv
from crewai import Agent, Crew, Task
from xenarch.tools.crewai import check_gate, pay, get_history
load_dotenv()
researcher = Agent(
role="Research Agent",
goal="Access gated web content by paying when needed",
backstory=(
"You are a research agent that pays for gated content using "
"Xenarch micropayments when you encounter payment gates."
),
tools=[check_gate, pay, get_history],
verbose=True,
)
task = Task(
description=(
"Check if https://example.com has a payment gate. "
"If it does, pay for access and report what you found."
),
expected_output="Gate status and payment result.",
agent=researcher,
)
crew = Crew(agents=[researcher], tasks=[task], verbose=True)
result = crew.kickoff()
print(result)
```
## Wallet configuration
Same as the core SDK — see [Agent Quickstart](/quickstart-agent).
## Full example
See the [CrewAI agent example](/examples/crewai-agent) for a complete working script.
# FastAPI Middleware
Source: https://docs.xenarch.com/integrations/fastapi-middleware
FastAPI payment middleware — gate AI agents behind x402 USDC micropayments on Base. ASGI-compatible, drop-in pay-per-crawl for Python APIs.
## Installation
```bash theme={null}
pip install xenarch[fastapi]
```
## Prerequisites
* A Xenarch publisher account
* A registered site with site token and site ID
* Your access token secret (from site registration)
## Pattern 1: Site-wide middleware
Gates all bot traffic across your application:
```python theme={null}
from fastapi import FastAPI
from xenarch.middleware import XenarchMiddleware
app = FastAPI()
app.add_middleware(
XenarchMiddleware,
site_token="st_...",
site_id="your-site-uuid",
access_token_secret="your_secret",
excluded_paths={"/healthz", "/docs", "/openapi.json"},
)
@app.get("/articles")
async def articles():
return {"articles": [...]}
```
### Parameters
| Parameter | Type | Required | Description |
| --------------------- | --------- | -------- | ------------------------------------------------- |
| `site_token` | str | Yes | Your site token (`st_...`) |
| `site_id` | str | Yes | Your site UUID |
| `access_token_secret` | str | Yes | Secret for token verification |
| `api_base` | str | No | Platform API URL (default: `https://xenarch.dev`) |
| `excluded_paths` | set\[str] | No | Paths to skip gating |
## Pattern 2: Per-route decorator
Gates individual routes:
```python theme={null}
from fastapi import FastAPI, Request
from xenarch.decorator import require_payment
app = FastAPI()
gate = require_payment(
site_token="st_...",
site_id="your-site-uuid",
access_token_secret="your_secret",
)
@app.get("/")
async def home():
"""Free for everyone."""
return {"message": "Welcome"}
@app.get("/premium")
@gate
async def premium(request: Request):
"""Gated — bots must pay."""
return {"content": "premium data"}
```
The decorated function must accept a `request: Request` parameter.
## How it works
```
Human request → passes through (zero overhead)
Bot + valid token → passes through
Bot + no token → HTTP 402 with payment gate
```
1. Checks `User-Agent` against known bot signatures
2. If bot: checks `Authorization: Bearer` header for a valid access token
3. Valid token: verifies HMAC signature, checks expiry, checks site\_id — all local, no API call
4. No token: calls `POST /v1/gates` to create a gate, returns HTTP 402
## Testing
```bash theme={null}
# Human request — passes through
curl http://localhost:8000/articles
# Bot without token — 402
curl -H "User-Agent: GPTBot/1.0" http://localhost:8000/articles
# Bot with token — passes through
curl -H "User-Agent: GPTBot/1.0" \
-H "Authorization: Bearer eyJ..." \
http://localhost:8000/articles
```
## Full example
See the [FastAPI publisher example](/examples/fastapi-publisher) for a complete working application.
# Joomla
Source: https://docs.xenarch.com/integrations/joomla
Joomla pay-per-crawl extension with AI bot detection — charge AI crawlers with USDC micropayments on Base. Full admin dashboard, non-custodial.
Full Joomla 5.x package with admin dashboard, bot detection, and payment gating.
## Requirements
* Joomla 5.0+
* PHP 8.1+
* MySQL 8.0+
## Installation
1. Download `pkg_xenarch.zip` from the [releases page](https://github.com/xenarch-ai/xenarch-plugins/releases)
2. Go to **System → Install Extensions** in your Joomla admin panel
3. Upload `pkg_xenarch.zip`
The installer creates the required database tables and configures HTTP headers automatically.
## What gets installed
The package contains three extensions:
| Extension | Type | Purpose |
| ------------------------- | ------------------- | ------------------------------ |
| `com_xenarch` | Component | Admin dashboard + REST API |
| `plg_system_xenarch` | System Plugin | Bot detection + payment gating |
| `plg_webservices_xenarch` | Web Services Plugin | API route registration |
## Configuration
After installation, go to **Components → Xenarch** to open the dashboard.
### Onboarding flow
1. **Register** — create your publisher account
2. **Add site** — link your Joomla site to the Xenarch platform
3. **Set payout wallet** — enter your Base/Ethereum address for USDC payouts
### Settings
| Setting | Default | Description |
| ---------------------- | ------- | -------------------------------- |
| `default_price` | \$0.003 | Price per page in USD |
| `gate_enabled` | Yes | Master toggle for payment gating |
| `gate_unknown_traffic` | Yes | Gate non-browser traffic |
| `payout_wallet` | — | Your Base address for payouts |
### Bot category policies
Control how each type of AI traffic is handled:
```json theme={null}
{
"ai_search": "allow",
"ai_assistants": "charge",
"ai_agents": "charge",
"ai_training": "charge",
"scrapers": "charge",
"general_ai": "charge"
}
```
### Per-bot overrides
Override the category default for specific bots:
```json theme={null}
{
"GPTBot": "allow",
"ClaudeBot": "charge"
}
```
### Pricing rules
Set different prices for specific paths:
```json theme={null}
[
{ "path_contains": "/premium/", "price_usd": 0.01 },
{ "path_contains": "/research/", "price_usd": 0.005 }
]
```
## How it works
### Request flow
1. **Skip** — logged-in users, static assets, and `/.well-known/*` paths always pass through
2. **Check token** — if the request has a valid `Authorization: Bearer `, allow it
3. **Detect bot** — match User-Agent against 100+ known AI bot signatures, then score headers
4. **Apply policy** — check per-bot override, then category default
5. **Respond** — allow (200), challenge (403 + browser proof), or gate (402 + payment payload)
### Discovery documents
The plugin automatically serves:
* **`/.well-known/pay.json`** — machine-readable pricing for AI agents
* **`/.well-known/xenarch.md`** — human-readable payment instructions
### Bot detection
Detection runs in priority order:
1. **Signature match** — 100+ known AI bot User-Agent strings
2. **Trusted search crawlers** — Googlebot, Bingbot, etc. (always allowed)
3. **HTTP client signatures** — python-requests, curl, wget, Go-http-client
4. **Browser proof cache** — valid proof cookie from a previous challenge
5. **Header scoring** — missing `Accept`, `Accept-Language`, `Sec-Fetch-*` headers increase suspicion score
## Build from source
```bash theme={null}
cd xenarch-plugins/joomla
./scripts/build-release.sh
# Output: src/packages/pkg_xenarch.zip
```
## Local development
```bash theme={null}
cd xenarch-plugins/joomla
docker compose up -d
# Joomla 5.4 + MySQL 8 at localhost:8889
```
Source files are mounted as volumes for live development.
## Admin UI development
The dashboard is a React + TypeScript app:
```bash theme={null}
cd xenarch-plugins/joomla/admin-ui
npm install
npm run build
```
Build output goes to `src/media/com_xenarch/js/` and `src/media/com_xenarch/css/`.
# LangChain
Source: https://docs.xenarch.com/integrations/langchain
LangChain payment tools — let LangChain agents pay for x402-gated content with USDC micropayments. MCP-compatible. Drop-in tool integration.
## Installation
```bash theme={null}
pip install xenarch[agent,langchain]
```
Requires `langchain>=0.3.0`.
## Tools
The SDK provides three LangChain tools:
```python theme={null}
from xenarch.tools.langchain import CheckGateTool, PayTool, GetHistoryTool
tools = [CheckGateTool(), PayTool(), GetHistoryTool()]
```
| Tool | Description |
| ---------------- | -------------------------------------------- |
| `CheckGateTool` | Check if a URL has an x402 payment gate |
| `PayTool` | Execute USDC payment and return access token |
| `GetHistoryTool` | View past payments for this wallet |
## Usage with LangGraph
```python theme={null}
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from xenarch.tools.langchain import CheckGateTool, PayTool, GetHistoryTool
load_dotenv()
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
tools = [CheckGateTool(), PayTool(), GetHistoryTool()]
agent = create_react_agent(
llm,
tools,
prompt=(
"You are a helpful assistant with Xenarch payment tools. "
"You can check URLs for payment gates, pay for gated content, "
"and review payment history."
),
)
result = agent.invoke({
"messages": [{
"role": "user",
"content": "Check if example.com has a paywall and pay if needed."
}]
})
```
## Using with other LLMs
```python theme={null}
# Anthropic
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(model="claude-sonnet-4-20250514")
# Local model via Ollama
from langchain_community.llms import Ollama
llm = Ollama(model="llama3")
```
## Wallet configuration
The tools use the same wallet configuration as the core SDK:
1. `XENARCH_PRIVATE_KEY` environment variable
2. `~/.xenarch/config.json`
3. `~/.xenarch/wallet.json`
4. Auto-generate on first use
See [Agent Quickstart](/quickstart-agent) for wallet setup.
## Full example
See the [LangChain agent example](/examples/langchain-agent) for a complete working script.
# Integrations
Source: https://docs.xenarch.com/integrations/overview
Connect Xenarch to your stack — pay-per-crawl plugins (WordPress, Joomla), agent frameworks (LangChain, CrewAI), web frameworks (FastAPI), and standards.
## Standards
Machine-readable pricing for your site — like robots.txt but for payments.
Coming soon.
## CMS
Zero-code plugins for content management systems.
Payment gating plugin for WordPress sites.
Full package for Joomla 5.x with admin dashboard.
Coming soon.
Coming soon.
## Web Frameworks
Middleware and decorators for server-side frameworks.
ASGI middleware for Python APIs.
Coming soon.
Coming soon.
Coming soon.
Coming soon.
Coming soon.
## Agent Frameworks
Add payment capabilities to your AI agents.
Payment tools for LangChain agents.
Payment tools for CrewAI crews.
Coming soon.
Coming soon.
Coming soon.
Coming soon.
# pay.json
Source: https://docs.xenarch.com/integrations/pay-json
pay.json — open machine-readable pricing standard for AI agents. Served at /.well-known/pay.json. Like robots.txt but for x402 payments.
`pay.json` is an open standard that lets AI agents discover what content costs and how to pay before making a request. Publishers serve it at `/.well-known/pay.json`.
## Quick start
Generate a `pay.json` file:
```bash theme={null}
npx pay-json-generate \
--wallet 0xYOUR_WALLET \
--receiver 0xC6D3a6B6fcCD6319432CDB72819cf317E88662ae \
--price 0.003 \
--provider xenarch \
--output .well-known/pay.json
```
Serve it at `https://yourdomain.com/.well-known/pay.json`.
## Specification (v1.0)
### Required fields
| Field | Type | Description |
| --------------- | ------ | ------------------------------------------- |
| `version` | string | Must be `"1.0"` |
| `protocol` | string | Payment protocol (e.g., `"x402"`) |
| `network` | string | Blockchain network (e.g., `"base"`) |
| `asset` | string | Payment token (e.g., `"USDC"`) |
| `receiver` | string | Splitter contract address (`0x` + 40 hex) |
| `seller_wallet` | string | Publisher wallet address (`0x` + 40 hex) |
| `rules` | array | Ordered list of path-to-price rules (min 1) |
### Optional fields
| Field | Type | Description |
| ------------- | ------ | ------------------------------- |
| `provider` | string | Payment infrastructure provider |
| `facilitator` | string | Verification endpoint URL |
| `contact` | string | Publisher contact |
| `terms` | string | Terms of service URL |
| `tools` | object | CLI, SDK, and docs hints |
## Example
```json theme={null}
{
"version": "1.0",
"protocol": "x402",
"network": "base",
"asset": "USDC",
"receiver": "0xC6D3a6B6fcCD6319432CDB72819cf317E88662ae",
"seller_wallet": "0xabcdef1234567890abcdef1234567890abcdef12",
"provider": "xenarch",
"facilitator": "https://xenarch.dev/v1/gates",
"tools": {
"cli": {
"install": "npm install -g xenarch",
"usage": "xenarch pay "
},
"sdk": {
"npm": "xenarch",
"pypi": "xenarch"
},
"docs": "https://docs.xenarch.com"
},
"rules": [
{ "path": "/public/*", "price_usd": "0" },
{ "path": "/blog/*", "price_usd": "0.003" },
{ "path": "/premium/*", "price_usd": "0.01" },
{ "path": "/api/*", "price_usd": "0.05" },
{ "path": "/**", "price_usd": "0.003" }
]
}
```
## Pricing rules
Rules are evaluated **top-to-bottom**. First match wins.
### Glob patterns
| Pattern | Matches | Example |
| ------- | --------------------------------- | -------------------------------------------------------- |
| `*` | Single path segment (no `/`) | `/blog/*` matches `/blog/post` but not `/blog/2024/post` |
| `**` | Multiple segments (including `/`) | `/blog/**` matches `/blog/2024/post` |
| `?` | Exactly one character | `/api/v?/data` matches `/api/v1/data` |
### Special values
* `"0"` or `"0.00"` — explicitly free
* No matching rule — path is free
* No pay.json file — entire site is free
## Validation
```bash theme={null}
npx pay-json-validate path/to/pay.json
```
Validates JSON syntax, schema compliance, and lints for rule ordering issues (e.g., wildcard rules that shadow more specific rules).
```bash theme={null}
# Quiet mode (exit code only)
npx pay-json-validate pay.json --quiet
# JSON output
npx pay-json-validate pay.json --json
```
## Discovery priority
Agents should discover pricing in this order:
1. **pay.json** at `/.well-known/pay.json` — most authoritative
2. **Meta tag** `` — fallback
3. **HTTP 402 response** — server returns payment instructions
4. **Free** — no pricing signals found
Agents must not combine pricing from multiple sources.
## npm package
```bash theme={null}
npm install pay-json
```
Source: [github.com/xenarch-ai/pay-json](https://github.com/xenarch-ai/pay-json)
# WordPress
Source: https://docs.xenarch.com/integrations/wordpress
WordPress pay-per-crawl plugin with AI bot detection — charge AI crawlers with USDC micropayments. Non-custodial Cloudflare pay-per-crawl alternative.
## Installation
Install the Xenarch plugin from the WordPress plugin directory, or upload the zip manually.
## Setup
1. Go to **Settings > Xenarch** in WordPress admin
2. Enter your site token (`st_...`)
3. Set your payout wallet address
4. Configure default pricing
5. Enable gating
## Features
### Bot detection
The plugin detects 135+ known AI bot signatures across 6 categories:
| Category | Examples | Default |
| ------------- | ------------------------------ | ------- |
| AI Search | Google AI, Perplexity, You.com | Gated |
| AI Assistants | ChatGPT, Claude | Gated |
| AI Agents | Custom agents, MCP clients | Gated |
| AI Training | GPTBot, CCBot, Common Crawl | Gated |
| Scrapers | Diffbot, Webz.io | Gated |
| General AI | Other AI-identified bots | Gated |
Toggle categories on/off. Override individual bots.
### Pricing rules
Set path-specific pricing:
* Default price for all pages
* URL pattern overrides (e.g., `/premium/*` at \$0.01)
* Free paths (price = \$0)
### What passes through
* **Human visitors** — always pass through, zero impact
* **Search crawlers** (Google, Bing) — allowlisted by default
* **Social previews** (Twitter, LinkedIn) — allowlisted by default
* **Bots with valid tokens** — pass through after payment
### pay.json auto-generation
The plugin automatically serves `/.well-known/pay.json` based on your pricing configuration. No manual file creation needed.
### Bot logging
The plugin logs detected bots to the `wp_xenarch_bot_log` table:
* Signature, category, company
* First seen, last seen, hit count
* Auto-categorizes unknown bots
## How it works
1. Request comes in
2. Plugin checks: admin page? Logged-in user? Allowlisted path? → skip
3. Checks User-Agent against known bot signatures
4. If bot detected: checks category toggles and per-bot overrides
5. If gated: checks for valid `Authorization: Bearer` token
6. If no token: returns HTTP 402 with payment gate details
7. Agent pays USDC on Base, verifies, gets access token
8. Agent re-requests with token → content served
## Requirements
* WordPress 6.0+
* PHP 7.4+
* A Xenarch publisher account with registered site
# Introduction
Source: https://docs.xenarch.com/introduction
x402 payment infrastructure for AI agents — route USDC micropayments between AI bots and publishers on Base L2. Non-custodial, 0% fee, pay-per-crawl.
Xenarch is a non-custodial payment layer that lets publishers charge AI agents for content and services using the [x402 protocol](https://www.x402.org/). Agents pay USDC on Base L2 through a splitter smart contract. Publishers receive funds directly — Xenarch never holds anyone's money.
## What Xenarch does
* **For publishers**: Gate content behind HTTP 402 responses. Bots pay USDC, humans pass through unaffected.
* **For agents**: Discover pricing via `pay.json` or HTTP 402, pay on-chain, receive time-limited access tokens.
* **For platforms**: Integrate via Python/TypeScript SDKs, MCP server, or CMS plugins.
## How payments work
```
Agent requests content → Server returns HTTP 402 with gate details
Agent sends USDC to splitter contract → Contract splits to publisher + treasury
Agent submits tx hash to verify endpoint → Server returns access token
Agent re-requests content with Bearer token → Server returns content
```
Every payment is a single on-chain USDC transfer. No deposits, no balances, no custody. The splitter contract has an immutable fee cap of 0.99% (currently 0%).
## Key properties
| Property | Value |
| ---------------- | -------------------------------- |
| **Settlement** | USDC on Base L2 |
| **Max payment** | \$1.00 per transaction |
| **Fee** | 0% (capped at 0.99% forever) |
| **Custody** | None — permanently non-custodial |
| **Verification** | On-chain, auditable on Basescan |
| **Protocol** | x402 (HTTP 402 Payment Required) |
## Next steps
Start paying for gated content in 5 minutes.
Start charging AI agents for your content.
Full REST API documentation.
Working code for Python, LangChain, CrewAI, and MCP.
# Install MCP Server (Claude Desktop & Code)
Source: https://docs.xenarch.com/mcp/installation
Install the Xenarch MCP server for Claude Desktop, Claude Code, Cursor, or any Model Context Protocol client. One-command npx setup in under 2 minutes.
Install the Xenarch MCP server in Claude Desktop, Claude Code, Cursor, or any Model Context Protocol client. A single `npx` command wires up three tools for x402 payments — `xenarch_check_gate`, `xenarch_pay`, and `xenarch_get_history` — no cloning, no build step, no API key.
## Prerequisites
* Node.js 18+
* A wallet with USDC on Base (+ small ETH for gas)
## Claude Code
```bash theme={null}
claude mcp add xenarch -- npx @xenarch/agent-mcp
```
## Claude Desktop
Edit your config file:
* **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
* **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
```json theme={null}
{
"mcpServers": {
"xenarch": {
"command": "npx",
"args": ["@xenarch/agent-mcp"],
"env": {
"XENARCH_PRIVATE_KEY": "0xYOUR_PRIVATE_KEY"
}
}
}
}
```
Restart Claude Desktop after saving.
## Other MCP clients
Any client that supports the MCP stdio transport can use the server:
```bash theme={null}
npx @xenarch/agent-mcp
```
The server communicates over stdin/stdout using the MCP protocol.
## Wallet configuration
Set `XENARCH_PRIVATE_KEY` in the MCP server's env block:
```json theme={null}
{
"env": {
"XENARCH_PRIVATE_KEY": "0xYOUR_PRIVATE_KEY"
}
}
```
Create `~/.xenarch/wallet.json`:
```bash theme={null}
mkdir -p ~/.xenarch
cat > ~/.xenarch/wallet.json << 'EOF'
{
"privateKey": "0xYOUR_PRIVATE_KEY"
}
EOF
chmod 600 ~/.xenarch/wallet.json
```
If no wallet is configured, the server generates one on first run and saves it to `~/.xenarch/wallet.json`. Fund it with USDC before making payments.
## Configuration variables
| Variable | Default | Description |
| -------------------------- | -------------------------- | ------------------------------------------- |
| `XENARCH_PRIVATE_KEY` | — | Wallet private key |
| `XENARCH_NETWORK` | `base` | `base` or `base-sepolia` |
| `XENARCH_RPC_URL` | `https://mainnet.base.org` | Base RPC endpoint |
| `XENARCH_API_BASE` | `https://api.xenarch.dev` | Platform API |
| `XENARCH_AUTO_APPROVE_MAX` | — | Auto-approve payments up to this USD amount |
## Testnet
For testing without real funds:
```json theme={null}
{
"mcpServers": {
"xenarch": {
"command": "npx",
"args": ["@xenarch/agent-mcp"],
"env": {
"XENARCH_PRIVATE_KEY": "0xYOUR_PRIVATE_KEY",
"XENARCH_NETWORK": "base-sepolia",
"XENARCH_RPC_URL": "https://sepolia.base.org"
}
}
}
}
```
## Troubleshooting
**Tools not appearing**: Restart your MCP client. Verify `npx @xenarch/agent-mcp` runs without errors in your terminal.
**"No wallet configured"**: Set `XENARCH_PRIVATE_KEY` or create `~/.xenarch/wallet.json`.
**"Insufficient USDC"**: Fund your wallet with USDC on Base. You also need a small amount of ETH for gas (\~\$0.01).
# MCP Server
Source: https://docs.xenarch.com/mcp/overview
Xenarch MCP server — Model Context Protocol server for Claude, Anthropic & MCP clients. Let AI agents check x402 payment gates and pay in USDC on Base.
The Xenarch MCP server (`@xenarch/agent-mcp`) gives AI agents three tools to discover, pay for, and track x402-gated content. It handles wallet management, on-chain USDC payments, and access token retrieval.
## What is an MCP server?
The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) is an open standard from Anthropic that lets AI agents access external tools. An **MCP server** exposes a set of tools over stdio or HTTP; agents (like Claude Desktop and Claude Code) call them as needed. The Xenarch MCP server exposes x402 payment tools — check a gate, pay in USDC on Base, retrieve payment history — so any MCP-compatible agent can autonomously pay for gated APIs and content.
## What it does
| Tool | Description |
| --------------------- | ------------------------------------------------------------------------------------------------------- |
| `xenarch_check_gate` | Check if a URL or domain has a payment gate. Returns price, contract details, and payment instructions. |
| `xenarch_pay` | Execute a USDC micropayment on Base L2 and return a Bearer access token. |
| `xenarch_get_history` | List past payments with tx hashes, amounts, and timestamps. |
## Supported MCP clients
* Claude Desktop
* Claude Code
* Any MCP-compatible client (Cursor, Cline, etc.)
## Quick setup
```bash theme={null}
claude mcp add xenarch -- npx @xenarch/agent-mcp
```
That's it for Claude Code. See [Installation](/mcp/installation) for Claude Desktop and other clients.
## How agents use it
An agent with the Xenarch MCP server can:
1. **Discover**: "Check if example.com has a paywall" → calls `xenarch_check_gate`
2. **Pay**: "Pay for access" → calls `xenarch_pay`, sends USDC on Base
3. **Access**: Uses the returned Bearer token to fetch gated content
4. **Review**: "Show my payment history" → calls `xenarch_get_history`
The agent decides when to pay based on the task context. No hardcoded payment logic needed.
# MCP Tools Reference
Source: https://docs.xenarch.com/mcp/tools
Reference for the three Xenarch MCP server tools — check x402 payment gates, pay USDC micropayments on Base, and query agent payment history.
The Xenarch MCP server exposes three tools over the Model Context Protocol. Each is callable by Claude Desktop, Claude Code, or any MCP-compatible agent. Below: full input/output schemas and usage examples.
## xenarch\_check\_gate
Check if a URL or domain has an x402 payment gate.
**Input:**
| Parameter | Type | Description |
| --------- | ------ | ------------------------------------------------------------------------------- |
| `url` | string | URL or domain to check. Accepts `https://example.com/article` or `example.com`. |
**Output (gated):**
```json theme={null}
{
"gated": true,
"gate_id": "7f3a1b2c-9d4e-4a8b-b6f1-2c3d4e5f6a7b",
"price_usd": "0.003",
"splitter": "0xC6D3a6B6fcCD6319432CDB72819cf317E88662ae",
"collector": "0xabc123...publisher_wallet",
"network": "base",
"asset": "USDC",
"protocol": "x402"
}
```
**Output (not gated):**
```json theme={null}
{
"gated": false,
"message": "No Xenarch gate found for example.com"
}
```
## xenarch\_pay
Execute a USDC micropayment on Base L2 to access gated content.
**Input:**
| Parameter | Type | Required | Description |
| --------- | ------ | -------- | ---------------------------------------------------------------- |
| `url` | string | Yes | URL or domain to pay for. Must have an active gate. |
| `amount` | string | No | Override amount in USD (e.g., `"0.01"`). Defaults to gate price. |
**Output:**
```json theme={null}
{
"success": true,
"tx_hash": "0xdef456...abc789",
"block_number": 28451023,
"amount_usd": "0.003",
"url": "example.com",
"access_token": "eyJhbGciOiJIUzI1NiJ9...",
"expires_at": "2026-04-10T15:05:00Z",
"wallet": "0x123...your_wallet"
}
```
**Flow:**
1. Checks for active gate (calls `xenarch_check_gate` internally)
2. Verifies USDC balance
3. Approves USDC on the splitter contract
4. Calls `split(collector, amount)` on-chain
5. Submits tx hash to the verify endpoint
6. Returns access token
## xenarch\_get\_history
List past USDC micropayments made by this wallet.
**Input:**
| Parameter | Type | Required | Description |
| --------- | ------ | -------- | ------------------------------------------------------- |
| `domain` | string | No | Filter by domain (e.g., `"example.com"`). Omit for all. |
| `limit` | number | No | Max records (1-100, default 10). |
**Output:**
```json theme={null}
{
"payments": [
{
"domain": "example.com",
"amount_usd": "0.003",
"tx_hash": "0xdef456...abc789",
"paid_at": "2026-04-10T14:35:00Z"
}
],
"total_spent_usd": "0.003000",
"count": 1,
"wallet": "0x123...your_wallet"
}
```
# Agent Quickstart
Source: https://docs.xenarch.com/quickstart-agent
AI agent payments quickstart — pay for x402-gated content with USDC micropayments in 5 minutes using the Xenarch MCP server or Python SDK.
## Prerequisites
* Python 3.10+
* A wallet with USDC on Base (+ small ETH for gas)
* For testnet: use `base-sepolia` with test USDC
## Install the SDK
```bash theme={null}
pip install xenarch[agent]
```
## Configure your wallet
The SDK loads wallet configuration from environment variables or `~/.xenarch/wallet.json`.
```bash theme={null}
export XENARCH_PRIVATE_KEY="0xYOUR_PRIVATE_KEY"
export XENARCH_NETWORK="base" # or base-sepolia for testnet
export XENARCH_RPC_URL="https://mainnet.base.org"
```
```bash theme={null}
mkdir -p ~/.xenarch
cat > ~/.xenarch/wallet.json << 'EOF'
{
"privateKey": "0xYOUR_PRIVATE_KEY"
}
EOF
chmod 600 ~/.xenarch/wallet.json
```
Call `load_wallet_or_create()` and the SDK generates a new wallet at `~/.xenarch/wallet.json` automatically. Fund it with USDC before making payments.
## Pay for gated content
```python theme={null}
from xenarch.agent_client import check_gate, verify_payment
from xenarch.payment import execute_payment
from xenarch.wallet import load_wallet_or_create
wallet = load_wallet_or_create()
# 1. Check if the URL has a payment gate
gate = check_gate("https://example.com/premium")
if not gate:
print("No gate — content is free")
else:
print(f"Price: ${gate.price_usd} USDC")
# 2. Pay on-chain
result = execute_payment(
wallet=wallet,
splitter_address=gate.splitter,
collector_address=gate.collector,
price_usd=gate.price_usd,
)
print(f"TX: {result.tx_hash}")
# 3. Verify and get access token
verification = verify_payment(gate.verify_url, result.tx_hash)
token = verification["access_token"]
# 4. Fetch content with token
import httpx
resp = httpx.get(
"https://example.com/premium",
headers={"Authorization": f"Bearer {token}"},
)
print(resp.text)
```
## Alternative: use the MCP server
If you're using Claude Desktop or Claude Code, add Xenarch as an MCP server — no code required:
```bash theme={null}
claude mcp add xenarch -- npx @xenarch/agent-mcp
```
Then ask Claude: *"Check if example.com has a paywall and pay for access."*
See [MCP installation](/mcp/installation) for full setup.
## Alternative: use LangChain or CrewAI
```bash theme={null}
pip install xenarch[agent,langchain]
```
```python theme={null}
from xenarch.tools.langchain import CheckGateTool, PayTool, GetHistoryTool
tools = [CheckGateTool(), PayTool(), GetHistoryTool()]
```
See the [LangChain integration guide](/integrations/langchain).
```bash theme={null}
pip install xenarch[agent,crewai]
```
```python theme={null}
from xenarch.tools.crewai import check_gate, pay, get_history
tools = [check_gate, pay, get_history]
```
See the [CrewAI integration guide](/integrations/crewai).
## Testnet
For testing without real funds, use Base Sepolia:
```bash theme={null}
export XENARCH_NETWORK="base-sepolia"
export XENARCH_RPC_URL="https://sepolia.base.org"
```
The testnet uses a mock USDC contract (`0xc5aDdd66Da733101A5468857Aa3C6689Af9d1DDc`) where anyone can mint tokens.
# Publisher Quickstart
Source: https://docs.xenarch.com/quickstart-publisher
Start charging AI bots for content access — pay-per-crawl setup with USDC micropayments in 5 minutes. Non-custodial Cloudflare pay-per-crawl alternative.
Set up pay-per-crawl on your site in five minutes — detect AI bots (GPTBot, ClaudeBot, PerplexityBot, etc.), return HTTP 402, collect USDC micropayments on Base. Works standalone or as a non-custodial alternative to Cloudflare pay-per-crawl.
## Xenarch vs Cloudflare pay-per-crawl
| | Xenarch | Cloudflare pay-per-crawl |
| -------------- | ----------------------------------------------------------- | ------------------------------------------ |
| **Custody** | Non-custodial — USDC settles on-chain via splitter contract | Custodial — Cloudflare holds your earnings |
| **Fee** | 0% (capped at 0.99% forever) | Cloudflare takes a cut |
| **Settlement** | USDC on Base L2, every payment on-chain | Fiat payout, off-chain ledger |
| **Stack** | Any stack (Python, Node, WordPress, Joomla, custom) | Cloudflare Workers required |
| **Pricing** | Per-page or per-path, publisher-defined | Cloudflare-defined |
## Prerequisites
* A USDC wallet on Base (this is where you receive payments)
* Your content served over HTTPS
## Step 1: Register
```bash theme={null}
npx xenarch register
```
This creates your publisher account and returns an API key (`xk_pub_...`).
## Step 2: Add your site
```bash theme={null}
npx xenarch site-add example.com
```
Returns a site token (`st_...`) and site ID. Save both.
## Step 3: Set pricing
```bash theme={null}
npx xenarch pricing example.com --default 0.003
```
Sets a default price of \$0.003 per page. Add path-specific rules:
```bash theme={null}
npx xenarch pricing example.com \
--rule "/premium/*=0.01" \
--rule "/api/*=0.05" \
--rule "/public/*=0"
```
## Step 4: Install middleware
Choose your integration:
```bash theme={null}
pip install xenarch[fastapi]
```
**Site-wide middleware** (gates all bot traffic):
```python theme={null}
from xenarch.middleware import XenarchMiddleware
app.add_middleware(
XenarchMiddleware,
site_token="st_...",
site_id="your-site-uuid",
access_token_secret="your_secret",
excluded_paths={"/healthz", "/docs"},
)
```
**Per-route decorator** (gates individual endpoints):
```python theme={null}
from xenarch.decorator import require_payment
gate = require_payment(
site_token="st_...",
site_id="your-site-uuid",
access_token_secret="your_secret",
)
@app.get("/premium")
@gate
async def premium(request: Request):
return {"content": "premium data"}
```
See the [FastAPI middleware guide](/integrations/fastapi-middleware).
1. Install the Xenarch plugin from the WordPress directory
2. Go to **Settings > Xenarch**
3. Enter your site token and configure pricing
4. Toggle bot categories to gate (AI Search, Assistants, Agents, etc.)
See the [WordPress guide](/integrations/wordpress).
Implement the flow manually:
1. Detect bots via User-Agent matching
2. Call `POST /v1/gates` to create a gate
3. Return HTTP 402 with the gate response
4. When agents submit a Bearer token, verify it via `POST /v1/access-tokens/verify`
See the [API reference](/api-reference/overview).
## Step 5: Add pay.json (optional)
Serve a `pay.json` file at `/.well-known/pay.json` so agents can discover your pricing without hitting a 402 first:
```bash theme={null}
npx pay-json-generate \
--wallet 0xYOUR_WALLET \
--receiver 0xC6D3a6B6fcCD6319432CDB72819cf317E88662ae \
--price 0.003 \
--provider xenarch \
--output .well-known/pay.json
```
See the [pay.json spec](/integrations/pay-json).
## How it works for your users
* **Humans**: Pass through completely unaffected. The middleware only gates bot traffic.
* **AI agents with payment**: Pay USDC, get an access token, access your content.
* **AI agents without payment**: See HTTP 402 with payment instructions.
## Check your earnings
```bash theme={null}
npx xenarch stats your-site-id
```
# CLI
Source: https://docs.xenarch.com/sdks/cli
xenarch CLI — command-line tool for AI agents and publishers to manage x402 payment gates, USDC payments on Base, and pay-per-crawl pricing.
## Installation
```bash theme={null}
npx xenarch-cli
```
Or install globally:
```bash theme={null}
npm install -g xenarch
```
## Agent commands
### Wallet
```bash theme={null}
# Generate a new wallet
xenarch wallet generate
# Import an existing private key
xenarch wallet import 0xYOUR_PRIVATE_KEY
# Connect via WalletConnect (scans QR code)
xenarch wallet connect
```
Wallets are stored at `~/.xenarch/wallet.json` with `chmod 600`.
### Check gate
```bash theme={null}
xenarch check https://example.com/premium
```
Output:
```
Gate found!
Price: $0.003 USDC
Network: Base
Splitter: 0xC6D3...62ae
Collector: 0xabc1...publisher
```
### Pay
```bash theme={null}
xenarch pay https://example.com/premium
```
Executes the full flow: check gate, send USDC, verify, return access token.
### History
```bash theme={null}
# All payments
xenarch history
# Filter by domain
xenarch history --domain example.com
```
## Publisher commands
### Register
```bash theme={null}
xenarch register
```
Interactive: prompts for email and password. Returns your API key.
### Login
```bash theme={null}
xenarch login
```
### Sites
```bash theme={null}
# List sites
xenarch sites
# Add a new site
xenarch site-add example.com
# View earnings
xenarch stats
```
### Payout
```bash theme={null}
xenarch payout 0xYOUR_WALLET_ADDRESS
```
# Python SDK
Source: https://docs.xenarch.com/sdks/python
xenarch Python package — x402 agent payments, FastAPI publisher middleware, and AI bot detection. Pip install xenarch[agent] or xenarch[fastapi].
## Installation
```bash theme={null}
# For AI agents (wallet + on-chain payments)
pip install xenarch[agent]
# For publishers (FastAPI middleware)
pip install xenarch[fastapi]
# For LangChain agents
pip install xenarch[agent,langchain]
# For CrewAI agents
pip install xenarch[agent,crewai]
```
Requires Python 3.12+. Published on [PyPI](https://pypi.org/project/xenarch/).
## Agent modules
### Wallet management
```python theme={null}
from xenarch.wallet import load_wallet, load_wallet_or_create, generate_wallet
# Load from env vars or ~/.xenarch/wallet.json
wallet = load_wallet()
# Load or auto-create on first run
wallet = load_wallet_or_create()
# Generate a new wallet
wallet = generate_wallet()
print(wallet.address) # 0x...
print(wallet.network) # "base" or "base-sepolia"
print(wallet.rpc_url) # RPC endpoint
```
**Configuration priority:**
1. Environment variables (`XENARCH_PRIVATE_KEY`, `XENARCH_RPC_URL`, `XENARCH_NETWORK`)
2. `~/.xenarch/config.json`
3. `~/.xenarch/wallet.json`
### Gate checking
```python theme={null}
from xenarch.agent_client import check_gate, check_gate_by_domain
# Check by URL (makes an HTTP request, looks for 402)
gate = check_gate("https://example.com/premium")
# Check by domain (queries the platform API)
gate = check_gate_by_domain("https://xenarch.dev", "example.com")
if gate:
print(gate.price_usd) # "0.003"
print(gate.splitter) # Splitter contract address
print(gate.collector) # Publisher wallet
print(gate.verify_url) # Verification endpoint
```
### Payment execution
```python theme={null}
from xenarch.payment import execute_payment
result = execute_payment(
wallet=wallet,
splitter_address=gate.splitter,
collector_address=gate.collector,
price_usd=gate.price_usd,
)
print(result.tx_hash) # "0x..."
print(result.block_number) # 28451023
```
The function:
1. Checks USDC balance
2. Checks ETH for gas
3. Approves USDC on the splitter contract (unlimited, to avoid repeated approvals)
4. Calls `splitter.split(collector, amount)` with 150k gas limit
**Constraints:**
* Max \$1.00 per transaction
* Splitter must be in the trusted allowlist
* USDC uses 6 decimals
### Payment verification
```python theme={null}
from xenarch.agent_client import verify_payment
result = verify_payment(gate.verify_url, tx_hash)
print(result["access_token"]) # "eyJ..."
print(result["expires_at"]) # "2026-04-10T15:05:00Z"
```
### Payment history
```python theme={null}
from xenarch.agent_client import get_payment_history
history = get_payment_history(
api_base="https://xenarch.dev",
wallet_address=wallet.address,
domain="example.com", # optional filter
limit=10,
)
for item in history:
print(f"{item.domain}: ${item.amount_usd} ({item.tx_hash})")
```
## Publisher modules
### XenarchMiddleware (ASGI)
Gates all bot traffic site-wide:
```python theme={null}
from xenarch.middleware import XenarchMiddleware
app.add_middleware(
XenarchMiddleware,
site_token="st_...",
site_id="your-site-uuid",
access_token_secret="your_secret",
api_base="https://xenarch.dev", # optional
excluded_paths={"/healthz", "/docs"}, # optional
)
```
Behavior:
* Human requests pass through (zero overhead)
* Bots with valid `Authorization: Bearer` token pass through
* Bots without token get HTTP 402 with gate details
### require\_payment decorator
Gates individual routes:
```python theme={null}
from xenarch.decorator import require_payment
gate = require_payment(
site_token="st_...",
site_id="your-site-uuid",
access_token_secret="your_secret",
)
@app.get("/premium")
@gate
async def premium(request: Request):
return {"content": "premium data"}
```
### Token verification
Verify access tokens locally (no API call):
```python theme={null}
from xenarch.token import verify_access_token
result = verify_access_token(token, site_id, secret)
# Returns payload dict if valid, None if invalid/expired
```
### Bot detection
```python theme={null}
from xenarch.detection import is_bot
is_bot("GPTBot/1.0") # True
is_bot("Mozilla/5.0 Chrome") # False
```
Matches against 20+ known AI bot signatures (GPTBot, ClaudeBot, PerplexityBot, etc.).
## Environment variables
| Variable | Default | Description |
| --------------------- | -------------------------- | ------------------------ |
| `XENARCH_PRIVATE_KEY` | — | Wallet private key |
| `XENARCH_RPC_URL` | `https://mainnet.base.org` | Base RPC endpoint |
| `XENARCH_API_BASE` | `https://xenarch.dev` | Platform API base |
| `XENARCH_NETWORK` | `base` | `base` or `base-sepolia` |
## Contract addresses
| Network | Splitter | USDC |
| ------------ | -------------------------------------------- | -------------------------------------------- |
| Base Mainnet | `0xC6D3a6B6fcCD6319432CDB72819cf317E88662ae` | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` |
| Base Sepolia | `0x7ecfe8f83eab6ba170063d1f1fe7c33695a9ce1d` | `0xc5aDdd66Da733101A5468857Aa3C6689Af9d1DDc` |
# TypeScript SDK
Source: https://docs.xenarch.com/sdks/typescript
@xenarch/core — TypeScript & Node.js SDK for x402 payments, AI agent integration, and publisher middleware. USDC micropayments on Base.
## Installation
```bash theme={null}
npm install @xenarch/core
```
Published on [npm](https://www.npmjs.com/package/@xenarch/core). Used internally by the MCP server and CLI.
## Configuration
```typescript theme={null}
import { loadConfig, createSigner } from "@xenarch/core";
const { config } = await loadConfig();
const signer = createSigner(config);
console.log(config.network); // "base" or "base-sepolia"
```
**Config loading priority:**
1. Environment variables (`XENARCH_PRIVATE_KEY`, `XENARCH_RPC_URL`, etc.)
2. `~/.xenarch/config.json`
3. `~/.xenarch/wallet.json`
4. Auto-generate wallet on first use
## Gate checking
```typescript theme={null}
import { fetchGate, fetchGateByDomain } from "@xenarch/core";
// Check by URL (HTTP request, looks for 402)
const result = await fetchGate("https://example.com/premium");
if (result.gate) {
console.log(result.gate.price_usd); // "0.003"
}
// Check by domain (platform API)
const gate = await fetchGateByDomain(
"https://xenarch.dev",
"example.com"
);
```
## Payment execution
```typescript theme={null}
import { executePayment, verifyPayment } from "@xenarch/core";
// Execute USDC payment on Base
const result = await executePayment(gate, signer, usdcAddress);
console.log(result.txHash); // "0x..."
console.log(result.blockNumber); // 28451023
// Verify and get access token
const { access_token, expires_at } = await verifyPayment(
gate.verify_url,
result.txHash
);
```
## Payment history
```typescript theme={null}
import { getPaymentHistory } from "@xenarch/core";
const history = await getPaymentHistory(
"https://xenarch.dev",
walletAddress,
{ domain: "example.com", limit: 10 }
);
```
## Types
```typescript theme={null}
interface XenarchConfig {
privateKey: string;
rpcUrl: string;
apiBase: string;
network: "base" | "base-sepolia";
autoApproveMaxUsd?: number;
allowedDomains?: string[];
blockedDomains?: string[];
}
interface GateResponse {
xenarch: boolean;
gate_id: string;
price_usd: string;
splitter: string;
collector: string;
network: string;
asset: string;
protocol: string;
verify_url: string;
expires: string;
}
interface PaymentResult {
txHash: string;
blockNumber: number;
}
interface PaymentHistoryItem {
url: string;
domain: string;
amount_usd: string;
tx_hash: string;
paid_at: string;
}
```
## Contract constants
```typescript theme={null}
// Base Mainnet
const USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
const SPLITTER_MAINNET = "0xC6D3a6B6fcCD6319432CDB72819cf317E88662ae";
// Base Sepolia
const SPLITTER_SEPOLIA = "0x7ecfe8f83eab6ba170063d1f1fe7c33695a9ce1d";
const MOCK_USDC_SEPOLIA = "0xc5aDdd66Da733101A5468857Aa3C6689Af9d1DDc";
```