> ## Documentation Index
> Fetch the complete documentation index at: https://docs.useotto.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Otto X Storefront

> Technical guide for accessing Otto's 42 X Layer endpoints via x402, OKX Onchain OS, and TEE-custodied sub-wallets.

Otto X brings the Otto AI agent swarm to the X Layer ecosystem. Same x402 thesis — pay per call, no API keys, payment IS the authentication — now settling on X Layer mainnet via OKX's Onchain OS infrastructure.

**Base URL:** `https://xlayer.ottoai.services`

**Chain:** X Layer Mainnet (Chain ID: 196)

**Payment:** Micro-payments on X Layer via the OKX Facilitator — pay service fees in **USDT0, USDG, or USDC** (see `GET /tokens` for the full token registry).

**Listed on OKX:** Otto X is reachable from OKX's Onchain OS at [okx.ai/agents/2118](https://okx.ai/agents/2118).

**Discovery:**

* [Landing Page](https://xlayer.ottoai.services) — interactive endpoint explorer
* [LLM Docs](https://xlayer.ottoai.services/llm.txt) — machine-readable for AI agents
* [Discovery Doc](https://xlayer.ottoai.services/.well-known/x402) — x402 discovery document
* [GitHub](https://github.com/useOttoAI/otto-x) — open source

**Sister surfaces (overlapping agent catalog, different rails):** [x402](/acp-swarm/x402) (USDC on Base/Polygon/Solana) · [USDC / Circle Gateway](/acp-swarm/usdc) (gasless batched USDC) · [MPP](/acp-swarm/mpp) (IETF M2M / Stripe). See [Access Paths & Coverage](/acp-swarm/storefront-parity) for current counts and capability coverage.

## How It Differs from x402.ottoai.services

|                   | **x402.ottoai.services**   | **xlayer.ottoai.services**                        |
| ----------------- | -------------------------- | ------------------------------------------------- |
| **Chain**         | Base, Polygon, Solana      | X Layer (196)                                     |
| **Facilitator**   | CDP (Coinbase)             | OKX Facilitator                                   |
| **Payment Token** | USDC                       | Native X Layer payments                           |
| **SDK**           | `@x402/express` (Coinbase) | `@okxweb3/x402-express` (OKX)                     |
| **Endpoints**     | 74                         | 42                                                |
| **Focus**         | Full agent swarm           | DEX + market intel + AI tools + trading resources |

Both deployments serve the same underlying agent intelligence. Otto X adds X Layer-native DeFi endpoints (swap quotes, token pricing, approvals) powered by OKX DEX Aggregator.

## OKX Onchain OS Usage

| Module                                                                            | How It's Used                                                                                        |
| --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| **x402 SDK** (`@okxweb3/x402-express`, `@okxweb3/x402-evm`, `@okxweb3/x402-core`) | Payment middleware gating all 42 paid endpoints via `OKXFacilitatorClient` on X Layer                |
| **DEX Aggregator API v6**                                                         | HMAC-authenticated calls for swap quotes, token pricing, registry, and ERC-20 approvals on chain 196 |
| **Agentic Wallet**                                                                | Project on-chain identity (`0xa3db6825de8222e9f8bac136eeb2f65d49a88fcf`)                             |
| **OKX API Auth**                                                                  | HMAC-SHA256 request signing for all DEX interactions                                                 |

## Pricing Overview

### X Layer DEX Endpoints

| Endpoint                            | Price   | Description                                                |
| ----------------------------------- | ------- | ---------------------------------------------------------- |
| `POST /swap`                        | \$0.01  | DEX swap quotes + unsigned calldata via OKX DEX Aggregator |
| `GET /market-alpha`                 | \$0.005 | Live token pricing derived from on-chain DEX quotes        |
| `GET /price?token=0x...`            | \$0.002 | Single token USD price via DEX quote                       |
| `GET /all-tokens`                   | \$0.002 | All tokens supported on X Layer DEX                        |
| `GET /approve?token=0x...&amount=N` | \$0.005 | ERC-20 approval calldata for DEX router                    |

### Market Intelligence

| Endpoint                            | Price   | Description                                                                             |
| ----------------------------------- | ------- | --------------------------------------------------------------------------------------- |
| `GET /crypto-news`                  | \$0.001 | Real-time crypto news with sentiment analysis                                           |
| `GET /token-alpha?symbol=BTC`       | \$0.001 | Premium token intelligence — news, sentiment, futures                                   |
| `GET /kol-sentiment`                | \$0.001 | Aggregated sentiment from top 50 crypto KOLs                                            |
| `GET /trending-altcoins`            | \$0.001 | Top 3 trending altcoins with analysis                                                   |
| `GET /mega-report`                  | \$0.05  | Alpha & Intel Report — comprehensive daily market briefing                              |
| `GET /token-security?address=0x...` | \$0.001 | Token contract security audit                                                           |
| `GET /funding-rates?symbol=BTC`     | \$0.001 | Derivatives funding rates & open interest                                               |
| `GET /defi-analytics?protocol=aave` | \$0.001 | DeFi protocol analytics                                                                 |
| `GET /filtered-news?topic=DeFi`     | \$0.001 | AI-filtered news by topic (DeFi, NFTs, Layer2, etc.)                                    |
| `GET /twitter-summary`              | \$0.001 | Curated crypto Twitter/X digest from top KOLs                                           |
| `GET /token-details?symbol=BTC`     | \$0.001 | Token price, market cap, 24h change                                                     |
| `GET /yield-alpha`                  | \$0.001 | Top DeFi yield opportunities across chains                                              |
| `GET /tradfi-data?symbol=SPY`       | \$0.001 | TradFi macro intelligence — indices, VIX, DXY, yields (omit symbol for macro dashboard) |

### AI Tools

| Endpoint                                    | Price  | Description                                                     |
| ------------------------------------------- | ------ | --------------------------------------------------------------- |
| `GET /generate-meme?prompt=...`             | \$0.15 | Multi-model image gen via fal.ai (GPT Image 2, Nano Banana Pro) |
| `GET /llm-research?prompt=...`              | \$0.10 | AI research assistant with web search                           |
| `GET /tx-explainer?txHash=0x...&chain=base` | \$0.01 | Decode & explain EVM transactions across 11 chains              |

### Trading Resources

Read-only data sourced directly from Otto X's own libs — Zerion for portfolios, vaults.fyi for yield positions, DeFi Llama for yield markets, Hyperliquid info endpoint for perps data. Wallet-scoped reads default to **your** Otto X sub-wallet (resolved from your x402 payer); pass `?address=0x...` to query any other EVM address.

| Endpoint                                         | Price   | Description                                                                                                                                                                                                                                    |
| ------------------------------------------------ | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /portfolio`                                 | \$0.001 | Multi-chain token balances for your Otto X sub-wallet (or `?address=`)                                                                                                                                                                         |
| `GET /supported-tokens?chainId=8453&search=USDC` | \$0.001 | Search tokens by symbol on a given chain (CoinGecko registry)                                                                                                                                                                                  |
| `GET /hyperliquid-account`                       | \$0.001 | Hyperliquid perpetual futures account + open positions                                                                                                                                                                                         |
| `GET /hyperliquid-market?asset=BTC`              | \$0.001 | Perpetual market data + mark prices (omit asset for top-20 by leverage)                                                                                                                                                                        |
| `GET /hl-transaction-history`                    | \$0.001 | Recent Hyperliquid fills. Optional `?limit=` (default 50, max 200)                                                                                                                                                                             |
| `GET /yield-markets`                             | \$0.001 | Available yield markets via DeFi Llama (filterable by `protocol`, `chainId`, `tokenSymbol`)                                                                                                                                                    |
| `GET /yield-farming-active`                      | \$0.001 | Active yield positions via vaults.fyi — Otto-allowlisted lending positions also get a rebalance recommendation (current APY vs. the highest-rated allowlisted protocol alternative + the action calls to switch) and a portfolio yield summary |
| `GET /yield-farming-historical`                  | \$0.001 | Yield op history — deposit/redeem timeline with exact \$0.05-per-op Otto fees, exact realized yield/APY per closed round-trip, and a totals summary                                                                                            |
| `GET /idle-capital`                              | \$0.001 | Detect undeployed tokens that could earn yield                                                                                                                                                                                                 |
| `GET /yield-recommendations`                     | \$0.001 | Personalized vault recs based on your idle balances                                                                                                                                                                                            |

### Agentic Wallet V2 — Autonomous DeFi Execution

Otto X provisions a TEE-custodied sub-wallet for each x402 payer and executes swaps, bridges, and DeFi deposits on their behalf — all signed inside OKX's TEE, no user-side key management.

| Endpoint                            | Price   | Description                                                                                                                                                                                                                                            |
| ----------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `GET /sub-wallet`                   | \$0.01  | Resolve or provision your payer-bound Otto X sub-wallet. Identity comes from your x402 payment signature — there is no `?address=` parameter, and one would be ignored. For a free lookup of any address, use `GET /sub-wallet/preview?address=0x...`. |
| `POST /auto-swap`                   | \$0.05  | In-chain swap via OKX DEX aggregator (500+ sources, 20 chains). Accepts `principalAuth` for one-call UX.                                                                                                                                               |
| `POST /auto-bridge`                 | \$0.05  | Cross-chain bridge via OKX (Stargate / Across / Relay / Gas.zip, 17 chains). Accepts `principalAuth`.                                                                                                                                                  |
| `POST /auto-defi-invest`            | \$0.05  | Deposit into allowlisted DeFi protocol (Aave V3, Lido, Compound V3, Morpho). Accepts `principalAuth`.                                                                                                                                                  |
| `POST /auto-defi-withdraw`          | \$0.05  | Redeem an active DeFi position                                                                                                                                                                                                                         |
| `POST /yield-copilot`               | \$0.05  | **One-call yield** — deploy idle stablecoins into the highest-APY Otto-allowlisted lending venue (Aave V3 / Compound V3 / Morpho) on Base, Arbitrum, Optimism, Ethereum, or X Layer. Accepts `principalAuth`; returns a before/after artifact.         |
| `POST /yield-watch`                 | \$0.001 | **Yield Watch** — register for notify-only alerts OR a 30-day signed delegation for autonomous Aave↔Compound rebalances. See [Yield Watch](#yield-watch--post-delete-get-yield-watch) below.                                                           |
| `DELETE /yield-watch`               | \$0.001 | Revoke the auto delegation (or pause notify mode). Signed-revoke (EIP-712) for `auto`; chat-id auth for `notify`.                                                                                                                                      |
| `GET /yield-watch`                  | \$0.001 | Inspect your current subscription (mode, scope, signed caps, next nonce, move count, paused state).                                                                                                                                                    |
| `GET /yield-watch/audit`            | \$0.001 | Read your audit trail — register/revoke/observation/alert/auto-move-started/-succeeded/-failed events with tx hashes.                                                                                                                                  |
| `POST /auto-withdraw`               | \$0.05  | **Escape hatch** — sweep funds from your sub-wallet to any external address                                                                                                                                                                            |
| `GET /supported-protocols`          | free    | Catalog of allowlisted protocol × chain × token combinations                                                                                                                                                                                           |
| `GET /defi-positions?address=0x...` | free    | Active DeFi positions for a sub-wallet                                                                                                                                                                                                                 |

### Yield Watch

| Endpoint                 | Price   | Description                                              |
| ------------------------ | ------- | -------------------------------------------------------- |
| `POST /yield-watch`      | \$0.001 | Register or update notify/auto yield monitoring policy   |
| `DELETE /yield-watch`    | \$0.001 | Revoke an active yield-watch subscription                |
| `GET /yield-watch`       | \$0.001 | Read the caller's current yield-watch subscription state |
| `GET /yield-watch/audit` | \$0.001 | Read the caller's yield-watch audit trail                |

**Allowlisted protocols:**

| Protocol        | Chains                                               |
| --------------- | ---------------------------------------------------- |
| **Aave V3**     | Base, Arbitrum, Optimism, Polygon, Ethereum, X Layer |
| **Lido**        | Ethereum                                             |
| **Compound V3** | Base, Arbitrum, Ethereum                             |
| **Morpho**      | Base, Ethereum                                       |

All four protocols × every chain in the table are reachable: each of those chains is in the gas-top-up + execution registry. (Lido is ETH staking on Ethereum, not a stablecoin venue.)

**`principalAuth` launch chains (USDC EIP-3009):** Base, Arbitrum, Optimism, Ethereum, Polygon. Plus X Layer (USDT0). Other chains still work via the legacy 409 funds-required fallback — see below. On Ethereum, ops are declined during a base-fee spike (above \~25 gwei) rather than subsidizing it.

Expansion requires mainnet validation of a full deposit→withdraw cycle before a new protocol is added.

### Yield Copilot — `POST /yield-copilot`

One call deploys your idle stablecoin capital into yield:

```bash theme={null}
POST /yield-copilot
{ "chain": "base", "token": "USDC" }          # deploys your full idle USDC balance
# or
{ "chain": "optimism", "token": "USDC", "amount": "500", "principalAuth": { ... } }
```

* **What it does:** reads your Otto X sub-wallet's idle balance of the requested stablecoin, picks the lending venue — the **highest current APY** among the Otto-allowlisted lending protocols (Aave V3, Compound V3, Morpho) for that stablecoin on that chain, sourced from **vaults.fyi** (Base / Arbitrum / Optimism / Ethereum) with the **DeFi Llama** yields API as fallback (the `apy_source` field in the response says which was used) — and supplies it via the same path `/auto-defi-invest` uses. Accepted stablecoins are those in the allowlist for that chain (USDC, USDT, USDT0, USDG, USDC.e, DAI as applicable). Omit `amount` to deploy the entire idle balance; supply `principalAuth` to fund the sub-wallet in the same call — `principalAuth` funding currently supports **USDC** on Base/Arbitrum/Optimism/Ethereum/Polygon and **USDT0** on X Layer, and its `value` must equal the deposit amount exactly.
* **Scope:** Base, Arbitrum, Optimism, Ethereum, X Layer. (X Layer has no public APY feed yet, so on X Layer the response reports the venue with `apy: null` and points you to `GET /yield-farming-active` for the live rate. On Ethereum, the call is declined during a base-fee spike — above \~25 gwei — rather than subsidizing it.) If a stablecoin has several allowlisted venues on a chain and the APY feed is unavailable, Otto returns `503 APY_DATA_UNAVAILABLE` rather than guessing — pick the venue yourself via `/auto-defi-invest`.
* **The response is the artifact:** `before` (idle amount, 0% APY) → `after` (venue, APY, illustrative annualized + monthly yield at the current rate) → `economics` (\$0.05 Otto fee, APY delta) → `custody` (your payer-bound sub-wallet, withdraw endpoints) → `selection` (why this venue, APY source, TVL, pool id) → `tx_hashes` → a `not_investment_advice` disclaimer.
* **What Otto provides:** automation + transparency + non-custody + a \$0.05 fee — **not** "earning power" or guaranteed returns. APYs float; deployed capital carries smart-contract, liquidity, and market risk. Otto never pools or rehypothecates user funds; withdraw the position anytime via `POST /auto-defi-withdraw`, or sweep the whole sub-wallet via `POST /auto-withdraw`.

### Yield Watch — `POST /yield-watch` (notify) / `POST /yield-watch` (auto) / `DELETE /yield-watch` / `GET /yield-watch` / `GET /yield-watch/audit`

Tier 3 of the yield ladder: instead of polling `/yield-farming-active` yourself, register once and let Otto watch your positions and either **notify** you via Telegram when there's a better venue, or **auto-rebalance** under a 30-day signed delegation.

Two modes — the same endpoint, the body distinguishes:

**Notify mode** (no on-chain delegation, no spending limits — Otto just sends a Telegram receipt when a sustained APY gap opens, including the copy-pasteable two-call switch):

```bash theme={null}
POST /yield-watch
{
  "mode": "notify",
  "telegramChatId": "1234567890",
  "chainIds": [8453, 42161],
  "tokens": ["USDC"],
  "protocols": ["aave_v3", "compound_v3", "morpho"],
  "hysteresisPctBps": 50,    # require ≥0.50pp APY gap before alerting
  "hysteresisHours": 6,       # for ≥6 sustained hours
  "throttleHours": 72,        # at most one alert per position per 72h
  "minHoldDays": 7            # don't alert on positions <7 days old
}
```

**Auto mode** (signed EIP-712 delegation — Otto will rebalance Aave↔Compound on your behalf, capped by `maxMoves` over 30 days and `maxPrincipalRaw` per move, every move audited + receipted to Telegram):

```bash theme={null}
POST /yield-watch
{
  "mode": "auto",
  "telegramChatId": "1234567890",
  "signature": "0x...",
  "message": {
    "wallet":            "0xYOUR_WALLET",
    "subWallet":         "0xYOUR_SUB_WALLET",
    "mode":              "auto",
    "chainIds":          [8453],
    "tokens":            ["USDC"],
    "protocols":         ["aave_v3", "compound_v3"],
    "hysteresisPctBps":  50,
    "hysteresisHours":   6,
    "throttleHours":     72,
    "minHoldDays":       7,
    "maxMoves":          10,
    "maxPrincipalRaw":   "0",          # 0 = no per-move cap; positive = raw token units
    "nonce":             0,
    "issuedAt":          1716158400,
    "expiry":            1716763200
  }
}
```

**Signing the delegation.** The client signs an EIP-712 `YieldDelegation` message over a fixed domain (`OttoXYieldWatch` v1 — a pure off-chain authority bound to the wallet, sub-wallet, and nonce). For the full domain, typed-data structure, and a copy-paste `signTypedData` recipe (plus the `RevokeYieldDelegation` flow), see the [Otto X repo](https://github.com/useOttoAI/otto-x).

Server verifies the signature with viem's `recoverTypedDataAddress` and binds it to the registered `wallet`. The delegation is **atomically claimed** via a single-statement CAS on `next_nonce` — concurrent registrations from the same wallet can't replay each other, and a revocation always bumps the nonce so a stale signed message can't replay after revoke. Auto-mode revocation signs `RevokeYieldDelegation` with the current `nonce`; notify mode just sends a `DELETE` (chat-id ownership is the auth).

**Guardrails (auto mode):**

* **Allowlist:** Aave V3 and Compound V3 only for v1. Morpho is rejected at registration (vault-address coupling lands in v1.1).
* **TVL floor + APY staleness:** an alt protocol must have ≥ \$10M TVL and an APY data point ≤ 2h old before it can win a move.
* **Hysteresis state machine:** the alt must beat the current venue by `hysteresisPctBps` *sustained* for `hysteresisHours` straight (the worker tracks per-position observations; a regression resets the window).
* **Throttle:** at most one move per position per `throttleHours` window (default 72h) — bounds gas + Otto-fee spend.
* **`maxMoves`:** a hard cap over the 30-day delegation window. After the cap, the worker refuses further moves on that wallet.
* **`maxPrincipalRaw`:** a per-move notional cap in raw token units (e.g. `"5000000"` = \$5 USDC at 6 decimals). `"0"` = no cap. **Cap is bound to the LIVE position size at lock time**, so a mid-window top-up over the cap is refused.
* **Pre-broadcast resolver guards:** both the current and the best-alt market must resolve cleanly via OKX, and must point at the SAME canonical token address (no `USDC → USDC.e` routing, no surprise asset substitution). Refusals at this stage never pay the audit cost.
* **Post-broadcast verification:** every leg (withdraw + invest) is followed by `assertReceiptsConfirmed` — a hard check that the broadcast tx hash actually landed on-chain. Defends against the OKX silent-drop bug pattern (`{ok:true, txHash}` returned but the relayer's simulate reverted and dropped the broadcast).
* **Per-phase failure receipts:** if any leg fails, the Telegram receipt names the specific phase (`withdraw` / `verification_withdraw` / `invest` / `verification_invest`) and a recovery CLI tailored to where the funds are (still in the old protocol vs idle in your sub-wallet).
* **Synthetic ledger close-out:** a successful auto-move writes `(auto_defi_withdraw, yield_copilot)` rows to your `otto_x_ops` ledger so the next tick sees the OLD protocol closed + NEW open, and `/yield-farming-historical` treats the move as a realized round-trip for the closed deposit.

**Status reads:**

```bash theme={null}
GET  /yield-watch                 # current subscription, paused flag, nextNonce, moveCount, signed scope
GET  /yield-watch/audit?limit=50  # full event trail: registered/revoked/observation_started/notify_alert/auto_move_started/auto_move_succeeded/auto_move_failed
```

The audit trail is the source of truth for "what did Otto do for me?" — every entry carries tx hashes (where applicable) and the resolved investment IDs, so a user can reproduce any move on-chain.

**Pricing:** all four endpoints are paywalled at \$0.001 (registration / revocation / status / audit are bookkeeping; the value is the moves themselves which carry the standard \$0.05 fee per leg via the underlying `/auto-defi-withdraw` + `/yield-copilot` calls Otto runs internally — same as a user-initiated rebalance).

**Launch posture:** Tier 3 launches **Base USDC Aave ↔ Compound V3** first, with Morpho-on-Base and multi-chain (Arbitrum / Optimism / Ethereum / X Layer) auto support landing in v1.1 once each chain has soaked a manual deposit + withdraw cycle on mainnet.

### Yield status & receipts — `GET /yield-farming-active`, `GET /yield-farming-historical`

* **`GET /yield-farming-active`** lists your active yield positions and, for each **Otto-allowlisted lending position** (Aave V3 / Compound V3 / Morpho stablecoin lending on Base / Arbitrum / Optimism / Ethereum / X Layer), adds a rebalance picture: `current_apy_pct` vs. `best_alternative` (the highest-rated allowlisted **protocol** for that stable on that chain — the APY is a *protocol-level* figure, since OKX picks the actual deposit market; it is never "the best vault is X"), `apy_delta_pts`, `projected_annual_uplift_usd`, and a `recommendation` of `rebalance` or `hold` with a plain-English `why`. A `rebalance` is suggested only when the gap clears both a minimum APY-delta and a minimum projected \$/yr bar **and** you've held the position past a cooldown — it won't nag you to chase rate noise. When you read your *own* sub-wallet, a `rebalance` recommendation includes the two-call switch: `POST /auto-defi-withdraw {protocol, chain, token, ratio:"1"}` then `POST /yield-copilot {chain, token}` (Otto re-picks the best venue at execution time, and the redeemed funds redeploy in full). The response also carries a `yield_summary` (total deployed, weighted-avg APY, projected annual yield, rebalances recommended).
* A rebalance is **informational** — the new rate is not locked, switching protocols carries smart-contract/migration risk, you pay 2 × \$0.05 in Otto fees (Otto absorbs the on-chain gas), and if the redeploy leg fails your funds simply sit idle in your own sub-wallet (re-call `POST /yield-copilot`). Not investment advice.
* **`GET /yield-farming-historical`** is the receipt: your full yield-op `timeline` (deposits via `/auto-defi-invest` & `/yield-copilot` + redemptions via `/auto-defi-withdraw`) with the **exact** $0.05 Otto fee per op and tx hashes. Each full redemption carries a `realized` block — `realized_yield_usd` and `realized_apy_pct` computed **exactly** (the on-chain amount that actually came back to your sub-wallet, minus what you deposited; APY annualized over the holding period) for positions whose deposit(s) Otto recorded; a `null` `realized` with a `reason` means it couldn't be attributed cleanly (e.g. partial withdrawal, position funded externally, or it pre-dates the redeemed-amount instrumentation). The `summary` adds `realized_yield` (lifetime realized $, # closed round-trips with a realized figure) alongside the exact total Otto fees. For *current* rates use `GET /yield-farming-active`.

### Custody Model (Important)

Otto X's Agentic Wallet is **TEE-custodial**, not self-custodial:

* Keys are generated and held inside OKX's Trusted Execution Environment (TEE). Otto AI holds an API credential that authorizes signing; neither Otto nor OKX staff can export the underlying key.
* Users do **not** control their sub-wallet directly. There is no seed phrase to back up, no MetaMask connection, no co-signer role.
* This trades away the confirm-and-withdraw control of Otto AI's Safe-based Trade Execution Agent — where you sign funding and withdrawals while an Otto-managed key signs execution — in exchange for fully autonomous execution (no user signing, no gas management, atomic operations).
* `POST /auto-withdraw` is the escape hatch: users can sweep any token balance to any external address at any time. No approvals, no holds.
* Otto runs an hourly GC that flags inactive empty sub-wallets to prevent capacity squat.

This posture is specific to Otto X on X Layer. Otto AI's other agents differ: Market Alpha and Tools are read-only intelligence (they never touch your funds); Trade Execution runs on an **agent-custodial** Safe today (the non-custodial [Safe7579](/introduction/safe7579-architecture) model is rolling out in gated early access); and Prediction Markets trades via a dedicated Safe + Dynamic vault.

#### Aligned with Agent Payments Protocol §8.4

This split — funded wallet off the per-action signing path, hot key in the TEE for autonomous execution — is exactly the architecture OKX's [Agent Payments Protocol whitepaper](https://www.okx.com/en/wallet/onchain-os) (§8.4 *Separating signing from custody*) describes for production agent commerce. Otto X has been running this design on mainnet since March 2026, ahead of the protocol's public release. Once the APP wire-format spec is published, Otto X sub-wallets are a drop-in Buyer-Agent runtime for `charge`, `session`, and `upto` intents.

### One-Call Flow via EIP-3009 `principalAuth` (recommended)

Recent clients collapse the old two-step funds-required dance into a single HTTP call by including a signed EIP-3009 `TransferWithAuthorization` note in the request body. The server verifies it, pulls your USDC (or USDT0 on X Layer) directly into your sub-wallet on-chain, then executes the op — all in one response.

**Client-side recipe:**

1. **One-time preview** — `GET /sub-wallet/preview?address=0xYOUR_WALLET` (free). Cache `sub_wallet.evm_address` indefinitely; it's deterministic per payer. (The unsuffixed `GET /sub-wallet` is the paid \$0.01 resolve-or-provision route and will answer a free call with a 402.)

2. **Sign two things** — your wallet signs:
   * The x402 service fee (standard paywall, \$0.05 USDT0 on X Layer → Otto treasury).
   * An EIP-3009 `TransferWithAuthorization` note authorizing your USDC on the target chain to flow into your sub-wallet. Modern wallets (MetaMask, Coinbase Wallet, Rabby, Phantom) can batch both into one confirmation screen.

3. **POST the op** — include `principalAuth` in the body:

```json theme={null}
{
  "fromToken": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
  "toToken":   "0x4200000000000000000000000000000000000006",
  "amount":    "10",
  "chain":     "base",
  "principalAuth": {
    "from":        "0xYOUR_WALLET",
    "to":          "0xYOUR_SUB_WALLET",
    "value":       "10000000",
    "validAfter":  0,
    "validBefore": 1776973646,
    "nonce":       "0x...",
    "signature":   "0x..."
  }
}
```

Sent with the x402 fee in `PAYMENT-SIGNATURE`.

**Server guarantees, verified before touching the chain:**

* `principalAuth.from` MUST equal your x402 payer (no impersonation).
* `principalAuth.to` MUST equal your provisioned sub-wallet (no draining to attacker addresses).
* `principalAuth.value` MUST be ≥ the op's required amount.
* `validBefore` MUST be in the future; `nonce` MUST be unseen (replay-safe via a per-signer-per-token-per-nonce DB claim + on-chain `authorizationState` check).

The server then broadcasts `token.transferWithAuthorization(...)` (operator pays gas, user funds move straight from their wallet to their sub-wallet — no intermediate custody), tops up the sub-wallet with dust native gas if needed, executes the op, and returns 200 with all tx hashes.

### Legacy Flow — HTTP 409 `funds_required` (fallback)

Clients that can't sign EIP-3009 notes, or that target chains we haven't enabled yet, fall back to the two-step flow. `POST /auto-*` without a `principalAuth` and with an insufficient sub-wallet balance returns:

```json theme={null}
{
  "status": "funds_required",
  "code": "FUNDS_REQUIRED",
  "idempotency_key": "a1b2c3...",
  "retry_after_deposit": true,
  "deposit": {
    "deposit_address": "0xYourSubWallet...",
    "required_amount": "50",
    "token": "USDC",
    "chain": "base"
  },
  "instructions": "Deposit 50 USDC to this address on Base, then retry with header 'idempotency-key: a1b2c3...'. Your x402 payment for this attempt was NOT charged."
}
```

**Because the status is ≥ 400, x402 skips settlement — you're NOT charged for the funds-required response.** Only successful execution settles the service fee.

The same idempotency key can be reused for up to 7 days to re-submit the original intent once funds arrive. Re-submitting the same body with a fresh key returns the same op (dedup on payer + op type + body hash).

### Free Endpoints

| Endpoint                                | Description                                                                                                                                                            |
| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /`                                 | Landing page + JSON service discovery                                                                                                                                  |
| `GET /health`                           | Service health check                                                                                                                                                   |
| `GET /tokens`                           | Curated token registry (16 tokens)                                                                                                                                     |
| `GET /llm.txt`                          | AI-readable service catalog                                                                                                                                            |
| `GET /.well-known/x402`                 | x402 discovery document                                                                                                                                                |
| `GET /openapi.json`                     | OpenAPI 3.1 description — method, request body and price for every endpoint                                                                                            |
| `GET /sub-wallet/preview?address=0x...` | Read-only lookup of the sub-wallet EVM address. Never provisions. (`GET /sub-wallet` is the **paid** \$0.01 resolve-or-provision route — see the pricing table above.) |
| `GET /supported-protocols`              | DeFi allowlist catalog                                                                                                                                                 |
| `GET /defi-positions?address=0x...`     | Active DeFi positions (public on-chain read)                                                                                                                           |

## x402 Payment Flow (OKX)

The flow is the same as our Base/Polygon deployment, but settlement happens on X Layer via OKX Facilitator instead of CDP Facilitator.

```
1. Send request  →  GET /crypto-news
2. Get 402       ←  Payment Required ($0.001, X Layer)
3. Pay on-chain  →  Transfer on X Layer mainnet (chain 196)
4. Retry + proof →  GET /crypto-news + payment header
5. Verified      →  OKX Facilitator confirms payment
6. Get data      ←  News report with sentiment
```

## Token Registry

Otto X maintains a curated registry of 16 X Layer tokens, available for free at `GET /tokens`.

| Category        | Tokens                               |
| --------------- | ------------------------------------ |
| **Native**      | OKB                                  |
| **Stablecoins** | USDT, USDG, USDC, USDe, frxUSD       |
| **Wrapped**     | WETH, WOKB, XBTC, XETH, XSOL, XOKSOL |
| **DeFi**        | sUSDe, rsETH, LINK                   |
| **Meme**        | XDOG                                 |

The paid `GET /all-tokens` endpoint returns the full list from OKX DEX Aggregator (100+ tokens).

## Quick Start

```bash theme={null}
# Health check (free)
curl https://xlayer.ottoai.services/health

# Token registry (free)
curl https://xlayer.ottoai.services/tokens

# AI-readable catalog (free)
curl https://xlayer.ottoai.services/llm.txt

# Paid endpoint (returns 402 with payment instructions)
curl https://xlayer.ottoai.services/crypto-news
```

For a full client example showing discovery and the 402 payment flow, see [examples/client.ts](https://github.com/useOttoAI/otto-x/blob/master/examples/client.ts) in the GitHub repo.

## Roadmap

* **`principalAuth` chain expansion:** add Ethereum, Optimism, Avalanche, BSC for EIP-3009 one-call flows once on-chain gas economics justify it
* **Onchain OS One-Time / Batch Payment for principal on X Layer:** reroute the principal leg through the OKX Payment protocol so the user's principal transfer itself is zero-gas (today only the service fee is); offer `aggr_deferred` scheme on high-frequency reads so AI-agent hot loops can batch-settle signatures via TEE
* **Agentic Wallet allowlist expansion:** broaden beyond Aave / Lido / Compound / Morpho once each new protocol clears mainnet validation; add BSC, Avalanche, and Solana DeFi integrations
* **Yield ladder:** `POST /yield-copilot` (Tier 1, live) deploys idle stablecoins into the highest-APY allowlisted lending venue in one call. Tier 2 (live, read-side): `GET /yield-farming-active` rebalance recommendations + the `GET /yield-farming-historical` op receipt — including **exact** realized yield/APY per closed round-trip. Tier 3 (live): `POST /yield-watch` — opt-in notify-only alerts OR a 30-day signed EIP-712 delegation for autonomous Aave↔Compound rebalances, with hard guardrails (TVL floor + APY staleness + hysteresis + minimum-hold + per-position throttle + signed `maxMoves`/`maxPrincipalRaw` caps + post-broadcast verification + per-phase failure receipts).
* **Earn-pay-earn loops:** Agents earn via x402, pay for intelligence via x402, compound returns through Otto X — all on X Layer
* **OKX Onchain OS Skills integration:** Publishing Otto services as first-class skills so Claude Code / Cursor / Codex CLI users can discover and pay for Otto intelligence natively
* **Hyperliquid perps via Agentic Wallet:** extend beyond OKX's DeFi catalog by wiring `wallet contract-call` against Hyperliquid's contracts for TP/SL-capable perp execution from the same sub-wallet
* **Multi-master sharding:** scale beyond 50 sub-wallets per OKX master by sharding across multiple execution masters with deterministic routing
