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