{
  "openapi": "3.1.0",
  "info": {
    "title": "swap — DEX meta-aggregator API",
    "version": "1.0.0",
    "summary": "Stateless quote / route / build endpoints behind swap.9summits.io and the local `swap` server.",
    "description": "Every endpoint is stateless: each call carries its full inputs, nothing is cached server-side, and `quoteId` is a client-side round key only. Amounts are **base units as decimal strings** (e.g. `\"1000000\"` for 1 USDC), never floats. Native gas token is the sentinel address `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee`. The public host applies a per-IP token bucket per minute: `quote` bucket 60 (`/api/quote`, `/api/quote/stream`, `/api/route`, `/api/loop/quote`, `/api/loop/quote/stream`, `/api/loop/unwind/quote`, `/api/loop/unwind/quote/stream`), `build` bucket 12 (`/api/build`, `/assemble`, `/api/loop/build`, `/api/loop/unwind/build`),`submit` bucket 6 (`/submit`), `light` bucket 120 (everything else, including `/api/loop/markets` and `/api/loop/positions`). Exceeding it returns HTTP 429 with a `Retry-After` header and body `{\"error\":\"rate limited, retry shortly\"}`. These calls consume the operator's venue API keys — cache responsibly and prefer the NDJSON stream for multi-venue races. Safety rules: never coerce `decimals` to 18; the ERC-20 approval target is `tx.spender`, not `tx.to`; use the same `slippageBps` for quote and build; never put the quote-only dEaD placeholder in a signed order (CoW stamps the real sender on the reused envelope; other async venues re-quote).",
    "contact": { "name": "9summits", "email": "contact@9summits.io", "url": "https://swap.9summits.io/" },
    "termsOfService": "https://swap.9summits.io/disclaimer.html"
  },
  "security": [],
  "externalDocs": {
    "description": "CLI manual, llms.txt and agent skill",
    "url": "https://swap.9summits.io/docs"
  },
  "servers": [
    { "url": "https://swap.9summits.io", "description": "Public hosted instance (no session gate, rate limited per IP)" },
    {
      "url": "http://127.0.0.1:5151",
      "description": "Local server started by `swap` with no arguments. Gated by `?id=<sid>` (printed at startup) unless the server runs with SWAP_NO_AUTH=1. Uses your own venue keys and RPC."
    }
  ],
  "tags": [
    { "name": "bootstrap", "description": "Capabilities, chains, venues, token lists" },
    { "name": "quote", "description": "Multi-venue quotes, ranked best-first for the active side" },
    { "name": "build", "description": "Executable payloads: tx, EIP-712 order, or Permit2 two-leg" },
    { "name": "browser-flow", "description": "Endpoints used by the wallet page; rarely needed by agents" },
    { "name": "loop", "description": "Morpho Blue leverage loop on Ethereum, Base, Robinhood, Monad and Arc: the 20 fork-tested Ethereum stable markets (fxSAVE, PTs, strUSD, reUSD, PST, PRIME, sUSDe, sUSDai, syrupUSDC) by alias, or any Morpho market id on one of those chains. Plan, then preflight txs + one Bundler3 flash-loan multicall. Same engine as `swap loop`." }
  ],
  "paths": {
    "/api/mode": {
      "get": {
        "tags": ["bootstrap"],
        "operationId": "getMode",
        "summary": "Capabilities: chains, venues, buy-capable venues",
        "description": "Call this first. `venues` is the set enabled on this deployment; `buyVenues` is the subset that supports exact-out (`amountOut`) natively.",
        "responses": {
          "200": { "description": "Mode", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Mode" } } } },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/api/tokens": {
      "get": {
        "tags": ["bootstrap"],
        "operationId": "listTokens",
        "summary": "Curated token list for a chain (native first)",
        "parameters": [{ "$ref": "#/components/parameters/chain" }],
        "responses": {
          "200": {
            "description": "Token list",
            "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/TokenInfo" } } } }
          },
          "429": { "$ref": "#/components/responses/RateLimited" },
          "502": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/api/resolve-token": {
      "post": {
        "tags": ["bootstrap"],
        "operationId": "resolveToken",
        "summary": "Resolve a symbol or 0x address to full token metadata",
        "description": "Use this for any token that is not in `/api/tokens`. Returns real on-chain `decimals`; never guess them.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["chain", "input"],
                "properties": {
                  "chain": { "$ref": "#/components/schemas/ChainAlias" },
                  "input": { "type": "string", "description": "Symbol (case-insensitive) or 0x address", "examples": ["WBTC", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"] }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Resolved token", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/TokenInfo" } } } },
          "400": { "$ref": "#/components/responses/Error" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/api/quote": {
      "post": {
        "tags": ["quote"],
        "operationId": "quote",
        "summary": "Race venues, return ranked quotes (one JSON object)",
        "description": "Exactly one of `amountIn` (sell / exact-in) or `amountOut` (buy / exact-out) must be set. With `amountOut` only buy-capable venues participate natively. No wallet is needed. Ranking is by the variable leg (gross of gas); each route carries `gasUnits` / `gasPriceWei` so a client can re-rank net of gas.",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/QuoteRequest" } } } },
        "responses": {
          "200": { "description": "Ranked quotes", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/QuoteResponse" } } } },
          "400": { "$ref": "#/components/responses/Error" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/api/quote/stream": {
      "post": {
        "tags": ["quote"],
        "operationId": "quoteStream",
        "summary": "Same as /api/quote, streamed as NDJSON while venues settle",
        "description": "Preferred for multi-venue races. One JSON object per line: a `meta` line first, then one `route` or `verror` line per venue in settlement order (unsorted), then `done`. A `fatal` line means the whole round failed.",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/QuoteRequest" } } } },
        "responses": {
          "200": {
            "description": "NDJSON stream",
            "content": { "application/x-ndjson": { "schema": { "$ref": "#/components/schemas/QuoteStreamEvent" } } }
          },
          "400": { "$ref": "#/components/responses/Error" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/api/route": {
      "post": {
        "tags": ["quote"],
        "operationId": "routeGraph",
        "summary": "Re-quote one venue and return its symbol-labelled hops",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RouteRequest" } } } },
        "responses": {
          "200": { "description": "Route graph", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RouteGraphResponse" } } } },
          "400": { "$ref": "#/components/responses/Error" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/api/build": {
      "post": {
        "tags": ["build"],
        "operationId": "build",
        "summary": "Re-quote the chosen venue with the real sender and return an executable payload",
        "description": "Quotes go stale within ~30 s, so the venue is re-quoted fresh. Send fully-resolved token metadata (from `/api/tokens` or `/api/resolve-token`). The result `kind` is `tx` (broadcast `tx`), `order` (sign `order.typedData`, POST to `order.submit`), or `permit-tx` (sign `permitTx.typedData`, then call `/assemble`). When `approval.needed` is true, broadcast `approval.approveTx` first. The approval target is `tx.spender` / `order.spender` / `permitTx.spender` — not necessarily `tx.to`.",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BuildRequest" } } } },
        "responses": {
          "200": { "description": "Executable payload", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Payload" } } } },
          "400": { "$ref": "#/components/responses/Error" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/api/loop/markets": {
      "get": {
        "tags": ["loop"],
        "operationId": "loopMarkets",
        "summary": "Loop markets: the registry's APRs, one market by alias or id, or a search",
        "description": "On `chain`. Without `market` or `q`: one row per registry market (its collateral APR, borrow APY and max-leverage Loop APR). The registry is Ethereum's, so another chain answers `{\"markets\": []}`. A row reads Morpho (market state, borrow rate), the collateral's yield source and, for a PT, Pendle's USD prices of the PT and the loan token against the oracle's `price()`; no swap is quoted, so the swap cost and the borrow's own rate impact are left out. `maxLeverageBps` is the leverage at the default max LTV (LLTV − 300 bps), 1 / (1 − maxLtv · (1 − oracleGap)) for a PT whose oracle sits under its price; `maxApyWad` the Loop APR there, on the collateral's oracle value. A market whose read failed carries `error` instead. `market=<alias | 0x market id>` answers `{market, stats}`: the market resolved on the chain (a registry alias on Ethereum only; any other id with `custom` set) and its row. `q=<text>` answers `{hits}`: Morpho-listed markets of the chain whose tokens match, largest supply first. `market` and `q` are exclusive. Each read is cached per chain: a minute, five for a search.",
        "parameters": [
          { "name": "chain", "in": "query", "required": false, "schema": { "type": "string", "enum": ["eth", "mainnet", "ethereum", "base", "robinhood", "monad", "arc"], "default": "eth" }, "description": "A Loop chain. Base's Morpho has Ethereum's address, so a market id is only ever read on this chain." },
          { "name": "market", "in": "query", "required": false, "schema": { "type": "string" }, "description": "A registry alias (Ethereum) or a Morpho market id (0x + 64 hex) on `chain`" },
          { "name": "q", "in": "query", "required": false, "schema": { "type": "string", "minLength": 1, "maxLength": 40 }, "description": "Token search over the chain's Morpho-listed markets, e.g. `cbbtc`" }
        ],
        "responses": {
          "400": { "description": "Unknown chain or one without a Loop deployment, `market` and `q` together, an empty `market`, a `q` outside 1–40 characters, or a market id that names no usable market", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopRejected" } } } },
          "200": {
            "description": "Without `market` / `q`: one row per market, in `market` alias order of the Loop table (empty off Ethereum). With `market`: `{market, stats}`, `stats` a row. With `q`: `{hits}`, each `{chainId, marketId, loan, collateral, lltvBps, supplyUsd, liquidityUsd, borrowApy, alias}` (`alias` set on a registry market, Ethereum only).",
            "content": { "application/json": { "schema": { "type": "object", "properties": { "market": { "type": "object", "description": "The market as the dApp draws it: alias, label, chainId, marketId, loan and collateral tokens with decimals, lltvBps, entry, yieldSource, and `custom` outside the registry" }, "stats": { "type": "object" }, "hits": { "type": "array", "items": { "type": "object" } }, "markets": { "type": "array", "items": { "type": "object", "required": ["alias"], "properties": {
              "alias": { "type": "string" },
              "error": { "type": "string" },
              "lltvBps": { "type": "string" },
              "collateralApyWad": { "type": ["string", "null"], "description": "1e18 = 100 %; null when the yield source could not be read" },
              "borrowApyWad": { "type": "string" },
              "oracleGapBps": { "type": ["string", "null"], "description": "PT only: how far the oracle values the PT under its Pendle price, bps (0 at or above it). null for another collateral, or when the read failed" },
              "maxLeverageBps": { "type": ["string", "null"], "description": "null for a PT whose oracle gap could not be read" },
              "maxApyWad": { "type": ["string", "null"], "pattern": "^-?[0-9]+$" },
              "availableLiquidity": { "type": "string", "description": "Loan-token base units" }
            } } } } } } }
          }
        }
      }
    },
    "/api/loop/quote": {
      "post": {
        "tags": ["loop"],
        "operationId": "loopQuote",
        "summary": "Plan a Morpho leverage loop (no transaction)",
        "description": "Reads Morpho, sizes the flash loan, picks the entry (fxsave-usdc: direct USDC deposit into fxSP, and/or a USDC→fxUSD swap when it beats fxSP's USDC credit by more than gas; every other market: one loan token → collateral swap on the best aggregator) and returns the plan: flash, borrow, LTV, health factor, liquidation price, max leverage at the default max LTV and at LLTV, borrow APY, collateral APR (a PT's fixed APY), loop APR. With a `sender` holding collateral or debt on the market, `leverageBps` is the whole position's target and `position` / `forward` describe it before and after. No wallet needed.",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopRequest" } } } },
        "responses": {
          "200": { "description": "Loop plan (`preflight` and `tx` are null)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopPlan" } } } },
          "400": { "description": "Malformed body, a chain without a Loop deployment, a market id that names no usable market on the chain, or a plan the engine refuses (LTV above max LTV, borrow above available liquidity, fxSP entry cost above 25 bps, maxLtvBps above LLTV, equity 0 without an open position, a target leverage that needs an unloop)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopRejected" } } } },
          "429": { "$ref": "#/components/responses/RateLimited" },
          "502": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/api/loop/positions": {
      "get": {
        "tags": ["loop"],
        "operationId": "loopPositions",
        "summary": "The sender's Morpho borrows on a Loop chain",
        "description": "Rows with debt, largest USD debt first (`listLoopPositions`). A wallet the Morpho API does not know is `{positions: []}`. Cached in-process for 15 seconds per chain and lowercased sender. The response is `cache-control: private, no-store` — not a CDN cache.",
        "parameters": [
          { "name": "chain", "in": "query", "required": true, "schema": { "type": "string", "enum": ["eth", "mainnet", "ethereum", "base", "robinhood", "monad", "arc"] }, "description": "A Loop chain. mainnet and ethereum are eth." },
          { "name": "sender", "in": "query", "required": true, "schema": { "$ref": "#/components/schemas/Address" } }
        ],
        "responses": {
          "200": { "description": "`{positions}`: market id, loan and collateral tokens, debt, USD, leverage, health, listed, warnings", "content": { "application/json": { "schema": { "type": "object", "required": ["positions"], "properties": { "positions": { "type": "array", "items": { "type": "object" } } } } } } },
          "400": { "description": "Missing or invalid chain or sender", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopRejected" } } } },
          "429": { "$ref": "#/components/responses/RateLimited" },
          "502": { "description": "The Morpho API failed", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/api/loop/unwind/quote": {
      "post": {
        "tags": ["loop"],
        "operationId": "loopUnwindQuote",
        "summary": "Plan an unwind of the sender's Morpho borrow (no transaction)",
        "description": "Flashes the accrued debt, repays, withdraws collateral and sells some or all of it for the loan token. `sender` is required. Partial (`targetLeverageBps` ≥ 10000, no `receive`) leaves the position open; close (`receive` collateral or loan, no target) repays every share. The sale races recipient venues only — `curve` is a 400. The API does not accept a max exit cost. Returns the plan with `preflight` and `tx` null.",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopUnwindRequest" } } } },
        "responses": {
          "200": { "description": "Unwind plan", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopUnwindPlan" } } } },
          "400": { "description": "Malformed body, or a plan the engine refuses", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopRejected" } } } },
          "429": { "$ref": "#/components/responses/RateLimited" },
          "502": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/api/loop/unwind/quote/stream": {
      "post": {
        "tags": ["loop"],
        "operationId": "loopUnwindQuoteStream",
        "summary": "Stream an unwind quote as NDJSON",
        "description": "Same body as `/api/loop/unwind/quote`. One JSON object per line: `leg` (`amountIn` and `usdcIn`, the collateral being sold; a second leg is a resized round), `route` or `verror` per venue, then `plan` (`plan`, `expiresAt`) or `error` (`status` 400 or 502, `error`). A refused body is HTTP 400 before the stream opens.",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopUnwindRequest" } } } },
        "responses": {
          "200": { "description": "application/x-ndjson", "content": { "application/x-ndjson": { "schema": { "type": "string" } } } },
          "400": { "description": "Malformed body, before the stream opens", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopRejected" } } } },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/api/loop/unwind/build": {
      "post": {
        "tags": ["loop"],
        "operationId": "loopUnwindBuild",
        "summary": "Build the unwind: Morpho authorization (if needed) plus the Bundler3 multicall",
        "description": "Same body as the quote. Returns the `/api/build` Payload with `venue: \"loop\"`, `kind: \"tx\"`, `approval: null`. `tokenIn` is the collateral, `tokenOut` the loan token, `amountIn` the collateral sold, `amountOut` the loan token quoted. `preflight` is `morpho-authorize` when GA1 is not yet authorized. `plan` is the unwind plan with that preflight and tx. Every build is simulated.",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopUnwindRequest" } } } },
        "responses": {
          "200": { "description": "The Loop Payload (`kind: tx`, `venue: loop`, collateral in, loan token out) plus `plan` (LoopUnwindPlan).", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Payload" } } } },
          "400": { "description": "Malformed body, or a plan the engine refuses", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopRejected" } } } },
          "429": { "$ref": "#/components/responses/RateLimited" },
          "502": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/api/loop/build": {
      "post": {
        "tags": ["loop"],
        "operationId": "loopBuild",
        "summary": "Build the loop: preflight txs + the Bundler3 multicall",
        "description": "Same body as /api/loop/quote; `sender` is required. Re-plans, then returns the Payload shape with `venue: \"loop\"`, `kind: \"tx\"` and `approval: null`. Send every `preflight` entry in order (loan-token approve to the chain's GeneralAdapter1 for the equity when the allowance is short; `Morpho.setAuthorization(GeneralAdapter1, true)` when missing), then `tx`. `tx.to` is the chain's Bundler3; `tx.spender` is its GeneralAdapter1, the loan-token approval target. On a `morpho-authorize` step, `tx.to` is Morpho and `tx.spender` names the authorized adapter, not an ERC-20 spender.",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopRequest" } } } },
        "responses": {
          "200": { "description": "Executable loop payload", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopBuildResponse" } } } },
          "400": { "description": "Missing `sender` (`{error}` only), malformed body, or a refused plan", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoopRejected" } } } },
          "429": { "$ref": "#/components/responses/RateLimited" },
          "502": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/assemble": {
      "post": {
        "tags": ["build"],
        "operationId": "assemblePermit",
        "summary": "Permit2 second leg: turn a signed PermitSingle into the final tx",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["signature", "context"],
                "properties": {
                  "signature": { "type": "string", "description": "EIP-712 signature of `permitTx.typedData`" },
                  "context": { "description": "The `assembleContext` returned by /api/build, echoed back verbatim" }
                }
              }
            }
          }
        },
        "responses": {
          "200": { "description": "Broadcastable tx", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SwapTx" } } } },
          "400": { "$ref": "#/components/responses/Error" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/submit": {
      "post": {
        "tags": ["build"],
        "operationId": "submitOrder",
        "summary": "Forward a signed intent order to a venue that needs an authenticated relayer (e.g. fusion)",
        "description": "Only for orders whose `order.submit.url` points here. The relayer URL is rebuilt server-side from the whitelisted `venue` and integer `chainId`; the body is the order's `submit.bodyTemplate` completed with the signature.",
        "parameters": [
          { "name": "venue", "in": "query", "required": true, "schema": { "type": "string" } },
          { "name": "chainId", "in": "query", "required": true, "schema": { "type": "integer" } },
          { "name": "orderHash", "in": "query", "required": false, "schema": { "type": "string" } }
        ],
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "additionalProperties": true } } } },
        "responses": {
          "200": { "description": "Relayer response, passed through" },
          "400": { "$ref": "#/components/responses/Error" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/simulate": {
      "post": {
        "tags": ["browser-flow"],
        "operationId": "simulate",
        "summary": "eth_simulateV1 dry-run (local server only; the public host returns kind=skipped)",
        "responses": {
          "200": { "description": "Simulation outcome", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SimulateOutcome" } } } },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/done": {
      "post": {
        "tags": ["browser-flow"],
        "operationId": "reportDone",
        "summary": "Report the outcome of a swap (anonymous aggregate counter; no address, no amount)",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "oneOf": [
                  { "type": "object", "required": ["kind", "hash", "venue", "chainId"], "properties": { "kind": { "const": "tx" }, "hash": { "type": "string" }, "venue": { "type": "string" }, "chainId": { "type": "integer" } } },
                  { "type": "object", "required": ["kind", "orderId", "venue", "chainId"], "properties": { "kind": { "const": "order" }, "orderId": { "type": "string" }, "venue": { "type": "string" }, "chainId": { "type": "integer" } } },
                  { "type": "object", "required": ["kind", "error", "venue", "chainId"], "properties": { "kind": { "const": "error" }, "error": { "type": "string" }, "venue": { "type": "string" }, "chainId": { "type": "integer" } } }
                ]
              }
            }
          }
        },
        "responses": { "200": { "description": "Acknowledged" }, "400": { "description": "Body failed validation" } }
      }
    }
  },
  "components": {
    "parameters": {
      "chain": { "name": "chain", "in": "query", "required": false, "schema": { "$ref": "#/components/schemas/ChainAlias" }, "description": "Chain alias, default `eth`" }
    },
    "responses": {
      "Error": { "description": "Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "RateLimited": {
        "description": "Per-IP bucket drained; retry after the number of seconds in `Retry-After`",
        "headers": { "Retry-After": { "schema": { "type": "integer" } } },
        "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } }
      }
    },
    "schemas": {
      "Error": { "type": "object", "required": ["error"], "properties": { "error": { "type": "string" } } },
      "ChainAlias": {
        "type": "string",
        "enum": ["eth", "base", "arb", "op", "avax", "bsc", "hype", "unichain", "robinhood", "arc", "monad", "plasma", "polygon", "gnosis", "ink"],
        "description": "eth=1, base=8453, arb=42161, op=10, avax=43114, bsc=56, hype=999, unichain=130, robinhood=4663, arc=5042, monad=143, plasma=9745, polygon=137, gnosis=100, ink=57073"
      },
      "Venue": {
        "type": "string",
        "enum": ["kyber", "velora", "matcha", "1inch", "curve", "uniswap", "openocean", "fynd", "9summits", "cow", "delta", "uniswapx", "fusion", "ophis"],
        "description": "Sync (tx): kyber, velora, matcha, 1inch, curve, uniswap, openocean, fynd, 9summits (USDC or fxUSD → fxSAVE, or fxSAVE → any token except fxSP (native ETH included), on Ethereum only; absent from the race on other pairs). Async / intent (EIP-712 order): cow, delta, uniswapx, fusion, ophis. odos / odosv2 are discontinued. The deployment's enabled subset is `GET /api/mode`."
      },
      "TradeSide": { "type": "string", "enum": ["sell", "buy"], "description": "sell = exact-in (amountIn fixed), buy = exact-out (amountOut fixed)" },
      "Address": { "type": "string", "pattern": "^0x[0-9a-fA-F]{40}$" },
      "BaseUnits": { "type": "string", "pattern": "^[0-9]+$", "description": "Integer amount in the token's base units, as a decimal string" },
      "ChainMeta": {
        "type": "object",
        "required": ["alias", "chainId", "name", "explorer", "nativeSymbol", "wrappedNative"],
        "properties": {
          "alias": { "$ref": "#/components/schemas/ChainAlias" },
          "chainId": { "type": "integer" },
          "name": { "type": "string" },
          "explorer": { "type": "string", "format": "uri" },
          "nativeSymbol": { "type": "string" },
          "wrappedNative": { "$ref": "#/components/schemas/Address" }
        }
      },
      "VenueMeta": {
        "type": "object",
        "required": ["name", "kind"],
        "properties": { "name": { "$ref": "#/components/schemas/Venue" }, "kind": { "type": "string", "enum": ["sync", "async"] } }
      },
      "Mode": {
        "type": "object",
        "required": ["interactive", "apiVersion", "chains", "venues", "defaultChain"],
        "properties": {
          "interactive": { "type": "boolean", "const": true },
          "apiVersion": { "type": "integer", "description": "Version of the /api/* wire contract served by this deployment. Absent on deployments predating versioning (treat as 0). Non-browser clients gate on it before relying on newer RouteQuote fields.", "examples": [1] },
          "sid": { "type": "string", "description": "Session id on the local server; empty on the public host" },
          "chains": { "type": "array", "items": { "$ref": "#/components/schemas/ChainMeta" } },
          "venues": { "type": "array", "items": { "$ref": "#/components/schemas/VenueMeta" } },
          "buyVenues": { "type": "array", "items": { "$ref": "#/components/schemas/Venue" }, "description": "Venues with a native exact-out path" },
          "defaultChain": { "$ref": "#/components/schemas/ChainAlias" },
          "walletConnectProjectId": { "type": ["string", "null"] }
        }
      },
      "TokenInfo": {
        "type": "object",
        "required": ["address", "symbol", "decimals"],
        "properties": {
          "address": { "$ref": "#/components/schemas/Address" },
          "symbol": { "type": "string" },
          "name": { "type": "string" },
          "decimals": { "type": "integer", "minimum": 0, "maximum": 255 },
          "logoURI": { "type": "string" }
        }
      },
      "WireToken": {
        "type": "object",
        "required": ["address", "symbol", "decimals"],
        "properties": {
          "address": { "$ref": "#/components/schemas/Address" },
          "symbol": { "type": "string" },
          "decimals": { "type": "integer" },
          "name": { "type": "string" }
        }
      },
      "QuoteRequest": {
        "type": "object",
        "required": ["chain", "tokenInAddress", "tokenOutAddress", "slippageBps", "allowAsync"],
        "properties": {
          "chain": { "$ref": "#/components/schemas/ChainAlias" },
          "tokenInAddress": { "$ref": "#/components/schemas/Address" },
          "tokenOutAddress": { "$ref": "#/components/schemas/Address" },
          "amountIn": { "$ref": "#/components/schemas/BaseUnits" },
          "amountOut": { "$ref": "#/components/schemas/BaseUnits" },
          "side": { "$ref": "#/components/schemas/TradeSide" },
          "slippageBps": { "type": "integer", "minimum": 0, "maximum": 10000, "description": "10 = 0.1 %", "examples": [10] },
          "allowAsync": { "type": "boolean", "description": "Include intent venues (result is an order to sign, not a tx)" },
          "venues": { "type": "array", "items": { "$ref": "#/components/schemas/Venue" }, "description": "Subset to race; omit for every enabled venue" },
          "disableOdosRfq": { "type": "boolean" },
          "veloraMethods": { "$ref": "#/components/schemas/VeloraMethods" },
          "legVenue": { "$ref": "#/components/schemas/LegVenue" },
          "sender": { "$ref": "#/components/schemas/Address", "description": "optional taker for indicative quotes (CoW from/receiver)" }
        },
        "oneOf": [{ "required": ["amountIn"] }, { "required": ["amountOut"] }],
        "examples": [
          { "chain": "eth", "tokenInAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "tokenOutAddress": "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "amountIn": "1000000000", "slippageBps": 10, "allowAsync": false }
        ]
      },
      "RouteHopRaw": {
        "type": "object",
        "description": "One hop of a venue's route, token ADDRESSES rather than symbols — the shape a venue adapter normalises to. Distinct from RouteHop (POST /api/route), which is the symbol-labelled form used by the dApp's route graph.",
        "required": ["tokenIn", "tokenOut", "exchange", "swapAmount"],
        "properties": {
          "tokenIn": { "type": "string", "description": "Hop input token address (lowercase; the native sentinel 0xeee…eee for the chain coin). Some venues expose no intermediate addresses and emit an opaque positional label instead." },
          "tokenOut": { "type": "string", "description": "Hop output token address, same conventions as tokenIn" },
          "exchange": { "type": "string", "description": "Protocol / pool label" },
          "swapAmount": { "type": "string", "description": "Amount routed through the hop, in tokenIn base units — unless approxAmount is true" },
          "approxAmount": { "type": "boolean", "description": "True when swapAmount is only a relative split weight denominated in the ROUTE input token, not a real amount in this hop's tokenIn (openocean, 1inch). Ratio math stays valid; never display it as an absolute amount." },
          "amountOut": { "type": "string", "description": "Hop output in tokenOut base units — only when the venue reports it" },
          "pool": { "type": "string" },
          "fee": { "type": "integer", "description": "Fee in hundredths of a bp (3000 = 0.3 %)" }
        }
      },
      "TokenHint": {
        "type": "object",
        "description": "Venue-supplied metadata for an address appearing in hops[], so a client can label the route without a second lookup.",
        "required": ["symbol", "name", "decimals"],
        "properties": {
          "symbol": { "type": "string" },
          "name": { "type": "string" },
          "decimals": { "type": "integer", "minimum": 0, "maximum": 255 }
        }
      },
      "ProtocolFee": {
        "type": "object",
        "description": "Explicit fee surfaced by the venue's API — distinct from the implicit spread aggregators bake into the price. CoW always returns one; sync aggregators only when an integrator/partner is configured.",
        "required": ["raw", "sharePct", "side"],
        "properties": {
          "raw": { "$ref": "#/components/schemas/BaseUnits" },
          "sharePct": { "type": "number", "description": "fee / corresponding amount × 100" },
          "side": { "type": "string", "enum": ["in", "out"], "description": "Token the fee is denominated in: \"in\" = deducted from tokenIn (CoW), \"out\" = from tokenOut (kyber/odos/velora)" }
        }
      },
      "VeloraMethods": {
        "type": "array",
        "items": { "type": "string", "enum": ["swapExactAmountIn", "swapExactAmountOut", "swapExactAmountInOnUniswapV2", "swapExactAmountOutOnUniswapV2", "swapExactAmountInOnUniswapV3", "swapExactAmountOutOnUniswapV3", "swapExactAmountInOnBalancerV2", "swapExactAmountOutOnBalancerV2", "swapExactAmountInOnCurveV1", "swapExactAmountInOnCurveV2", "swapOnAugustusRFQTryBatchFill"] },
        "description": "Velora only: Augustus v6.2 methods the route must use (sent as includeContractMethods; a comma-separated string is also accepted). Velora is dropped with a per-venue error when it has no route under the constraint, answers with another method, or builds calldata whose selector is not listed. An unknown name is a 400. Omit or [] for no constraint. CLI --velora-methods.",
        "examples": [["swapExactAmountIn"]]
      },
      "LegVenue": {
        "type": "string",
        "enum": ["kyber", "velora", "matcha", "1inch", "openocean", "fynd"],
        "description": "9summits fxSAVE exit only: the aggregator its fxUSD / USDC swap legs go through when it quotes them all (else each leg takes its best quote). Other venues ignore it. CLI --leg-venue."
      },
      "LegChoice": {
        "type": "object",
        "required": ["pinned", "legs", "options"],
        "properties": {
          "pinned": { "type": ["string", "null"], "description": "The venue every leg went through: the request's legVenue when it quoted them all, else null" },
          "legs": { "type": "array", "items": { "type": "string" }, "description": "The venue of each leg, as quoted" },
          "options": {
            "type": "array",
            "description": "Each venue that quoted every leg: the route's output and gas through it alone, most output first",
            "items": {
              "type": "object",
              "required": ["venue", "amountOut", "gasUnits"],
              "properties": {
                "venue": { "type": "string" },
                "amountOut": { "$ref": "#/components/schemas/BaseUnits" },
                "gasUnits": { "type": "integer" }
              }
            }
          }
        }
      },
      "RouteQuote": {
        "type": "object",
        "required": ["venue", "amountIn", "amountOut", "kind", "hops", "router", "protocolFee", "tokenHints", "amountInUsd", "amountOutUsd", "legChoice"],
        "properties": {
          "venue": { "$ref": "#/components/schemas/Venue" },
          "amountIn": { "$ref": "#/components/schemas/BaseUnits" },
          "amountOut": { "$ref": "#/components/schemas/BaseUnits" },
          "minAmountOut": {
            "$ref": "#/components/schemas/BaseUnits",
            "description": "Guaranteed sell-side floor when amountOut is an optimistic cote (Fusion Dutch-auction auctionEndAmount). Ranking uses this when present."
          },
          "gasUsd": { "type": ["number", "null"] },
          "priceImpactPct": { "type": ["number", "null"] },
          "kind": { "type": "string", "enum": ["sync", "async"] },
          "gasUnits": { "type": ["integer", "null"] },
          "gasPriceWei": { "type": ["string", "null"] },
          "amountInUsd": { "type": ["number", "null"] },
          "amountOutUsd": { "type": ["number", "null"] },
          "hops": { "type": "array", "items": { "$ref": "#/components/schemas/RouteHopRaw" }, "description": "Address-labelled route edges; empty array when the venue exposes no path breakdown" },
          "router": { "type": ["string", "null"], "description": "Router / settlement contract the venue would execute through, when it reports one" },
          "protocolFee": { "oneOf": [{ "$ref": "#/components/schemas/ProtocolFee" }, { "type": "null" }] },
          "tokenHints": { "type": "object", "description": "Address (lowercase) → venue-supplied token metadata for the addresses appearing in hops[]. Empty object when the venue ships none.", "additionalProperties": { "$ref": "#/components/schemas/TokenHint" } },
          "legChoice": { "oneOf": [{ "$ref": "#/components/schemas/LegChoice" }, { "type": "null" }], "description": "9summits fxSAVE exit only: its swap legs and the aggregators that can take them all. null on every other row." },
          "contractMethod": { "type": "string", "description": "Velora only: the Augustus v6.2 entrypoint the route executes through (priceRoute.contractMethod), e.g. swapExactAmountIn", "examples": ["swapExactAmountIn"] },
          "buyRefine": { "type": "boolean", "description": "Exact-out served by a sell-only venue via refine (build is exact-in with a min-out floor at the target)" },
          "clientSide": { "type": "boolean", "description": "Client-only: set by the in-browser curve integration on routes it produced. The server never emits it." }
        }
      },
      "QuoteResponse": {
        "type": "object",
        "required": ["quoteId", "side", "chain", "tokenIn", "tokenOut", "amountIn", "amountOut", "best", "routes", "rate", "expiresAt"],
        "properties": {
          "quoteId": { "type": "string" },
          "side": { "$ref": "#/components/schemas/TradeSide" },
          "chain": { "type": "object", "properties": { "alias": { "type": "string" }, "chainId": { "type": "integer" }, "name": { "type": "string" } } },
          "tokenIn": { "$ref": "#/components/schemas/WireToken" },
          "tokenOut": { "$ref": "#/components/schemas/WireToken" },
          "amountIn": { "$ref": "#/components/schemas/BaseUnits" },
          "amountOut": { "$ref": "#/components/schemas/BaseUnits" },
          "best": { "type": "object", "properties": { "venue": { "$ref": "#/components/schemas/Venue" }, "amountIn": { "type": "string" }, "amountOut": { "type": "string" } } },
          "routes": { "type": "array", "items": { "$ref": "#/components/schemas/RouteQuote" }, "description": "Best first for the active side" },
          "unavailable": { "type": "array", "items": { "type": "object", "properties": { "venue": { "type": "string" }, "reason": { "type": "string" } } } },
          "tokenInUsd": { "type": ["number", "null"] },
          "tokenOutUsd": { "type": ["number", "null"] },
          "rate": { "type": "string", "description": "Human-units tokenOut per tokenIn of the best route" },
          "expiresAt": { "type": "integer", "description": "Unix ms; re-quote after this" }
        }
      },
      "QuoteStreamEvent": {
        "oneOf": [
          { "type": "object", "required": ["type", "quoteId", "side", "chain", "tokenIn", "tokenOut", "expiresAt"], "properties": { "type": { "const": "meta" }, "quoteId": { "type": "string" }, "side": { "$ref": "#/components/schemas/TradeSide" }, "chain": { "type": "object" }, "tokenIn": { "$ref": "#/components/schemas/WireToken" }, "tokenOut": { "$ref": "#/components/schemas/WireToken" }, "amountIn": { "type": "string" }, "amountOut": { "type": "string" }, "expiresAt": { "type": "integer" } } },
          { "type": "object", "required": ["type", "route"], "description": "One settled venue. The row is byte-for-byte the same RouteQuote shape POST /api/quote returns in routes[] — both handlers share one mapper — except that stream rows arrive unranked, in settle order.", "properties": { "type": { "const": "route" }, "route": { "$ref": "#/components/schemas/RouteQuote" } } },
          { "type": "object", "required": ["type", "venue", "error"], "properties": { "type": { "const": "verror" }, "venue": { "type": "string" }, "error": { "type": "string" } } },
          { "type": "object", "required": ["type", "expiresAt"], "properties": { "type": { "const": "done" }, "expiresAt": { "type": "integer" } } },
          { "type": "object", "required": ["type", "error"], "properties": { "type": { "const": "fatal" }, "error": { "type": "string" } } }
        ]
      },
      "RouteRequest": {
        "type": "object",
        "required": ["chain", "venue", "tokenIn", "tokenOut"],
        "properties": {
          "chain": { "$ref": "#/components/schemas/ChainAlias" },
          "venue": { "$ref": "#/components/schemas/Venue" },
          "amountIn": { "$ref": "#/components/schemas/BaseUnits" },
          "amountOut": { "$ref": "#/components/schemas/BaseUnits" },
          "side": { "$ref": "#/components/schemas/TradeSide" },
          "slippageBps": { "type": "integer" },
          "tokenIn": { "$ref": "#/components/schemas/WireToken" },
          "tokenOut": { "$ref": "#/components/schemas/WireToken" },
          "disableOdosRfq": { "type": "boolean" },
          "veloraMethods": { "$ref": "#/components/schemas/VeloraMethods" },
          "legVenue": { "$ref": "#/components/schemas/LegVenue" }
        }
      },
      "RouteHop": {
        "type": "object",
        "required": ["from", "to", "exchange", "swapAmount", "fromName", "fromDecimals", "toDecimals"],
        "properties": {
          "from": { "type": "string", "description": "tokenIn symbol of the hop" },
          "to": { "type": "string" },
          "exchange": { "type": "string", "description": "Protocol / pool label" },
          "swapAmount": { "type": "string", "description": "Base units routed through the hop" },
          "approxAmount": { "type": "boolean" },
          "amountOut": { "type": "string" },
          "fromName": { "type": "string" },
          "fromDecimals": { "type": "integer" },
          "toDecimals": { "type": "integer" }
        }
      },
      "RouteGraphResponse": {
        "type": "object",
        "required": ["venue", "tokenIn", "tokenOut", "hops"],
        "properties": {
          "venue": { "$ref": "#/components/schemas/Venue" },
          "tokenIn": { "type": "string" },
          "tokenOut": { "type": "string" },
          "hops": { "type": "array", "items": { "$ref": "#/components/schemas/RouteHop" }, "description": "Empty for intent venues (settled by a solver, no on-chain route)" }
        }
      },
      "BuildRequest": {
        "type": "object",
        "required": ["venue", "sender", "chain", "tokenIn", "tokenOut"],
        "properties": {
          "venue": { "$ref": "#/components/schemas/Venue" },
          "sender": { "$ref": "#/components/schemas/Address" },
          "recipient": { "oneOf": [{ "$ref": "#/components/schemas/Address" }, { "type": "null" }], "description": "Only for plain sends; swaps always pay out to `sender`" },
          "slippageBps": { "type": "integer", "description": "Use the same value you quoted with. Default 10." },
          "chain": { "$ref": "#/components/schemas/ChainAlias" },
          "tokenIn": { "$ref": "#/components/schemas/WireToken" },
          "tokenOut": { "$ref": "#/components/schemas/WireToken" },
          "amountIn": { "$ref": "#/components/schemas/BaseUnits" },
          "amountOut": { "$ref": "#/components/schemas/BaseUnits" },
          "side": { "$ref": "#/components/schemas/TradeSide" },
          "odosNotCompact": { "type": "boolean" },
          "disableOdosRfq": { "type": "boolean" },
          "veloraMethods": { "$ref": "#/components/schemas/VeloraMethods" },
          "legVenue": { "$ref": "#/components/schemas/LegVenue" }
        },
        "oneOf": [{ "required": ["amountIn"] }, { "required": ["amountOut"] }]
      },
      "SwapTx": {
        "type": "object",
        "required": ["to", "from", "data", "value", "spender", "chainId"],
        "properties": {
          "to": { "$ref": "#/components/schemas/Address" },
          "from": { "$ref": "#/components/schemas/Address" },
          "data": { "type": "string", "description": "0x-prefixed calldata" },
          "value": { "type": "string", "description": "Wei, decimal string" },
          "gas": { "type": ["string", "null"] },
          "gasPrice": { "type": ["string", "null"] },
          "maxPriorityFeePerGas": { "type": ["string", "null"] },
          "spender": { "$ref": "#/components/schemas/Address" },
          "chainId": { "type": "integer" }
        }
      },
      "Eip712TypedData": {
        "type": "object",
        "required": ["domain", "types", "primaryType", "message"],
        "properties": {
          "domain": { "type": "object", "additionalProperties": true },
          "types": { "type": "object", "additionalProperties": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string" }, "type": { "type": "string" } } } } },
          "primaryType": { "type": "string" },
          "message": { "type": "object", "additionalProperties": true }
        }
      },
      "SwapOrder": {
        "type": "object",
        "required": ["venue", "spender", "signer", "typedData", "submit", "validUntilSec", "chainId"],
        "properties": {
          "venue": { "$ref": "#/components/schemas/Venue" },
          "spender": { "$ref": "#/components/schemas/Address" },
          "signer": { "$ref": "#/components/schemas/Address" },
          "typedData": { "$ref": "#/components/schemas/Eip712TypedData" },
          "submit": {
            "type": "object",
            "required": ["url", "method", "bodyTemplate"],
            "properties": {
              "url": { "type": "string", "format": "uri", "description": "Where to POST the signed order (venue relayer, or this host's /submit for authed venues)" },
              "method": { "const": "POST" },
              "bodyTemplate": { "type": "object", "additionalProperties": true, "description": "Body to send, with the signature field filled in" }
            }
          },
          "validUntilSec": { "type": "integer" },
          "decayStartSec": { "type": ["integer", "null"] },
          "chainId": { "type": "integer" }
        }
      },
      "SwapPermitTx": {
        "type": "object",
        "required": ["venue", "spender", "signer", "typedData", "chainId"],
        "properties": {
          "venue": { "$ref": "#/components/schemas/Venue" },
          "spender": { "$ref": "#/components/schemas/Address" },
          "signer": { "$ref": "#/components/schemas/Address" },
          "typedData": { "$ref": "#/components/schemas/Eip712TypedData" },
          "chainId": { "type": "integer" }
        }
      },
      "ApprovalInfo": {
        "type": "object",
        "required": ["needed", "current", "required"],
        "properties": {
          "needed": { "type": "boolean" },
          "current": { "type": "string", "description": "Current allowance, base units" },
          "required": { "type": "string" },
          "approveTx": { "oneOf": [{ "$ref": "#/components/schemas/SwapTx" }, { "type": "null" }], "description": "Broadcast this first when `needed` is true" }
        }
      },
      "Payload": {
        "type": "object",
        "required": ["kind", "venue", "chain", "tokenIn", "tokenOut", "amountIn", "amountOut", "sender", "slippageBps", "tx", "order", "permitTx"],
        "properties": {
          "kind": { "type": "string", "enum": ["tx", "order", "permit-tx"] },
          "venue": { "$ref": "#/components/schemas/Venue" },
          "chain": { "type": "object", "properties": { "chainId": { "type": "integer" }, "name": { "type": "string" }, "explorer": { "type": "string" }, "nativeSymbol": { "type": "string" } } },
          "tokenIn": { "$ref": "#/components/schemas/WireToken" },
          "tokenOut": { "$ref": "#/components/schemas/WireToken" },
          "amountIn": { "$ref": "#/components/schemas/BaseUnits" },
          "amountOut": { "$ref": "#/components/schemas/BaseUnits" },
          "sender": { "$ref": "#/components/schemas/Address" },
          "recipient": { "type": ["string", "null"] },
          "slippageBps": { "type": "integer" },
          "approval": { "oneOf": [{ "$ref": "#/components/schemas/ApprovalInfo" }, { "type": "null" }] },
          "simulateEnabled": { "type": "boolean" },
          "tx": { "oneOf": [{ "$ref": "#/components/schemas/SwapTx" }, { "type": "null" }], "description": "Set when kind = tx" },
          "order": { "oneOf": [{ "$ref": "#/components/schemas/SwapOrder" }, { "type": "null" }], "description": "Set when kind = order" },
          "permitTx": { "oneOf": [{ "$ref": "#/components/schemas/SwapPermitTx" }, { "type": "null" }], "description": "Set when kind = permit-tx" },
          "assembleContext": { "description": "Opaque; echo back to /assemble for kind = permit-tx" },
          "walletConnectProjectId": { "type": ["string", "null"] }
        }
      },
      "SimulateOutcome": {
        "oneOf": [
          {
            "type": "object",
            "required": ["kind", "swapStatus", "tokenOutReceived"],
            "properties": {
              "kind": { "const": "ok" },
              "approveStatus": { "type": "string", "enum": ["ok", "reverted", "skipped"] },
              "approveGasUsed": { "type": ["string", "null"] },
              "swapStatus": { "type": "string", "enum": ["ok", "reverted"] },
              "swapGasUsed": { "type": ["string", "null"] },
              "swapRevertReason": { "type": ["string", "null"] },
              "tokenOutReceived": { "type": "string" },
              "tokenInPriceUsd": { "type": ["number", "null"] },
              "tokenOutPriceUsd": { "type": ["number", "null"] }
            }
          },
          { "type": "object", "required": ["kind", "reason"], "properties": { "kind": { "const": "skipped" }, "reason": { "type": "string" } } },
          { "type": "object", "required": ["kind", "message"], "properties": { "kind": { "const": "error" }, "message": { "type": "string" } } }
        ]
      },
      "LoopUnwindRequest": {
        "type": "object",
        "required": ["chain", "market", "sender", "mode"],
        "properties": {
          "chain": { "type": "string", "enum": ["eth", "mainnet", "ethereum", "base", "robinhood", "monad", "arc"] },
          "market": { "type": "string", "description": "A registry alias (Ethereum) or any Morpho market id on `chain`" },
          "sender": { "$ref": "#/components/schemas/Address", "description": "Required. The position being unwound is the sender's." },
          "mode": { "type": "string", "enum": ["partial", "close"] },
          "targetLeverageBps": { "oneOf": [{ "type": "integer", "minimum": 10000 }, { "type": "string", "pattern": "^[0-9]+$" }], "description": "Partial only. The whole position's target leverage, bps. 10000 repays every share and leaves the unsold collateral supplied. Must not be sent with `receive`." },
          "receive": { "type": "string", "enum": ["collateral", "loan"], "description": "Close only. collateral (default) sells only what repays the flash; loan sells all of the collateral. Must not be sent with `targetLeverageBps`." },
          "slippageBps": { "type": "integer", "minimum": 0, "maximum": 9999, "default": 10 },
          "venues": { "type": "array", "items": { "type": "string", "enum": ["kyber", "velora", "matcha", "1inch", "openocean", "fynd", "fxsave-redeem"] }, "description": "Venues the sale races. All of them when omitted. `fxsave-redeem` (fxSAVE instant exit) is accepted on the fxsave-usdc market only. `curve` is not a venue of the sale." },
          "venue": { "type": ["string", "null"], "enum": ["kyber", "velora", "matcha", "1inch", "openocean", "fynd", "fxsave-redeem", null], "description": "Venue picked over the best quote. Must be one of `venues` when that list is set." },
          "legVenue": { "$ref": "#/components/schemas/LegVenue", "description": "fxsave-redeem only: the aggregator its fxUSD → loan swap leg goes through when it quotes it (CLI --leg-venue). The fxsave-redeem route row then carries `legChoice`." }
        }
      },
      "LoopUnwindPlan": {
        "type": "object",
        "description": "Same object as `swap unloop --json`. Amounts are base-unit strings. `preflight` and `tx` are null on a quote.",
        "required": ["action", "market", "marketId", "mode", "sellCollateral", "expectedLoanOut", "preflight", "tx"],
        "properties": {
          "action": { "const": "unwind" },
          "market": { "type": "string" },
          "marketId": { "type": "string" },
          "chainId": { "type": "integer" },
          "mode": { "type": "string", "enum": ["partial", "close"] },
          "receive": { "type": ["string", "null"], "enum": ["collateral", "loan", null] },
          "targetLeverageBps": { "type": ["string", "null"] },
          "sellCollateral": { "type": "string", "description": "Collateral base units sold" },
          "expectedLoanOut": { "type": "string", "description": "Loan-token base units the picked quote gives" },
          "swapGraph": { "oneOf": [{ "$ref": "#/components/schemas/RouteGraphResponse" }, { "type": "null" }], "description": "Symbol-labelled hops of the collateral sale only, the same shape as POST /api/route. null when the sale has no hops." },
          "loanToWallet": { "type": "string" },
          "collateralToWallet": { "type": "string" },
          "preflight": { "type": ["array", "null"], "items": { "$ref": "#/components/schemas/LoopPreflightAction" } },
          "tx": { "oneOf": [{ "$ref": "#/components/schemas/SwapTx" }, { "type": "null" }] }
        }
      },
      "LoopRequest": {
        "type": "object",
        "required": ["chain", "market", "equity", "leverageBps"],
        "properties": {
          "chain": { "type": "string", "enum": ["eth", "mainnet", "ethereum", "base", "robinhood", "monad", "arc"], "description": "A Loop chain (mainnet and ethereum are eth). Any other chain is a 400: it has no Loop deployment." },
          "market": { "anyOf": [{ "type": "string", "enum": ["fxsave-usdc", "pt-fxsave-29oct2026-usdc", "pt-reusd-10dec2026-usdc", "pt-reusd-10dec2026-usdt", "pt-susde-26nov2026-usdc", "pt-usdat-14jan2027-usdc", "strusd-usdc", "reusd-usdc", "pst-usdc", "pst-pyusd", "pst-ausd", "prime-pyusd", "prime-ausd", "susde-pyusd", "susde-usdtb", "susdai-ausd", "susdai-ausd-86", "susdai-usdt", "syrupusdc-pyusd", "syrupusdc-ausd"] }, { "type": "string", "pattern": "^0x[0-9a-fA-F]{64}$" }], "description": "A registry alias (Ethereum markets), or any Morpho market id on `chain`, resolved there (`custom` in the plan)", "examples": ["fxsave-usdc", "pt-reusd-10dec2026-usdc"] },
          "sender": { "$ref": "#/components/schemas/Address", "description": "Position owner. Optional for quote: omitted or the zero address plans without reading an open position. Required for build." },
          "equity": { "$ref": "#/components/schemas/BaseUnits", "description": "Loan token (the market's, in its decimals) the sender brings. \"0\" levers up the sender's open position with a flash only." },
          "leverageBps": { "oneOf": [{ "type": "integer", "minimum": 10000 }, { "type": "string", "pattern": "^[0-9]+$" }], "description": "10000 = 1x. On an open position, the whole position's target leverage after the loop.", "examples": [30000] },
          "maxLtvBps": { "oneOf": [{ "type": "integer", "minimum": 0 }, { "type": "string", "pattern": "^[0-9]+$" }], "description": "Default LLTV − 300 (8850 on a 91.5 % market). Up to LLTV: health factor 1, liquidatable once interest accrues." },
          "slippageBps": { "type": "integer", "minimum": 0, "maximum": 9999, "default": 10, "description": "Bounds the entry swap's minimum out, and on fxsave-usdc the fxSP deposits and the fxSAVE share price" }
        },
        "examples": [
          { "chain": "eth", "market": "fxsave-usdc", "equity": "1000000000", "leverageBps": 30000, "slippageBps": 10 }
        ]
      },
      "LoopRejected": {
        "type": "object",
        "required": ["error"],
        "properties": {
          "error": { "type": "string" },
          "maxLeverageBps": { "type": ["string", "null"], "description": "Reachable max leverage in bps when the engine can size one, else null. Absent on a missing-sender build error." }
        }
      },
      "LoopPosition": {
        "type": "object",
        "description": "The sender's open Morpho position on the market, before the loop",
        "properties": {
          "collateral": { "type": "string", "description": "Collateral base units" },
          "borrowShares": { "type": "string" },
          "borrowAssets": { "type": "string", "description": "Loan-token base units, shares rounded up" },
          "collateralValue": { "type": "string", "description": "Loan-token base units at the oracle price" },
          "ltvBps": { "type": "string" },
          "leverageBps": { "type": "string", "description": "collateralValue / (collateralValue − borrowAssets); 0 when underwater" },
          "healthFactorWad": { "type": ["string", "null"], "description": "LLTV / LTV, 1e18 = 1.0; null without debt" }
        }
      },
      "LoopForward": {
        "type": "object",
        "description": "Open position plus this loop, combined",
        "properties": {
          "collateral": { "type": "string" },
          "collateralValue": { "type": "string" },
          "borrowAmount": { "type": "string" },
          "ltvBps": { "type": "string" },
          "leverageBps": { "type": "string" },
          "healthFactorWad": { "type": ["string", "null"] }
        }
      },
      "LoopPreflightAction": {
        "type": "object",
        "required": ["kind", "label", "tx"],
        "properties": {
          "kind": { "type": "string", "enum": ["approve", "morpho-authorize"], "description": "approve: loan-token approve(GeneralAdapter1, equity), preceded by approve(GeneralAdapter1, 0) for USDT with a non-zero allowance. morpho-authorize: Morpho setAuthorization(GeneralAdapter1, true)." },
          "label": { "type": "string" },
          "tx": { "$ref": "#/components/schemas/SwapTx" }
        }
      },
      "LoopPlan": {
        "type": "object",
        "description": "Same object as `swap loop --json`. Amounts are base-unit strings in `loanToken` / `collateralToken` decimals (fxSP 18); leverage and LTV are bps; APYs and health are wad (1e18 = 100 % or 1.0).",
        "required": ["action", "market", "marketId", "chainId", "equity", "leverageBps", "flashTotal", "depositAmount", "borrowAmount", "expectedCollateral", "ltvBps", "maxLtvBps", "lltvBps", "healthFactorWad", "liquidationPrice", "maxLeverageBps", "optimiser", "preflight", "tx"],
        "properties": {
          "action": { "const": "loop" },
          "market": { "type": "string", "examples": ["fxsave-usdc"] },
          "marketId": { "type": "string" },
          "chainId": { "type": "integer", "enum": [1, 8453, 4663, 143, 5042] },
          "entryKind": { "type": "string", "enum": ["fxsp", "swap"], "description": "fxsp: fxSAVE through fxSP. swap: the deposit sold for the collateral in one aggregator swap." },
          "loanToken": { "$ref": "#/components/schemas/WireToken" },
          "collateralToken": { "$ref": "#/components/schemas/WireToken" },
          "sender": { "type": ["string", "null"] },
          "equity": { "type": "string" },
          "leverageBps": { "type": "string" },
          "flashTotal": { "type": "string", "description": "Loan token flash-borrowed from Morpho, repaid by borrowAmount + equity" },
          "fee": { "type": "string", "description": "Loan-token fee taken from the flash and sent to REFERRAL_ADDRESS (LOOP_FLASH_FEE_BPS); 0 when unset (the embedded swap's partner fee is in optimiser.feeBps)" },
          "feeBps": { "type": "integer", "description": "LOOP_FLASH_FEE_BPS as charged; 0 when no fee is taken" },
          "feeRecipient": { "type": ["string", "null"] },
          "depositAmount": { "type": "string", "description": "Loan token turned into collateral (fxsave-usdc: into fxSP, directly or through the swap)" },
          "usdcLeg": { "type": "string", "description": "fxsave-usdc: part of depositAmount deposited into fxSP as USDC. 0 elsewhere." },
          "borrowAmount": { "type": "string", "description": "Loan token borrowed on Morpho by this loop" },
          "expectedFxSp": { "type": "string", "description": "fxsave-usdc only; 0 elsewhere" },
          "expectedCollateral": { "type": "string", "description": "Collateral the entry is expected to deliver" },
          "minCollateral": { "type": "string", "description": "Collateral the entry's floors guarantee; health is checked on it" },
          "expectedFxSave": { "type": "string", "deprecated": true, "description": "Same as expectedCollateral" },
          "collateralValue": { "type": "string", "description": "Loan-token value of minCollateral at the oracle price" },
          "ltvBps": { "type": "string", "description": "This loop's LTV, or the combined position's when `forward` is set" },
          "maxLtvBps": { "type": "string" },
          "lltvBps": { "type": "string" },
          "healthFactorWad": { "type": ["string", "null"] },
          "liquidationPrice": { "type": "string", "description": "Loan-token base units per 1 whole collateral token at which LTV reaches LLTV" },
          "maxLeverageBps": { "type": "string", "description": "Max leverage at maxLtvBps and the market's available liquidity" },
          "safeMaxLeverageBps": { "type": "string", "description": "Max leverage at the default max LTV (LLTV − 3 %)" },
          "lltvMaxLeverageBps": { "type": "string", "description": "Max leverage at LLTV (health factor 1)" },
          "borrowApyWad": { "type": "string" },
          "borrowApyAfterWad": { "type": "string", "description": "Borrow APY once this borrow raises utilisation" },
          "position": { "oneOf": [{ "$ref": "#/components/schemas/LoopPosition" }, { "type": "null" }] },
          "forward": { "oneOf": [{ "$ref": "#/components/schemas/LoopForward" }, { "type": "null" }] },
          "collateralApyWad": { "type": "string", "description": "Collateral yield, annualized: fxSAVE convertToAssets × fxSP redeemed at par, ERC-4626 convertToAssets or the oracle price over ~7 days, or a PT's Pendle implied APY; 0 when the read fails" },
          "fxSaveApyWad": { "type": "string", "deprecated": true, "description": "Same as collateralApyWad" },
          "maturity": { "type": ["integer", "null"], "description": "PT expiry, unix seconds; null for other collateral" },
          "loopApyWad": { "type": "string", "pattern": "^-?[0-9]+$", "description": "(collateral × collateral APR − debt × borrow APY) / equity; negative when the borrow costs more than the yield" },
          "availableLiquidity": { "type": "string" },
          "oraclePrice": { "type": "string", "description": "Morpho oracle price, 1e36-scaled" },
          "entryCostBps": { "type": "string", "description": "Entry cost against the oracle value of the expected collateral; the plan is refused above the market cap (25, 200 on pt-fxsave-29oct2026-usdc)" },
          "slippageBps": { "type": "integer" },
          "exitWarning": { "type": "string" },
          "optimiser": {
            "type": "object",
            "properties": {
              "executed": { "type": "boolean", "description": "true when the entry swaps: part of the flash USDC→fxUSD on fxsave-usdc, all of it loan → collateral elsewhere" },
              "swapIn": { "type": "string", "description": "Loan token swapped" },
              "swapOut": { "type": "string", "description": "Quoted swap output (fxUSD, or the collateral)" },
              "swapUsdc": { "type": "string", "deprecated": true, "description": "Same as swapIn" },
              "fxUsdOut": { "type": "string", "deprecated": true, "description": "Same as swapOut" },
              "gainWad": { "type": "string" },
              "reason": { "type": "string" },
              "venue": { "type": ["string", "null"], "description": "Aggregator that wins the embedded swap, or \"curve\"" },
              "feeBps": { "type": "integer", "description": "Partner fee on the swap: REFERRAL_FEE_BPS + LOOP_SWAP_FEE_SURCHARGE_BPS on fee-taking venues, 0 on Curve and Fynd" }
            }
          },
          "swapGraph": { "oneOf": [{ "$ref": "#/components/schemas/RouteGraphResponse" }, { "type": "null" }], "description": "Symbol-labelled hops of the embedded swap only, the same shape as POST /api/route. null when this plan does not swap." },
          "preflight": { "oneOf": [{ "type": "array", "items": { "$ref": "#/components/schemas/LoopPreflightAction" } }, { "type": "null" }] },
          "tx": { "oneOf": [{ "$ref": "#/components/schemas/SwapTx" }, { "type": "null" }] }
        }
      },
      "LoopBuildResponse": {
        "type": "object",
        "description": "The /api/build Payload shape with `venue: \"loop\"`, plus `preflight` and `plan`",
        "required": ["kind", "venue", "chain", "tokenIn", "tokenOut", "amountIn", "amountOut", "sender", "slippageBps", "approval", "preflight", "tx", "order", "permitTx", "plan"],
        "properties": {
          "kind": { "const": "tx" },
          "venue": { "const": "loop" },
          "chain": { "type": "object", "properties": { "chainId": { "type": "integer" }, "name": { "type": "string" }, "explorer": { "type": "string" }, "nativeSymbol": { "type": "string" } } },
          "tokenIn": { "$ref": "#/components/schemas/WireToken", "description": "Loan token" },
          "tokenOut": { "$ref": "#/components/schemas/WireToken", "description": "Collateral" },
          "amountIn": { "$ref": "#/components/schemas/BaseUnits", "description": "Equity" },
          "amountOut": { "$ref": "#/components/schemas/BaseUnits", "description": "Expected collateral" },
          "sender": { "$ref": "#/components/schemas/Address" },
          "recipient": { "type": "null" },
          "slippageBps": { "type": "integer" },
          "simulateEnabled": { "type": "boolean" },
          "approval": { "type": "null", "description": "Loop approvals are in `preflight`" },
          "preflight": { "type": "array", "items": { "$ref": "#/components/schemas/LoopPreflightAction" }, "description": "Send in order before `tx`; only the missing grants are listed" },
          "tx": { "$ref": "#/components/schemas/SwapTx", "description": "Bundler3 multicall" },
          "order": { "type": "null" },
          "permitTx": { "type": "null" },
          "walletConnectProjectId": { "type": ["string", "null"] },
          "plan": { "$ref": "#/components/schemas/LoopPlan" }
        }
      }
    }
  }
}
