# Elsa X402 MCP — Full Documentation > Pay-per-use HTTP API for crypto trading, DeFi operations, and on-chain analytics. Settled with X402 micropayments on Base. Each endpoint has a fixed USDC price; payment and execution happen in a single request. The same endpoints are also available as MCP tools for AI agents. This long-form reference mirrors the content at https://x402.heyelsa.ai/docs. ## Base URL & Payment Paths Base host: `https://x402-api.heyelsa.ai` Three payment paths exist for every endpoint. They are functionally identical — only the payment token differs. - **USDC** (default): `POST /api/` — pay in USDC on Base. - **ELSA token**: `POST /api/elsa/` — pay in ELSA (discounted). - **HYPERTHON**: `POST /api/hyperthon/` — Base mainnet only, 1:1 USDC equivalence. Hackathon-scoped availability; obtain HYPERTHON tokens from Hyperthon organizers. ## Quick Start ```ts import { withPaymentInterceptor } from 'x402-axios'; import axios from 'axios'; import { createWalletClient, http } from 'viem'; import { base } from 'viem/chains'; import { privateKeyToAccount } from 'viem/accounts'; const walletClient = createWalletClient({ account: privateKeyToAccount(PRIVATE_KEY), chain: base, transport: http('https://mainnet.base.org'), }); const client = withPaymentInterceptor( axios.create({ baseURL: 'https://x402-api.heyelsa.ai' }), walletClient, ); // Get portfolio (costs $0.01) const portfolio = await client.post('/api/get_portfolio', { wallet_address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb7', }); // Execute swap (costs $0.02) const swap = await client.post('/api/execute_swap', { from_chain: 'base', from_token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC from_amount: '100', to_chain: 'base', to_token: '0x4200000000000000000000000000000000000006', // WETH wallet_address: '0x...', slippage: 2.0, dry_run: false, }); ``` ## X402 Protocol Headers The X402 protocol uses a single Base64-encoded request header (`X-PAYMENT`) and a single Base64-encoded response header (`X-PAYMENT-RESPONSE`). Payment requirements themselves are returned in the **JSON body** of the `402` response — not in a header. ### Request / Response Flow 1. Client makes a request to a protected endpoint with **no `X-PAYMENT` header**. 2. Server replies with `402 Payment Required` and a JSON body listing payment options under `accepts`. 3. Client builds and signs an EIP-3009 payment authorization, and retries with an `X-PAYMENT` request header. 4. Server verifies, runs the handler, settles on-chain, and replies `200 OK` with an `X-PAYMENT-RESPONSE` header containing the settlement tx hash. ### `402` Response Body (server → client) Returned as the JSON response body when no valid payment is provided: ```json { "x402Version": 1, "error": "X-PAYMENT header is required", "accepts": [ { "scheme": "exact", "network": "base", "maxAmountRequired": "10000", "resource": "https://x402-api.heyelsa.ai/api/get_portfolio", "description": "Elsa X402 API", "mimeType": "application/json", "payTo": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C", "maxTimeoutSeconds": 60, "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "extra": { "name": "USDC", "version": "2" } } ] } ``` - `accepts[].maxAmountRequired` is in token base units (`10000` = $0.01 USDC at 6 decimals). - `accepts[].asset` is the ERC-20 contract for the payment token. - `accepts[].payTo` is the recipient wallet. - `accepts[].network` is the chain name (`base` = Base mainnet). - `accepts[].maxTimeoutSeconds` bounds the validity window for the signed authorization. ### `X-PAYMENT` Request Header (client → server) Base64-encoded `PaymentPayload` — a signed EIP-3009 `transferWithAuthorization`: ```json { "x402Version": 1, "scheme": "exact", "network": "base", "payload": { "signature": "0x...", "authorization": { "from": "0x857b06519E91e3A54538791bDbb0E22373e36b66", "to": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C", "value": "10000", "validAfter": "1740672089", "validBefore": "1740672154", "nonce": "0xf3746613..." } } } ``` `scheme` and `network` must match one of the `accepts` options from the `402` body. ### `X-PAYMENT-RESPONSE` Response Header (server → client, 200) Base64-encoded `SettleResponse`: ```json { "success": true, "transaction": "0x1234...", "network": "base", "payer": "0x857b06519E91e3A54538791bDbb0E22373e36b66" } ``` ### HTTP Status Codes - `200 OK` — payment verified and settled; response body returned with the `X-PAYMENT-RESPONSE` header. - `402 Payment Required` — missing `X-PAYMENT` header, malformed or invalid payment, facilitator rejection, or settlement failure. Body contains `x402Version`, `error`, and `accepts` retry options. - `400 Bad Request` — request body failed schema validation (a required endpoint parameter is missing or wrong-typed). - `500 Server Error` — unexpected internal error, unrelated to payment processing. ## Pipeline Transaction System All execution endpoints (swaps, perps, claims, Polymarket orders) return a **`pipeline_id`** rather than executing directly. The client must sign returned transactions and submit them back to advance the pipeline. Flow: 1. Call execute endpoint → receive `pipeline_id`. 2. Poll `/api/get_transaction_status` with the `pipeline_id`. 3. When a step has `status === "sign_pending"`, sign its `tx_data` (or EIP-712 typed data). 4. Submit the signed transaction or signature to the chain (or via the pipeline). 5. Submit the resulting tx hash via `/api/submit_transaction_hash` (or signature via `/api/submit_typed_data_signature`). 6. Continue polling until `status === "success"`. ```ts const result = await client.post('/api/execute_swap', { /* ... */ }); const status = await client.post('/api/get_transaction_status', { pipeline_id: result.data.result.pipeline_id, }); if (status.data.status[0].status === 'sign_pending') { const hash = await walletClient.sendTransaction(status.data.status[0].tx_data); await client.post('/api/submit_transaction_hash', { task_id: status.data.status[0].task_id, tx_hash: hash, status: 'submitted', }); } ``` ## API Endpoints Endpoint reference. Prices are in USDC; the same price applies on the ELSA and HYPERTHON paths (denominated in those tokens). Source of truth: `src/shared/config.ts` in the `elsa-x402-mcp-server` repo. ### Portfolio & Analytics - `POST /api/search_token` — **$0.001** — Search for tokens across all blockchains. - Request: `{ symbol_or_address, limit }` - `POST /api/get_token_price` — **$0.002** — Real-time token price. - Request: `{ token_address, chain }` - `POST /api/get_balances` — **$0.005** — Wallet token balances. - Request: `{ wallet_address }` - `POST /api/get_portfolio` — **$0.01** — Comprehensive portfolio: balances + DeFi + staking + perps (Avantis & Hyperliquid). - Request: `{ wallet_address }` - `POST /api/analyze_wallet` — **$0.02** — Wallet behavior and risk profile, including perp positions. - Request: `{ wallet_address }` - `POST /api/get_pnl_report` — **$0.015** — Profit and loss over a time window. - Request: `{ wallet_address, time_period }` (e.g. `"30_days"`) ### Trading - `POST /api/get_swap_quote` — **$0.01** — Optimal routing and pricing for a swap. - Request: `{ from_chain, from_token, from_amount, to_chain, to_token, wallet_address, slippage }` - `POST /api/execute_swap` — **$0.02** — Execute on-chain swap. Returns `pipeline_id`. Set `dry_run: true` for simulation. - Request: `{ from_chain, from_token, from_amount, to_chain, to_token, wallet_address, slippage, dry_run }` - `POST /api/create_limit_order` — **$0.05** — Limit order via CoW Protocol. - `POST /api/get_limit_orders` — **$0.002** — View limit orders for a wallet. - `POST /api/cancel_limit_order` — **$0.01** — Cancel a pending limit order. ### Perpetual Trading Supported venues: Avantis (Base) and Hyperliquid. - `POST /api/get_available_perp_pairs` — **$0.001** — List tradable pairs. - Request: `{ provider? }` - `provider` (optional): `avantis` (Avantis), `hyperliquid` (Hyperliquid), or `all` (default) to query across both. - `POST /api/get_perp_positions` — **$0.002** — Open positions for a wallet. - `POST /api/get_perp_details` — **$0.002** — Hyperliquid market details for a token. - `POST /api/open_perp_position` — **$0.05** — Open a perp position (returns pipeline). - `POST /api/close_perp_position` — **$0.05** — Close a perp position (returns pipeline). ### Prediction Markets (Polymarket) Polymarket trading needs no credential setup step. Pass your EOA as `wallet_address`; the deposit wallet is derived server-side, and the pipeline deploys it, sets trading approvals, and derives CLOB credentials automatically on the first order. Fund the deposit wallet with pUSD before placing buy orders — underfunded buys are rejected. - `POST /api/polymarket_search_markets` — **$0.002** — Keyword search. - `POST /api/polymarket_advanced_search` — **$0.002** — Search with date range filters. - `POST /api/polymarket_user_status` — **$0.002** — Account status, deposit wallet, balances, allowances. - `POST /api/polymarket_user_data` — **$0.005** — User positions, trades, open orders. - `POST /api/create_polymarket_v2_order` — **$0.05** — Place an order via pipeline. Params: `wallet_address` (EOA), `market_id`, `token_id`, `side` (`buy`/`sell`), `price` (0.0–1.0 per share), `size` (USD, min 1), `neg_risk` (optional, backend overrides from the live order book), `dry_run` (optional, defaults to `true`). ### Staking & Yield - `POST /api/get_stake_balances` — **$0.005** — Staking positions. - `POST /api/get_yield_suggestions` — **$0.02** — Yield opportunity discovery. - `POST /api/get_yield_portfolio` — **$0.02** — Active yield farming positions for a wallet. Filters: `tokens`, `chains`, `min_apy`, `max_risk` (`low`/`medium`/`high`), `yield_types` (`staking`/`liquid-staking`/`vault`/`lending`/`farming`/`liquid-restaking`), `yield_ids`. ### Airdrop - `POST /api/check_airdrop` — **$0.002** — Check ELSA airdrop eligibility / allocation. - `POST /api/claim_airdrop` — **$0.001** — Claim ELSA airdrop tokens. ### Transaction Management - `POST /api/get_transaction_history` — **$0.003** — Wallet tx history. - `POST /api/get_transaction_status` — **$0.001** — Pipeline status by `pipeline_id`. - `POST /api/submit_transaction_hash` — **$0.005** — Submit a signed tx hash to advance a pipeline. - Request: `{ task_id, tx_hash, status }` - `POST /api/submit_typed_data_signature` — **$0.005** — Submit an EIP-712 typed data signature to advance a pipeline (used for off-chain order submission flows like Polymarket and CoW). - `POST /api/get_gas_prices` — **$0.001** — Current Base gas prices. ### Free Endpoints - `GET /health` — Server health check (no payment required). ## MCP Integration The same tools are exposed via MCP for use in AI assistants. The MCP server lives at `~/www/elsa-x402-mcp-server`. Tool definitions: - Read-only tools: `src/mcp/tools/query.ts` - Execution tools: `src/mcp/tools/trading.ts` Default prices: `src/shared/config.ts`. HTTP routes and dual-payment registration: `src/api/server.ts` (search for `registerDualPaymentEndpoint`). A Claude skill named **`elsa-openclaw`** (see https://x402.heyelsa.ai/openclaw) wraps every MCP tool with an `elsa_` prefix — e.g. `polymarket_search_markets` → `elsa_polymarket_search_markets`. ## References - X402 protocol: https://www.x402.org · https://github.com/coinbase/x402 - Coinbase Developer Platform: https://docs.cdp.coinbase.com · https://portal.cdp.coinbase.com - Base network: https://base.org · https://docs.base.org · https://basescan.org - Model Context Protocol: https://modelcontextprotocol.io · https://github.com/modelcontextprotocol - Examples repo: https://github.com/HeyElsa/elsa-x402-examples - Support: x402@heyelsa.ai