openapi: 3.1.0

info:
  title: Insight Oracle Risk & Transparency API
  version: v1
  description: |
    Decision-input integrity for onchain AI agents: before an agent acts on a
    price, Insight assesses whether that price can be trusted and returns a
    signed verdict a third party can re-verify offline. The first assessment
    domain is oracle risk: prices with source metadata, cross-oracle consensus,
    deviation, freshness, source independence, feed health, protocol liquidation
    analysis, and unified Peg Risk. Price snapshots are collected every 15
    minutes. Pre-trade assessments, Oracle Watch, and signed assessment/
    execution-price evidence expose these capabilities to applications and
    agents. Insight does not authorize or submit transactions; PriorSeal is an
    optional, separate authorization and execution-evidence integration.

    ---

    ## Quick Start

    1. **Get an API Key** — Create one in [Settings](/settings). It's shown only once, so store it securely.
    2. **Build the Query** — Choose a provider, symbol, and chain. URL-encode symbols like `BTC%2FUSD`.
    3. **Handle the Response** — Check the `success` flag, read `price` and `verification` metadata, handle errors.

    ```bash
    curl -H "X-API-Key: ins_your_key_here" \
      "https://www.oracleinsight.xyz/api/v1/prices?provider=chainlink&symbol=BTC%2FUSD&chain=ethereum"
    ```

    ---

    ## Authentication

    External v1 endpoints accept API keys only. Browser account-management
    endpoints outside `/api/v1` use Supabase session bearer tokens.

    | Method | Header | Use Case |
    |--------|--------|----------|
    | **API Key** | `X-API-Key: ins_...` | External integrations, scripts, bots |
    - Credit-metered `/api/v1` endpoints require an API key. Bearer tokens cannot bypass metering.
    - Public endpoints (`/health`, `/symbols`) require no authentication.

    ⚠️ **Keep your key safe** — API keys are shown only once when created. Rotate them immediately if leaked.

    ---

    ## Plans & Pricing

    Access is gated by a **credit wallet**, not plan tiers. There is no recurring
    free tier and no feature gating — every paying user gets every endpoint and
    MCP tool; a call is allowed iff the key's credit balance covers its metering
    class cost (C1–C4). New users receive a **one-time 400-credit trial** after
    email verification (it never refreshes).

    | Plan | Monthly / annual price | Rate Limit | Included credits/mo | Credit Packs (pay-as-you-go) |
    |------|-----------------------|-----------|---------------------|------------------------------|
    | **Starter** | $19/mo / $190/yr | 120 req/min | 25,000 | Starter 100k / $99 |
    | **Usage Pack 120K** | $79/mo / $790/yr | 400 req/min | 120,000 | Builder 400k / $389 |
    | **Usage Pack 500K** | $299/mo / $2,990/yr | 1,200 req/min | 500,000 | Agent 2M / $1,849 |
    | **Enterprise** | Contact us | Unlimited | Unlimited | Available on every paid path |

    Endpoints marked with 🔒 are **credit-metered** (charged per call from the
    wallet). Public metadata endpoints (`/health`, `/symbols`) are free.
    Annual billing is 10 times the monthly price for 12 monthly credit grants.
    API C3 pre-trade checks work out to about $0.0100–$0.0198
    per call depending on the plan, billing cycle, or prepaid pack; direct x402
    and optional MPP C3 access remains $0.02.
    Payments are crypto-only via NOWPayments (USDC-denominated); there is no
    auto-renewal — subscriptions run one billing cycle.

    ---

    ## Rate Limits

    Rate limits are enforced **per API key** (not per IP) in 60-second sliding windows.

    **Response Headers:**

    | Header | Description |
    |--------|-------------|
    | `X-RateLimit-Limit` | Maximum requests allowed in the window |
    | `X-RateLimit-Remaining` | Requests remaining in current window |
    | `X-RateLimit-Reset` | Unix timestamp when the window resets |
    | `Retry-After` | Seconds until you can retry. Only on rate-limit 429s; product concurrency refusals (open window/lifecycle caps) carry no `Retry-After`, because a slot frees only when one is closed or expires |

    **Quota / Credit Headers:**

    | Header | Description |
    |--------|-------------|
    | `X-Quota-Limit` | Remaining credit balance (credit wallet) |
    | `X-Quota-Remaining` | Remaining credit balance |
    | `X-Quota-Reset` | Unix timestamp when the balance resets (monthly cycle) |
    | `X-Credit-Cost` | Credits charged for this call (metering class) |
    | `X-Credit-Balance` | Wallet balance remaining after the call |
    | `X-Credit-Denied` | Reason a call was rejected for insufficient credits |

    ---

    ## Response Format

    All responses follow a consistent envelope:

    ```json
    {
      "success": true,
      "data": { ... },
      "meta": {
        "timestamp": 1700000000000,
        "requestId": "req_abc123"
      }
    }
    ```

    Error responses:

    ```json
    {
      "success": false,
      "error": {
        "code": "SYMBOL_NOT_SUPPORTED",
        "message": "No active oracle feed for the requested symbol.",
        "retryable": false
      },
      "meta": { "timestamp": 1700000000000 }
    }
    ```

    ---

    ## Error Codes

    | Code | Status | Description |
    |------|--------|-------------|
    | `UNAUTHORIZED` | 401 | Missing or invalid X-API-Key header |
    | `FORBIDDEN` | 403 | Insufficient permissions |
    | `BAD_REQUEST` | 400 | Malformed request or missing required parameters |
    | `VALIDATION_ERROR` | 400 | Query or body parameters failed validation |
    | `NOT_FOUND` | 404 | Requested resource not found |
    | `SYMBOL_NOT_SUPPORTED` | 404 | No active oracle feed for the requested symbol |
    | `PROTOCOL_NOT_FOUND` | 404 | Requested protocol does not exist |
    | `CREDIT_EXHAUSTED` | 402 | Wallet balance insufficient to cover the call's metering cost |
    | `INSUFFICIENT_DATA` | 422 | Not enough data points to compute the requested metric |
    | `RATE_LIMIT_EXCEEDED` | 429 | Too many requests. Retry after the timestamp in the header |
    | `PAYLOAD_TOO_LARGE` | 413 | Request body exceeds the configured maximum size |
    | `INTERNAL_ERROR` | 500 | Unexpected server error |

    ---

    ## Code Examples

    **JavaScript — fetch latest price:**

    ```javascript
    const API_KEY = 'ins_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    const symbol = encodeURIComponent('BTC/USD');

    const response = await fetch(
      `https://www.oracleinsight.xyz/api/v1/prices?provider=chainlink&symbol=${symbol}&chain=ethereum`,
      { headers: { 'X-API-Key': API_KEY } }
    );

    const result = await response.json();
    if (!result.success) throw new Error(result.error?.message);
    console.log(result.data.price);
    ```

    **Batch query:**

    ```javascript
    const response = await fetch('https://www.oracleinsight.xyz/api/v1/prices/batch', {
      method: 'POST',
      headers: {
        'X-API-Key': API_KEY,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        queries: [
          { provider: 'chainlink', symbol: 'BTC/USD', chain: 'ethereum' },
          { provider: 'redstone', symbol: 'ETH/USD', chain: 'arbitrum' },
        ],
      }),
    });

    const result = await response.json();
    result.data.forEach((item) => {
      if (item.error) console.error(`${item.symbol}: ${item.error}`);
      else console.log(`${item.symbol}: ${item.price.price}`);
    });
    ```

    ---

    ## Best Practices

    - **Cache responses** client-side to avoid hitting rate limits for unchanged data.
    - **Read `X-RateLimit-Remaining`** headers to throttle requests proactively.
    - **Always URL-encode** symbols containing `/`, e.g. `BTC%2FUSD`.
    - **Check `verification.type`** to distinguish on-chain (`🛡️`) from API (`🌐`) data.
    - **Use batch endpoints** to reduce request count when querying multiple prices.
  contact:
    name: Insight API Support
    url: https://www.oracleinsight.xyz/docs/api
  license:
    name: MIT
    url: https://opensource.org/licenses/MIT

servers:
  - url: https://www.oracleinsight.xyz/api/v1
    description: Production
  - url: http://localhost:3000/api/v1
    description: Local development

tags:
  - name: Public
    description: No authentication required
  - name: System
    description: Service liveness and dependency readiness
  - name: Prices
    description: Historical and latest oracle price data
  - name: DEX Markets
    description: Reviewed execution-market evidence, separate from oracle consensus
  - name: Consensus
    description: Cross-oracle consensus pricing 🔒
  - name: Feeds
    description: Oracle feed registry, health, and freshness
  - name: Reputation
    description: Oracle provider reputation scores and rankings
  - name: Risk
    description: Composite risk metrics 🔒
  - name: Protocols
    description: Lending protocol risk parameters and oracle exposure 🔒
  - name: Safety
    description: Liquidation stress tests and position safety 🔒
  - name: Analytics
    description: Deviation, correlation, signals, latency, anomalies 🔒
  - name: Risk Signals
    description: Peg Risk for stablecoins and wrapped/LST assets, plus incidents
  - name: Oracle Watch
    description: Signed oracle monitoring signals and history
  - name: Data
    description: Snapshots, exports, and daily reports
  - name: Execution Evidence
    description: Issue, retrieve, and independently verify signed execution receipts

security: []

paths:
  /rwa/assessment:
    post:
      operationId: assessRwaEvidence
      tags: [Safety]
      summary: Unsigned RWA evidence diagnostic
      description: Evaluates caller-supplied instrument, exact-call scope, quotes, market state and issuer evidence against an explicit policy. Does not authenticate inputs or authorize execution. Uses the separate insight.rwa-report.v1 family; existing pre-trade receipts are unchanged.
      security:
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: './rwa-assessment.schema.json'
      responses:
        '200':
          description: Diagnostic envelope; data.mode is diagnostic, data.mayAuthorizeExecution is false, data.evidenceProvenance is caller-supplied-unverified, and data.report contains recomputable evaluation.
        '400':
          description: Invalid input or unsupported policy semantics
        '401':
          description: API key required
  /rwa/robinhood/context:
    get:
      operationId: getRobinhoodRwaContext
      tags: [Safety]
      summary: Robinhood Stock Token issuer context
      description: >-
        Returns first-party Robinhood Assets (Jersey) Limited metadata, trading
        capabilities, halt state, corporate actions, multiplier-normalized
        reference price, and an optional on-chain ERC-8056 cross-check. This is
        issuer context, not an independent oracle observation: it never counts
        toward oracle quorum and never authorizes execution.
      security:
        - apiKey: []
      parameters:
        - in: query
          name: symbol
          required: true
          schema:
            type: string
            pattern: '^[A-Za-z][A-Za-z0-9.-]{0,15}$'
          example: AAPL
        - in: query
          name: verifyOnchain
          required: false
          schema:
            type: boolean
            default: true
          description: Cross-check uiMultiplier, pending multiplier, effective time, and oraclePaused on Robinhood Chain.
      responses:
        '200':
          description: Non-authorizing first-party issuer context with explicit provenance and quorum exclusion.
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success:
                    type: boolean
                    const: true
                  data:
                    type: object
                    required:
                      [
                        schema,
                        source,
                        asset,
                        quote,
                        multiplier,
                        priceNormalization,
                        verification,
                        corporateActions,
                        marketEvidence,
                        integrity,
                      ]
                    properties:
                      schema:
                        type: string
                        const: insight.robinhood-rwa-context.v1
                      source:
                        type: object
                        description: First-party issuer provenance; independent and countsTowardOracleQuorum are always false.
                        required: [id, type, independent, countsTowardOracleQuorum, issuer]
                        properties:
                          id:
                            type: string
                            const: robinhood-rhj
                          type:
                            type: string
                            const: issuer-first-party
                          independent:
                            type: boolean
                            const: false
                          countsTowardOracleQuorum:
                            type: boolean
                            const: false
                          issuer:
                            type: string
                            const: Robinhood Assets (Jersey) Limited
                      asset:
                        type: object
                        required:
                          [id, tokenSymbol, tokenName, status, currentMultiplier, deployment]
                        properties:
                          id:
                            type: string
                            pattern: '^0x[0-9a-fA-F]{64}$'
                          tokenSymbol:
                            type: string
                          tokenName:
                            type: string
                          status:
                            type: string
                          currentMultiplier:
                            type: string
                          pendingMultiplier:
                            type: [string, 'null']
                          deployment:
                            type: object
                      quote:
                        type: object
                        required:
                          [tokenSymbol, bid, ask, currency, generatedAt, midpointUsd, ageSeconds]
                        properties:
                          tokenSymbol:
                            type: string
                          bid:
                            type: string
                          ask:
                            type: string
                          currency:
                            type: string
                            const: USD
                          generatedAt:
                            type: string
                            format: date-time
                          midpointUsd:
                            type: string
                          ageSeconds:
                            type: [integer, 'null']
                      multiplier:
                        type: object
                        required:
                          [decimals, apiCurrent, apiCurrentAtomic, onchain, currentMatchesOnchain]
                        properties:
                          decimals:
                            type: integer
                            const: 18
                          apiCurrent:
                            type: string
                          apiCurrentAtomic:
                            type: string
                          currentMatchesOnchain:
                            type: [boolean, 'null']
                          onchain:
                            type: object
                            required: [attempted, available, complete, rpcMode, tokenUid]
                            properties:
                              attempted:
                                type: boolean
                              available:
                                type: boolean
                              complete:
                                type: boolean
                              rpcMode:
                                type: string
                                enum: [configured, public-rate-limited, not-requested]
                              tokenUid:
                                type: [string, 'null']
                      priceNormalization:
                        type: object
                        required:
                          [
                            rawUnderlyingMidUsd,
                            tokenReferencePriceUsd,
                            formula,
                            countsTowardOracleQuorum,
                          ]
                        properties:
                          rawUnderlyingMidUsd:
                            type: string
                          tokenReferencePriceUsd:
                            type: string
                          formula:
                            type: string
                            const: underlying-midpoint * currentMultiplier
                          countsTowardOracleQuorum:
                            type: boolean
                            const: false
                      verification:
                        type: object
                        description: REST/on-chain asset UID and deployment consistency checks.
                        required:
                          [
                            assetIdMatchesOnchain,
                            assetDeploymentRegistered,
                            quoteSymbolMatchesAsset,
                            quoteDeploymentMatchesAsset,
                            corporateActionSymbolsMatchAsset,
                            corporateActionDeploymentsMatchAsset,
                          ]
                        properties:
                          assetIdMatchesOnchain:
                            type: [boolean, 'null']
                          assetDeploymentRegistered:
                            type: boolean
                          quoteSymbolMatchesAsset:
                            type: boolean
                          quoteDeploymentMatchesAsset:
                            type: boolean
                          corporateActionSymbolsMatchAsset:
                            type: boolean
                          corporateActionDeploymentsMatchAsset:
                            type: boolean
                      corporateActions:
                        type: array
                        items:
                          type: object
                      marketEvidence:
                        type: object
                        required: [halt, corporateAction, quoteObservedAt, quoteValidUntil, session]
                        properties:
                          halt:
                            type: string
                            enum: [CLEAR, HALTED, UNKNOWN]
                          corporateAction:
                            type: string
                            enum: [CLEAR, PENDING, UNKNOWN]
                          quoteObservedAt:
                            type: [integer, 'null']
                          quoteValidUntil:
                            type: [integer, 'null']
                          session:
                            type: string
                            const: UNKNOWN
                      integrity:
                        type: object
                        description: CLEAR, CAUTION, or BLOCK consistency status; mayAuthorizeExecution is always false.
                        required: [status, reasonCodes, mayAuthorizeExecution]
                        properties:
                          status:
                            type: string
                            enum: [CLEAR, CAUTION, BLOCK]
                          reasonCodes:
                            type: array
                            items:
                              type: string
                          mayAuthorizeExecution:
                            type: boolean
                            const: false
        '400':
          description: Invalid or unsupported Stock Token symbol
        '401':
          description: API key required
        '502':
          description: Robinhood issuer-context service unavailable or returned invalid data
  /rwa/robinhood/instrument:
    get:
      operationId: getRobinhoodRwaInstrument
      tags: [Safety]
      summary: Resolve and cross-check an RWA instrument identity
      description: >-
        Resolves the committed FIGI/MIC instrument record for a Robinhood Stock
        Token and cross-checks it against current issuer UID, ISIN, chain and
        contract data. Registry entries remain in shadow mode until explicitly
        promoted. This endpoint returns reference master data only: it never
        counts toward oracle quorum and never authorizes execution.
      security:
        - apiKey: []
      parameters:
        - in: query
          name: symbol
          required: true
          schema:
            type: string
            pattern: '^[A-Za-z][A-Za-z0-9.-]{0,15}$'
          example: AAPL
        - in: query
          name: verifyOnchain
          required: false
          schema:
            type: boolean
            default: true
          description: Also cross-check the issuer UID and deployment against Robinhood Chain.
      responses:
        '200':
          description: Non-authorizing FIGI/MIC registry record and issuer identity cross-check.
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success:
                    type: boolean
                    const: true
                  data:
                    type: object
                    required:
                      [
                        schema,
                        registryVersion,
                        evaluatedAt,
                        entry,
                        observedIssuerBinding,
                        evaluation,
                      ]
                    properties:
                      schema:
                        type: string
                        const: insight.rwa-instrument-admission.v1
                      registryVersion:
                        type: string
                      evaluatedAt:
                        type: integer
                      entry:
                        type: [object, 'null']
                        description: Committed instrument, FIGI, MIC and issuer binding record.
                      observedIssuerBinding:
                        type: object
                        description: Current issuer UID, ISIN, chain and token contract observation.
                      evaluation:
                        type: object
                        required:
                          [
                            identityStatus,
                            reasonCodes,
                            productionIdentityAdmitted,
                            countsTowardOracleQuorum,
                            mayAuthorizeExecution,
                          ]
                        properties:
                          identityStatus:
                            type: string
                            enum: [MATCH, MISMATCH, NOT_FOUND]
                          reasonCodes:
                            type: array
                            items:
                              type: string
                          productionIdentityAdmitted:
                            type: boolean
                          countsTowardOracleQuorum:
                            type: boolean
                            const: false
                          mayAuthorizeExecution:
                            type: boolean
                            const: false
        '400':
          description: Invalid or unsupported Stock Token symbol
        '401':
          description: API key required
        '502':
          description: Robinhood issuer-context service unavailable or returned invalid data
  /execution/attestation/issue:
    post:
      operationId: issueExecutionReceipt
      tags: [Execution Evidence]
      summary: Issue a durable signed Execution Receipt
      description: Collects settlement facts on chain, verifies both pre-trade gates, signs the result, and durably stores the complete envelope before returning it. Cross-chain settlements and caller-selected post-settlement policies are rejected.
      security:
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ExecutionIssueRequest'
      responses:
        '200':
          description: Receipt signed and persisted
          content:
            application/json:
              schema:
                type: object
        '400':
          description: Invalid or unprovable execution binding
        '503':
          description: Signing or durable persistence unavailable

  /execution/attestation/issue/journey:
    post:
      operationId: redeemSwapIntentReceipt
      tags: [Execution Evidence]
      summary: Redeem the included Swap Intent Execution Receipt
      description: |
        Redeems the single receipt credit created by a settled x402 Swap Intent.
        The caller must present the opaque `journeyId`, its caller-held
        `outcomeToken`, both signed Pre-Trade gates, and the settlement transaction.
        Both gates are signature-verified and must match the journey. This route
        does not accept an API key in place of the one-time capability.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              allOf:
                - $ref: '#/components/schemas/ExecutionIssueRequest'
                - type: object
                  required: [journeyId, outcomeToken, destinationPreTradeUid, preTradeAttestations]
                  properties:
                    journeyId:
                      type: string
                      format: uuid
                    outcomeToken:
                      type: string
                      minLength: 32
                      description: Caller-held one-time lifecycle capability; do not log it.
      responses:
        '200':
          description: Signed receipt issued, or the exact same persisted receipt returned idempotently.
        '404':
          description: Unknown journey or invalid caller capability.
        '409':
          description: Settlement is still pending, a receipt is being issued, or the credit is unavailable.
        '503':
          description: Durable receipt finalization temporarily unavailable; retry the identical request.

  /execution/solana/collect:
    post:
      operationId: collectSolanaExecutionFacts
      tags: [Execution Evidence]
      summary: Collect unsigned Solana balance facts
      description: |
        Reads a confirmed Solana mainnet-beta transaction and measures the taker's
        net wallet-owned SPL or Token-2022 balance changes and/or native SOL lamport
        change across the full transaction. This endpoint returns unsigned facts.
        SOL movements include rent, tips and unrelated instructions, so they do not
        produce an attributed execution price.
      security:
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [signature, sourceAssetId, destinationAssetId, taker]
              properties:
                signature:
                  type: string
                  minLength: 87
                  maxLength: 88
                  description: Base58 Solana transaction signature.
                sourceAssetId:
                  type: string
                  description: CAIP-19 SOL ID solana:0/slip44:501 or SPL/Token-2022 ID solana:0/spl:<mint>.
                destinationAssetId:
                  type: string
                  description: CAIP-19 SOL ID solana:0/slip44:501 or SPL/Token-2022 ID solana:0/spl:<mint>.
                taker:
                  type: string
                  minLength: 32
                  maxLength: 44
                  description: Base58 wallet public key whose token-account and/or lamport changes are measured.
      responses:
        '200':
          description: Collection result; inspect data.collection.ok and data.signed.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      signed:
                        type: boolean
                        const: false
                      assertionScope:
                        type: [string, 'null']
                        enum:
                          [
                            NET_WALLET_OWNED_SPL_BALANCE_DELTA,
                            NET_WALLET_LAMPORT_AND_SPL_BALANCE_DELTA,
                            null,
                          ]
                      collection:
                        type: object
                        description: 'Either { ok: true, facts } or { ok: false, code, message }.'
        '400':
          description: Invalid request body
        '401':
          description: API key required
        '402':
          description: Credit balance insufficient

  /execution/solana/receipt:
    post:
      operationId: issueSolanaExecutionReceipt
      tags: [Execution Evidence]
      summary: Issue signed Solana execution evidence
      description: |
        Reads a confirmed mainnet-beta transaction and signs bounded wallet-level
        SPL/Token-2022 and native SOL balance-delta facts with the dedicated Insight
        Ed25519 Solana evidence key. It does not attribute arbitrary instruction
        semantics, venue fills, or SOL transfers. The response includes a SHA-256
        context commitment over the complete signed receipt.
      security:
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [signature, sourceAssetId, destinationAssetId, taker]
              properties:
                signature:
                  {
                    type: string,
                    minLength: 87,
                    maxLength: 88,
                    description: Base58 Solana transaction signature.,
                  }
                sourceAssetId:
                  { type: string, description: CAIP-19 native SOL or SPL/Token-2022 asset ID. }
                destinationAssetId:
                  { type: string, description: CAIP-19 native SOL or SPL/Token-2022 asset ID. }
                taker:
                  {
                    type: string,
                    minLength: 32,
                    maxLength: 44,
                    description: Base58 wallet whose balance changes are measured.,
                  }
      responses:
        '200':
          description: Ed25519-signed execution evidence and context commitment.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    required: [receipt, contextCommitment, signerPublicKey]
                    properties:
                      receipt:
                        {
                          type: object,
                          description: insight.solana-execution-receipt.v1 signed envelope.,
                        }
                      contextCommitment:
                        {
                          type: object,
                          description: SHA-256 commitment over canonical receipt JSON.,
                        }
                      signerPublicKey:
                        {
                          type: string,
                          description: Base58 Ed25519 public key; consumers must independently pin it.,
                        }
        '400': { description: Invalid request or unsupported asset pair. }
        '401': { description: API key required. }
        '402': { description: Credit balance insufficient. }
        '503': { description: Dedicated Solana evidence signer unavailable. }

  /execution/solana/simulate:
    post:
      operationId: simulateSolanaTransaction
      tags: [Execution Evidence]
      summary: Simulate and sign a Solana pre-sign receipt
      description: |
        Simulates an unsigned serialized legacy, v0, or v1 transaction on
        mainnet-beta at confirmed commitment with signature verification disabled.
        All signature slots must be zero. It checks the
        exact message SHA-256 against expectedMessageHash and signs the simulation
        result. Simulation is a state snapshot and does not predict landing or
        subsequent state changes.
      security:
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [transactionBase64, expectedMessageHash]
              properties:
                transactionBase64:
                  {
                    type: string,
                    minLength: 8,
                    maxLength: 12000,
                    description: Serialized Solana transaction in base64.,
                  }
                expectedMessageHash:
                  {
                    type: string,
                    pattern: '^0x[0-9a-fA-F]{64}$',
                    description: SHA-256 digest of the exact serialized message bytes.,
                  }
      responses:
        '200':
          description: Ed25519-signed simulation evidence and context commitment.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    required: [receipt, contextCommitment, signerPublicKey]
                    properties:
                      receipt:
                        {
                          type: object,
                          description: insight.solana-simulation-receipt.v1 signed envelope.,
                        }
                      contextCommitment:
                        {
                          type: object,
                          description: SHA-256 commitment over canonical receipt JSON.,
                        }
                      signerPublicKey:
                        {
                          type: string,
                          description: Base58 Ed25519 public key; consumers must independently pin it.,
                        }
        '400': { description: Invalid/signed transaction or expected message hash mismatch. }
        '401': { description: API key required. }
        '402': { description: Credit balance insufficient. }
        '503': { description: Dedicated Solana evidence signer or RPC unavailable. }

  /execution/attestation/verify:
    post:
      operationId: verifyExecutionReceipt
      tags: [Execution Evidence]
      summary: Verify one Execution Receipt
      description: Recomputes its UID and signature and requires a registry-authorised production signer. Public and unmetered.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [attestation]
              properties:
                policyId:
                  $ref: '#/components/schemas/ImmutablePartnerPolicyId'
                  description: Optional only for generic or historical verification. Partner production integrations must use the partner-scoped route below.
                attestation:
                  $ref: '#/components/schemas/ExecutionReceipt'
      responses:
        '200':
          description: Verification result; inspect valid, cryptographicValid, trustedAttester, expired and reason

  /execution/attestation/verify-pair:
    post:
      operationId: verifyExecutionPair
      tags: [Execution Evidence]
      summary: Verify the pre-trade → settlement closed loop
      description: Verifies signatures, production-key trust, exact signed bindings, authorising verdicts, and that settlement occurred inside every signed gate window. Historical expired envelopes remain verifiable.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [preTradeAttestation, executionReceipt]
              properties:
                policyId:
                  $ref: '#/components/schemas/ImmutablePartnerPolicyId'
                  description: Optional only for generic or historical verification. Partner production integrations must use the partner-scoped route below.
                preTradeAttestation:
                  type: object
                  additionalProperties: true
                destinationPreTradeAttestation:
                  type: object
                  additionalProperties: true
                executionReceipt:
                  $ref: '#/components/schemas/ExecutionReceipt'
      responses:
        '200':
          description: Cryptographic closed-loop verification result

  /partners/{partnerId}/execution/attestation/verify:
    parameters:
      - $ref: '#/components/parameters/PartnerId'
    get:
      operationId: getPartnerExecutionVerificationContract
      tags: [Execution Evidence]
      summary: Resolve the policy-mandatory partner verification contract
      description: Returns the exact active policy id and production reachability for this partner path.
      security: []
      responses:
        '200':
          description: Current partner runtime contract
        '400':
          description: Unknown partner id
    post:
      operationId: verifyPartnerExecutionReceipt
      tags: [Execution Evidence]
      summary: Verify one Execution Receipt under the active partner policy
      description: Fails closed unless policyId is the exact immutable policy currently activated for partnerId, production reachability is enabled, and the receipt schema/profile is admitted. The policy is selected by the verifier and is never trusted from receipt data.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [policyId, attestation]
              properties:
                policyId:
                  $ref: '#/components/schemas/ImmutablePartnerPolicyId'
                attestation:
                  $ref: '#/components/schemas/ExecutionReceipt'
      responses:
        '200':
          description: Policy-bound verification result; valid is false for stale, cross-partner, disabled, or unadmitted policy input
        '400':
          description: Missing/malformed policy id, partner id, or receipt envelope

  /partners/{partnerId}/execution/attestation/verify-pair:
    parameters:
      - $ref: '#/components/parameters/PartnerId'
    get:
      operationId: getPartnerExecutionPairVerificationContract
      tags: [Execution Evidence]
      summary: Resolve the policy-mandatory partner pair contract
      description: Returns the exact active policy id and production reachability for this partner path.
      security: []
      responses:
        '200':
          description: Current partner runtime contract
        '400':
          description: Unknown partner id
    post:
      operationId: verifyPartnerExecutionPair
      tags: [Execution Evidence]
      summary: Verify the closed loop under the active partner policy
      description: Applies exact partner/policy activation, production reachability, and receipt schema/profile admission in addition to the cryptographic pair checks.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [policyId, preTradeAttestation, executionReceipt]
              properties:
                policyId:
                  $ref: '#/components/schemas/ImmutablePartnerPolicyId'
                preTradeAttestation:
                  type: object
                  additionalProperties: true
                destinationPreTradeAttestation:
                  type: object
                  additionalProperties: true
                executionReceipt:
                  $ref: '#/components/schemas/ExecutionReceipt'
      responses:
        '200':
          description: Policy-bound cryptographic closed-loop verification result
        '400':
          description: Missing/malformed policy id, partner id, or receipt envelope

  /partners/{partnerId}/safety/pre-trade:
    parameters:
      - $ref: '#/components/parameters/PartnerId'
    get:
      operationId: issuePartnerPreTradeSafetyGate
      tags: [Safety]
      summary: Issue a policy-bound one-time VERITAS pre-trade gate (inactive candidate)
      description: |
        This candidate route fails closed until the exact immutable VERITAS 1800-second
        policy is separately activated. It also requires the dedicated API-key ID,
        a selected one-time UTC window, the fixed v3 WETH/USDC trade and the
        request/signature cutoffs. The public pre-trade endpoint and registered
        selection rule remain at 600 seconds. A successful call does not authorize
        any Bitcoin or Ethereum broadcast.
      security:
        - apiKey: []
      parameters:
        - name: policyId
          in: query
          required: true
          schema:
            $ref: '#/components/schemas/ImmutablePartnerPolicyId'
        - name: asset
          in: query
          required: true
          schema:
            type: string
            enum: [WETH, USDC]
        - name: destinationAsset
          in: query
          required: true
          schema:
            type: string
            enum: [WETH, USDC]
        - name: chainId
          in: query
          required: true
          schema:
            type: integer
            enum: [1]
        - name: action
          in: query
          required: true
          schema:
            type: string
            enum: [swap]
        - name: tradeAmountUsd
          in: query
          required: true
          schema:
            type: number
            enum: [50000]
        - name: schemaVersion
          in: query
          required: true
          schema:
            type: integer
            enum: [3]
      responses:
        '200':
          description: Signed 1800-second v3 gate if every policy and window condition holds
        '400':
          description: Partner, policy, trade, key, or window condition failed
        '402':
          $ref: '#/components/responses/CreditExhausted'

  /execution/attestation/{uid}:
    get:
      operationId: getExecutionReceipt
      tags: [Execution Evidence]
      summary: Retrieve a durable receipt by UID
      description: Returns the complete signed envelope. The 32-byte UID acts as an unguessable content identifier.
      security: []
      parameters:
        - name: uid
          in: path
          required: true
          schema:
            type: string
            pattern: '^0x[0-9a-fA-F]{64}$'
      responses:
        '200':
          description: Complete persisted signed envelope
        '404':
          $ref: '#/components/responses/NotFound'

  # ── Public ──────────────────────────────────────────────
  /health:
    get:
      operationId: getHealth
      tags: [Public]
      summary: Health check
      description: Public endpoint to verify that the API is available.
      security: []
      responses:
        '200':
          description: API is healthy
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HealthResponse'

  /health/ping:
    get:
      operationId: getHealthPing
      tags: [Public]
      summary: Lightweight liveness ping
      description: >-
        Zero-dependency liveness surface consumed by the Cloudflare sentinel's
        5-minute HTTP probe. Returns a constant body and never touches any
        database; deep dependency checks live on /health/ready?deep=1.
        The route bundle must stay free of shared handler/billing imports.
      security: []
      responses:
        '200':
          description: Service is live
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    example: live
                  timestamp:
                    type: integer
                    format: int64

  /symbols:
    get:
      operationId: getSymbols
      tags: [Public]
      summary: Supported symbols
      description: List all asset symbols supported by the platform. Public, no authentication required.
      security: []
      responses:
        '200':
          description: Symbol list
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SymbolsResponse'

  /metrics:
    get:
      operationId: getMetrics
      tags: [Public]
      summary: Platform overview metrics
      description: High-level platform metrics — provider count, active feeds, symbols, chains, and top providers.
      security:
        - apiKey: []
      responses:
        '200':
          description: Platform metrics
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MetricsResponse'

  # ── DEX Markets ─────────────────────────────────────────
  /markets/dex/monad:
    get:
      operationId: getMonadDexMarket
      tags: [DEX Markets]
      summary: Monad WMON/USDC on-chain market evidence
      description: >-
        Returns a block-pinned, Factory-verified Uniswap V3 WMON/USDC snapshot
        on Monad: spot, a 15-minute TWAP, active liquidity, token balances,
        and fixed-size Quoter V2 execution quotes. Finalized Swap-event volume
        is returned only after the contiguous local index covers each window.
        This is DEX execution evidence, not an oracle feed and never an oracle-consensus vote.
      security:
        - apiKey: []
      responses:
        '200':
          description: Fresh block-pinned Monad DEX market evidence.
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success:
                    type: boolean
                    const: true
                  data:
                    type: object
                    required: [source, venue, chainId, market, block, spot, twap, quotes, volume]
                    properties:
                      source: { type: string, const: dex-market }
                      venue: { type: string, const: uniswap-v3 }
                      chainId: { type: integer, const: 143 }
                      market: { type: string, const: MON/USDC }
                      block:
                        type: object
                        required: [number, hash, timestamp]
                      spot:
                        type: object
                        required: [tick, usdcPerWmon]
                      twap:
                        type: object
                        required: [windowSeconds, tick, usdcPerWmon, deviationBpsFromSpot]
                      quotes:
                        type: array
                        items:
                          type: object
                          required:
                            [amountInWmon, amountOutUsdc, effectiveUsdcPerWmon, priceImpactBps]
                      volume:
                        type: object
                        description: Null volume fields mean the finalized event index is warming or unavailable, never zero volume.
        '503':
          description: Fresh Monad DEX evidence is unavailable.

  /markets/dex/monad/hanji:
    get:
      operationId: getHanjiMonadMarket
      tags: [DEX Markets]
      summary: Monad Hanji MON/USDC CLOB market context
      description: >-
        Returns bounded, read-only Hanji MON/USDC CLOB context: a fresh public
        L2 order book, displayed-depth and two-sided impact estimates, plus
        block-pinned code identity checks for the reviewed order-book and
        fast-quoter proxies and their implementations. It is venue context,
        not an oracle feed, executable quote, order simulation, margin action,
        or settlement guarantee.
      security:
        - apiKey: []
      responses:
        '200':
          description: Fresh Hanji Monad CLOB market evidence.
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success: { type: boolean, const: true }
                  data:
                    type: object
                    required:
                      [source, venue, chainId, market, block, contracts, book, estimates, caveats]
                    properties:
                      source: { type: string, const: dex-market }
                      venue: { type: string, const: hanji }
                      chainId: { type: integer, const: 143 }
                      market: { type: string, const: MON/USDC }
                      sourceFreshnessSeconds: { type: number, minimum: 0 }
                      observedAt: { type: string, format: date-time }
                      block: { type: object }
                      contracts: { type: object }
                      book:
                        type: object
                        required: [timestamp, bestBidUsdcPerMon, bestAskUsdcPerMon, spreadBps]
                      estimates:
                        type: array
                        items:
                          type: object
                          required:
                            [side, targetNotionalUsdc, filledNotionalUsdc, filledMon, complete]
                      caveats:
                        type: array
                        items: { type: string }
        '503':
          description: Fresh Hanji Monad CLOB evidence is unavailable.

  /markets/dex/base:
    get:
      operationId: getBaseDexMarket
      tags: [DEX Markets]
      summary: Base WETH/USDC on-chain market evidence
      description: >-
        Returns a block-pinned, Factory-verified Uniswap V3 WETH/USDC snapshot
        on Base: spot, a 30-minute TWAP, active in-range liquidity, token
        balances, and fixed-size Quoter V2 exact-input quotes. This is one DEX
        market source, not an oracle feed, consensus vote, or statement about
        every Base route.
      security:
        - apiKey: []
      responses:
        '200':
          description: Fresh block-pinned Base DEX market evidence.
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success:
                    type: boolean
                    const: true
                  data:
                    type: object
                    required: [source, venue, chainId, market, block, spot, twap, quotes]
                    properties:
                      source: { type: string, const: dex-market }
                      venue: { type: string, const: uniswap-v3 }
                      chainId: { type: integer, const: 8453 }
                      market: { type: string, const: WETH/USDC }
                      block:
                        type: object
                        required: [number, hash, timestamp]
                      spot:
                        type: object
                        required: [tick, token1PerToken0]
                      twap:
                        type: object
                        required: [windowSeconds, tick, token1PerToken0, deviationBpsFromSpot]
                      quotes:
                        type: array
                        items:
                          type: object
                          required: [amountIn, amountOut, effectiveToken1PerToken0, priceImpactBps]
        '503':
          description: Fresh Base DEX evidence is unavailable.

  /markets/dex/base/quickswap:
    get:
      operationId: getQuickSwapV2BaseMarket
      tags: [DEX Markets]
      summary: Base QuickSwap V2 USDC/USDT market evidence
      description: >-
        Returns block-pinned, code-identity-verified evidence for one reviewed
        Base QuickSwap V2 USDC/USDT pair: Factory, Router, Pair, token
        bindings, reserves, spot, and a bounded exact-input quote ladder.
        This is read-only venue context, not a generic QuickSwap route,
        executable transaction, or oracle-consensus input. The response's
        executionReadiness field is authoritative and remains fail-closed when
        reserves are insufficient.
      security:
        - apiKey: []
      responses:
        '200':
          description: Fresh block-pinned QuickSwap V2 market evidence.
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success: { type: boolean, const: true }
                  data:
                    type: object
                    required:
                      [
                        source,
                        venue,
                        chainId,
                        market,
                        block,
                        contracts,
                        reserves,
                        executionReadiness,
                        spot,
                        quotes,
                        caveats,
                      ]
                    properties:
                      source: { type: string, const: dex-market }
                      venue: { type: string, const: quickswap-v2 }
                      chainId: { type: integer, const: 8453 }
                      market: { type: string, const: USDC/USDT }
                      sourceFreshnessSeconds: { type: number, minimum: 0 }
                      observedAt: { type: string, format: date-time }
                      block: { type: object }
                      contracts: { type: object }
                      reserves:
                        type: object
                        required: [token0Raw, token0, token1Raw, token1]
                      executionReadiness:
                        type: object
                        required: [status, reason]
                        properties:
                          status: { type: string, enum: [unavailable, review-required] }
                          reason: { type: string }
                      spot:
                        type: object
                        required: [token1PerToken0]
                      quotes:
                        type: array
                        items:
                          type: object
                          required:
                            [
                              amountIn,
                              amountInRaw,
                              amountOut,
                              amountOutRaw,
                              effectiveToken1PerToken0,
                              priceImpactBps,
                            ]
                      caveats:
                        type: array
                        items: { type: string }
        '503':
          description: Fresh QuickSwap V2 Base market evidence is unavailable.

  /markets/dex/aerodrome:
    get:
      operationId: getAerodromeSlipstreamMarket
      tags: [DEX Markets]
      summary: Base Aerodrome Slipstream WETH/USDC market evidence
      description: >-
        Returns a block-pinned, code-identity-verified Aerodrome Slipstream
        WETH/USDC CL100 snapshot on Base: spot, a 30-minute TWAP, active
        in-range liquidity, token balances, the live pool fee, and fixed-size
        QuoterV2 exact-input quotes. Factory, QuoterV2, and Pool runtime
        hashes are re-verified against the reviewed allowlist at the quoted
        block. This is evidence for one reviewed pool, not an oracle feed,
        consensus vote, executable route, or statement about every Aerodrome
        or Base route.
      security:
        - apiKey: []
      responses:
        '200':
          description: Fresh block-pinned Aerodrome Slipstream market evidence.
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success:
                    type: boolean
                    const: true
                  data:
                    type: object
                    required:
                      [
                        source,
                        venue,
                        chainId,
                        market,
                        block,
                        contracts,
                        spot,
                        twap,
                        activeLiquidityRaw,
                        poolBalances,
                        quotes,
                        caveats,
                      ]
                    properties:
                      source: { type: string, const: dex-market }
                      venue: { type: string, const: aerodrome-slipstream }
                      chainId: { type: integer, const: 8453 }
                      market: { type: string, const: WETH/USDC }
                      sourceFreshnessSeconds: { type: integer, minimum: 0 }
                      observedAt: { type: string, format: date-time }
                      block:
                        type: object
                        required: [number, hash, timestamp]
                        properties:
                          number: { type: string, pattern: '^[0-9]+$' }
                          hash: { type: string, pattern: '^0x[0-9a-fA-F]{64}$' }
                          timestamp: { type: string, format: date-time }
                      contracts:
                        type: object
                        required: [factory, quoterV2, pool, token0, token1, tickSpacing, feePips]
                        properties:
                          factory: { type: string, pattern: '^0x[0-9a-fA-F]{40}$' }
                          quoterV2: { type: string, pattern: '^0x[0-9a-fA-F]{40}$' }
                          pool: { type: string, pattern: '^0x[0-9a-fA-F]{40}$' }
                          token0: { type: string, pattern: '^0x[0-9a-fA-F]{40}$' }
                          token1: { type: string, pattern: '^0x[0-9a-fA-F]{40}$' }
                          tickSpacing: { type: integer, const: 100 }
                          feePips: { type: integer, minimum: 0 }
                      spot:
                        type: object
                        required: [tick, token1PerToken0]
                      twap:
                        type: object
                        required: [windowSeconds, tick, token1PerToken0, deviationBpsFromSpot]
                      activeLiquidityRaw: { type: string, pattern: '^[0-9]+$' }
                      poolBalances:
                        type: object
                        required: [token0Raw, token0, token1Raw, token1]
                      quotes:
                        type: array
                        items:
                          type: object
                          required:
                            [
                              amountIn,
                              amountInRaw,
                              amountOut,
                              amountOutRaw,
                              effectiveToken1PerToken0,
                              initializedTicksCrossed,
                              priceImpactBps,
                            ]
                      caveats:
                        type: array
                        items: { type: string }
        '503':
          description: Fresh Aerodrome Slipstream evidence is unavailable.

  /markets/dex/pancakeswap:
    get:
      operationId: getPancakeSwapV3Market
      tags: [DEX Markets]
      summary: Base PancakeSwap V3 USDC/USDT market evidence
      description: >-
        Returns block-pinned, code-identity-verified PancakeSwap V3 evidence
        for the reviewed Base USDC/USDT 0.01% pool. It is one venue witness,
        not an oracle consensus input or a general PancakeSwap route quote.
      security:
        - apiKey: []
      responses:
        '200':
          description: Fresh block-pinned PancakeSwap V3 market evidence.
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success: { type: boolean, const: true }
                  data:
                    type: object
                    required: [source, venue, chainId, market, block, contracts, spot, twap, quotes]
                    properties:
                      source: { type: string, const: dex-market }
                      venue: { type: string, const: uniswap-v3 }
                      chainId: { type: integer, const: 8453 }
                      market: { type: string, const: USDC/USDT }
                      block: { type: object }
                      contracts: { type: object }
                      spot: { type: object }
                      twap: { type: object }
                      quotes: { type: array, items: { type: object } }
        '503':
          description: Fresh PancakeSwap V3 market evidence is unavailable.

  /markets/dex/base/venues:
    get:
      operationId: getBaseDexVenueIntegrations
      tags: [DEX Markets]
      summary: Reviewed Base DEX deployment identities
      description: >-
        Re-verifies pinned runtime bytecode for Insight's reviewed Base DEX
        deployments at one block. The response distinguishes deployment
        evidence from pool-specific execution support; dynamic hooks, fees,
        bins, and Curve invariants are fail-closed until separately reviewed.
      security:
        - apiKey: []
      responses:
        '200':
          description: Fresh pinned Base DEX deployment evidence.
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success: { type: boolean, const: true }
                  data:
                    type: object
                    required: [source, chainId, block, venues]
                    properties:
                      source: { type: string, const: dex-deployment }
                      chainId: { type: integer, const: 8453 }
                      block: { type: object }
                      venues: { type: array, items: { type: object } }
        '503':
          description: Fresh Base DEX deployment evidence is unavailable.

  /markets/dex/solana:
    get:
      operationId: getSolanaDexRoute
      tags: [DEX Markets]
      summary: Solana SOL/USDC route evidence
      description: >-
        Returns an authenticated Jupiter exact-input SOL/USDC quote ladder with
        its selected AMM route, Jupiter context slot, and a verified Solana
        mainnet-beta finalized RPC witness. This is an aggregator route quote,
        not a block-pinned single-pool read, transaction simulation, or landing
        guarantee. Use the signed Solana simulation endpoint for an exact
        prepared transaction before authorization.
      security:
        - apiKey: []
      responses:
        '200':
          description: Fresh Solana route evidence.
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success:
                    type: boolean
                    const: true
                  data:
                    type: object
                    required: [source, venue, network, market, finalizedSlot, quotes]
                    properties:
                      source: { type: string, const: dex-route }
                      venue: { type: string, const: jupiter }
                      network: { type: string, const: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' }
                      market: { type: string, const: SOL/USDC }
                      finalizedSlot: { type: integer, minimum: 0 }
                      quotes:
                        type: array
                        items:
                          type: object
                          required: [amountInRaw, amountOutRaw, priceImpactPct, contextSlot, route]
        '503':
          description: Fresh Solana route evidence is unavailable.

  /markets/dex/hyperliquid:
    get:
      operationId: getHyperliquidPerpMarket
      tags: [DEX Markets]
      summary: Hyperliquid perpetual CLOB market evidence
      description: >-
        Returns fresh, read-only Hyperliquid mainnet perpetual-market context
        for a reviewed BTC, ETH, or HYPE market: exchange-reported mark, mid,
        oracle, funding, open interest and 24-hour notional volume, plus a
        fresh L2 book witness, displayed depth, and bounded two-sided impact
        estimates. This is one exchange's CLOB context, not an oracle feed,
        consensus vote, or executable quote. It never signs, simulates, or
        submits an order.
      security:
        - apiKey: []
      parameters:
        - name: market
          in: query
          required: false
          description: Reviewed Hyperliquid perpetual market. Defaults to BTC.
          schema:
            type: string
            enum: [BTC, ETH, HYPE]
            default: BTC
      responses:
        '200':
          description: Fresh reviewed Hyperliquid perpetual-market evidence.
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success:
                    type: boolean
                    const: true
                  data:
                    type: object
                    required: [source, venue, network, market, coin, book, perpetual, estimates]
                    properties:
                      source: { type: string, const: dex-market }
                      venue: { type: string, const: hyperliquid-perp }
                      network: { type: string, const: hyperliquid:mainnet }
                      market: { type: string, example: BTC-PERP }
                      coin: { type: string, enum: [BTC, ETH, HYPE] }
                      sourceFreshnessSeconds: { type: number, minimum: 0 }
                      book:
                        type: object
                        required:
                          [
                            timestamp,
                            displayedLevelsPerSide,
                            bestBid,
                            bestAsk,
                            spreadBps,
                            bidDepthNotionalUsd,
                            askDepthNotionalUsd,
                          ]
                      perpetual:
                        type: object
                        required:
                          [
                            markPrice,
                            midPrice,
                            oraclePrice,
                            markDeviationBpsFromOracle,
                            fundingRate,
                            openInterest,
                            dayNotionalVolume,
                            sizeDecimals,
                            maxLeverage,
                          ]
                      estimates:
                        type: array
                        items:
                          type: object
                          required:
                            [
                              side,
                              targetNotionalUsd,
                              filledNotionalUsd,
                              filledBase,
                              averagePrice,
                              priceImpactBps,
                              complete,
                            ]
        '400':
          description: The market is not in Insight's reviewed Hyperliquid perpetual allowlist.
        '503':
          description: Fresh Hyperliquid perpetual-market evidence is unavailable.

  /markets/settlement-evidence:
    get:
      operationId: getSettlementEvidence
      tags: [Execution Evidence]
      summary: Signed prediction-market settlement evidence
      description: >-
        Returns Insight's independently derived settlement-evidence pack for a
        prediction-market price contract: the market's declared resolution
        compared against independent sources (settlement-window derived
        analytics and Insight's own oracle-consensus snapshots), with an EIP-712
        attestation when the pack is signed. With the `slug` query parameter a
        single pack is returned; without it the most recent packs are listed.
        Packs carry derived analytics only — settlement-window venue candles
        stay internal because their source is vendor-licensed
        derived-analytics-only.
      security:
        - apiKey: []
      parameters:
        - name: slug
          in: query
          required: false
          description: >-
            Market slug of a watched prediction-market price contract. Omit to
            list the most recent packs.
          schema:
            type: string
            maxLength: 256
        - name: limit
          in: query
          required: false
          description: Maximum number of packs when listing. Defaults to 20.
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
      responses:
        '200':
          description: Settlement-evidence pack(s).
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success:
                    type: boolean
                    const: true
                  data:
                    type: object
                    properties:
                      pack:
                        $ref: '#/components/schemas/SettlementEvidencePack'
                      packs:
                        type: array
                        items:
                          $ref: '#/components/schemas/SettlementEvidencePack'
                      count: { type: integer, minimum: 0 }
                      rightsNotice: { type: string }
                      requestId: { type: string }
        '404':
          description: No settlement-evidence pack exists for this market. Packs are produced after a market resolves.
        '503':
          description: Settlement evidence is temporarily unavailable (infrastructure state; retryable).

  /markets/settlement-evidence/grade:
    post:
      operationId: gradeSettlementEvidence
      tags: [Execution Evidence]
      summary: On-demand signed settlement-evidence record (legacy) 🔒
      description: >-
        Legacy, idempotent historical record of one settled prediction-market
        price contract. The request carries a market slug ONLY; the declared
        outcome is always read from the Insight watch list, never from the
        caller. Returns a signed EIP-712 evidence pack carrying derived
        analytics: declared versus independently observed outcome, bps
        deltas, and coverage statistics. The grade describes a market that
        has already resolved. It is NOT a safety assessment, NOT a
        recommendation, and NOT a verdict about any live configuration.
        Retained for existing integrations. For a signed, advisory,
        independently recomputable record of an oracle configuration and its
        source state, use POST /api/v1/oracle-config/snapshot instead.
        An existing persisted pack is returned cached and is never downgraded.

        **x402-metered** (merchant-configured payment rail) or API key.
      security:
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [slug]
              properties:
                slug:
                  type: string
                  minLength: 1
                  maxLength: 200
                  description: Market slug of a watched prediction-market price contract.
      responses:
        '200':
          description: Evidence pack (freshly graded or cached).
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success:
                    type: boolean
                    const: true
                  data:
                    type: object
                    required: [pack, grade, attested, cached, rightsNotice]
                    properties:
                      pack:
                        $ref: '#/components/schemas/SettlementEvidencePack'
                      grade:
                        type: string
                        enum: [consistent, inconsistent, insufficient_data]
                      attested: { type: boolean }
                      cached: { type: boolean }
                      rightsNotice: { type: string }
        '400':
          description: 'VALIDATION_ERROR — body must be a JSON object with a non-empty string field "slug".'
        '404':
          description: 'WATCH_MARKET_NOT_FOUND — slug is not in the settlement watch list.'
        '409':
          description: 'Window not resolved yet (WINDOW_NOT_RESOLVED) or market has no declared outcome (MARKET_UNRESOLVED).'
        '410':
          description: 'WINDOW_TOO_OLD — the window predates the candle source retention.'

  # ── Prices ──────────────────────────────────────────────
  /oracle-config/snapshot:
    post:
      operationId: createOracleConfigSnapshot
      tags: [Execution Evidence]
      summary: Signed, advisory oracle config snapshot 🔒
      description: >-
        Paid, idempotent, on-demand record of ONE oracle configuration and its
        independent-source state at a point in time. This is an advisory INPUT
        record, not a safety assessment: it states what was observable and does
        not assert that a configuration is safe or unsafe, and does not
        recommend parameter changes.

        The request is strict and names chainId, protocolId and assetSymbol
        ONLY. Caller-supplied feed lists, parameters, source claims or declared
        outcomes are rejected. All observable state is read server-side from
        the live feed registry, the Chainlink feed config and the
        reviewed-profile registry. Returns configHash, checksHash, a D1-D6
        check record, the observed source state and an EIP-712 attestation
        with no expiry, so the holder can verify the record offline later.
        Within one hour bucket an identical configuration yields a
        byte-identical payload and typed-data hash.

        **x402-metered** (merchant-configured payment rail) or API key.
      security:
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [chainId, protocolId, assetSymbol]
              additionalProperties: false
              properties:
                chainId:
                  type: integer
                  minimum: 1
                  description: EVM chain id of the configuration.
                protocolId:
                  type: string
                  minLength: 1
                  maxLength: 120
                  description: Reviewed protocol or vault identifier.
                assetSymbol:
                  type: string
                  minLength: 1
                  maxLength: 40
                  description: Collateral or loan asset symbol.
      responses:
        '200':
          description: Signed snapshot record.
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success:
                    type: boolean
                    const: true
                  data:
                    type: object
                    required: [snapshot, attested, idempotent, advisory, rightsNotice]
                    properties:
                      snapshot:
                        type: object
                        description: payload, payloadHash and nullable attestation.
                      attested: { type: boolean }
                      idempotent: { type: boolean }
                      advisory: { type: boolean, const: true }
                      rightsNotice: { type: string }
        '400':
          description: 'VALIDATION_ERROR — strict body violation or caller-supplied configuration claim.'

  /prices:
    get:
      operationId: getPrice
      tags: [Prices]
      summary: Latest price
      description: Fetch the latest price for a symbol from a supported oracle provider.
      security:
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/provider'
        - $ref: '#/components/parameters/symbol'
        - $ref: '#/components/parameters/chain'
        - $ref: '#/components/parameters/forceRefresh'
      responses:
        '200':
          description: Price data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PriceResponse'
        '404':
          $ref: '#/components/responses/NotFound'

  /prices/batch:
    post:
      operationId: batchPrices
      tags: [Prices]
      summary: Batch price query
      description: Query prices for up to 20 asset/provider combinations in a single request.
      security:
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BatchPriceRequest'
      responses:
        '200':
          description: Batch price results
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BatchPriceResponse'

  /prices/consensus:
    get:
      operationId: getConsensusPrice
      tags: [Consensus]
      summary: Consensus price 🔒
      description: |
        Aggregate real-time prices from every active oracle provider for a symbol,
        compute a tamper-resistant consensus price, and identify outliers.
        Returns per-provider deviation from consensus, confidence level, agreement score,
        and a recommended provider.

        **Credit-metered** — any API key with sufficient credit balance.
      security:
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/symbol'
        - $ref: '#/components/parameters/chain'
        - name: method
          in: query
          description: Consensus aggregation method. Use auto for the asset-category recommendation; omission preserves the weighted_median default.
          schema:
            type: string
            enum: [auto, median, trimmed_mean, weighted_median, iqr_filtered]
            default: weighted_median
      responses:
        '200':
          description: Consensus price data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ConsensusPriceResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'
        '404':
          $ref: '#/components/responses/NotFound'

  /prices/history:
    get:
      operationId: getPriceHistory
      tags: [Prices]
      summary: Historical prices
      description: Fetch historical price data for a symbol over a given period.
      security:
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/provider'
        - $ref: '#/components/parameters/symbol'
        - $ref: '#/components/parameters/chain'
        - name: period
          in: query
          required: true
          description: Number of hours to look back (1–2160, i.e. up to 90 days)
          schema:
            type: integer
            minimum: 1
            maximum: 2160
        - $ref: '#/components/parameters/forceRefresh'
      responses:
        '200':
          description: Historical price data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HistoryPriceResponse'

  # ── Feeds ───────────────────────────────────────────────
  /feeds:
    get:
      operationId: listFeeds
      tags: [Feeds]
      summary: List oracle feeds
      description: Query the oracle feed registry with filters. Returns feed metadata, contract addresses, and health indicators.
      security:
        - apiKey: []
      parameters:
        - name: provider
          in: query
          description: Filter by oracle provider
          schema:
            $ref: '#/components/schemas/OracleProvider'
        - name: symbol
          in: query
          description: Filter by asset symbol
          schema:
            type: string
        - name: category
          in: query
          description: Filter by asset category
          schema:
            type: string
            enum: [crypto, stablecoin, forex, commodity, wrapped, lst]
        - name: chain_id
          in: query
          description: Filter by chain ID (e.g. 1 for Ethereum)
          schema:
            type: integer
        - name: is_active
          in: query
          description: Filter by active status
          schema:
            type: boolean
            default: true
        - $ref: '#/components/parameters/limit'
        - $ref: '#/components/parameters/offset'
      responses:
        '200':
          description: Feed list
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FeedsListResponse'

  /feeds/freshness:
    get:
      operationId: getFeedsFreshness
      tags: [Feeds]
      summary: Feed freshness
      description: Check data freshness status (fresh/stale/outdated/never) for oracle feeds.
      security:
        - apiKey: []
      parameters:
        - name: provider
          in: query
          schema:
            $ref: '#/components/schemas/OracleProvider'
        - name: symbol
          in: query
          schema:
            type: string
        - name: category
          in: query
          schema:
            type: string
            enum: [crypto, stablecoin, forex, commodity, wrapped, lst]
      responses:
        '200':
          description: Feed freshness data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FeedsFreshnessResponse'

  /feeds/heartbeat-stats:
    get:
      operationId: getFeedsHeartbeatStats
      tags: [Feeds]
      summary: Feed heartbeat statistics
      description: Heartbeat statistics (success rate, coverage, daily snapshot count) for oracle feeds over a date range.
      security:
        - apiKey: []
      parameters:
        - name: provider
          in: query
          schema:
            $ref: '#/components/schemas/OracleProvider'
        - name: symbol
          in: query
          schema:
            type: string
        - $ref: '#/components/parameters/dateFrom'
        - $ref: '#/components/parameters/dateTo'
      responses:
        '200':
          description: Heartbeat stats
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HeartbeatStatsResponse'

  /feeds/{feedId}/health:
    get:
      operationId: getFeedHealth
      tags: [Feeds]
      summary: Feed health status
      description: Health status for a single oracle feed (healthy/degraded/critical).
      security:
        - apiKey: []
      parameters:
        - name: feedId
          in: path
          required: true
          description: Feed UUID
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Feed health
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FeedHealthResponse'
        '404':
          $ref: '#/components/responses/NotFound'

  # ── Reputation ──────────────────────────────────────────
  /reputation:
    get:
      operationId: getReputation
      tags: [Reputation]
      summary: All provider reputations
      description: Real-time reputation scores for every oracle provider, including accuracy, reliability, freshness, uptime, deviation, and latency.
      security:
        - apiKey: []
      responses:
        '200':
          description: Reputation data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReputationListResponse'

  /reputation/rankings:
    get:
      operationId: getReputationRankings
      tags: [Reputation]
      summary: Provider rankings
      description: Ranked leaderboard of oracle providers with score trends over a configurable period.
      security:
        - apiKey: []
      parameters:
        - name: days
          in: query
          description: Lookback period in days
          schema:
            type: integer
            minimum: 1
            maximum: 90
            default: 7
      responses:
        '200':
          description: Rankings
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RankingsResponse'

  /reputation/{provider}:
    get:
      operationId: getProviderReputation
      tags: [Reputation]
      summary: Single provider reputation
      description: Detailed reputation data for a specific oracle provider, with optional trend data.
      security:
        - apiKey: []
      parameters:
        - name: provider
          in: path
          required: true
          schema:
            $ref: '#/components/schemas/OracleProvider'
        - name: trend
          in: query
          description: Include daily trend data
          schema:
            type: boolean
        - name: days
          in: query
          description: Trend lookback period in days
          schema:
            type: integer
            minimum: 1
            maximum: 365
            default: 30
      responses:
        '200':
          description: Provider reputation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProviderReputationResponse'
        '404':
          $ref: '#/components/responses/NotFound'

  # ── Analytics 🔒 ───────────────────────────────────────
  /correlation:
    get:
      operationId: getCorrelation
      tags: [Analytics]
      summary: Provider correlation matrix 🔒
      description: |
        Pearson correlation matrix between oracle providers for a given symbol.
        Identifies highly correlated provider pairs that amplify systemic risk.

        **Credit-metered** — any API key with sufficient credit balance.
      security:
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/symbol'
        - $ref: '#/components/parameters/dateFrom'
        - $ref: '#/components/parameters/dateTo'
      responses:
        '200':
          description: Correlation data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CorrelationResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'

  /signals:
    get:
      operationId: getSignals
      tags: [Analytics]
      summary: Signal vectors 🔒
      description: |
        5-dimensional signal vectors (freshness, sourceReliability, metadataCompleteness,
        consistency, auditStatus) for each price observation, with failure mode classification.

        **Credit-metered** — any API key with sufficient credit balance.
      security:
        - apiKey: []
      parameters:
        - name: provider
          in: query
          schema:
            $ref: '#/components/schemas/OracleProvider'
        - name: symbol
          in: query
          schema:
            type: string
        - $ref: '#/components/parameters/dateFrom'
        - $ref: '#/components/parameters/dateTo'
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 1000
            default: 200
        - name: offset
          in: query
          schema:
            type: integer
            minimum: 0
            default: 0
      responses:
        '200':
          description: Signal vector data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SignalsResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'

  /deviation:
    get:
      operationId: getDeviation
      tags: [Analytics]
      summary: Deviation analysis
      description: |
        Aggregated deviation analysis across oracle providers for a symbol,
        with timeline data at configurable intervals (1h/6h/24h).

        Public tier: anonymous callers may request up to a 30-day window.
        Full-history timelines require an API key. No credits are charged on
        the public tier.
      security:
        - {}
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/symbol'
        - $ref: '#/components/parameters/dateFrom'
        - $ref: '#/components/parameters/dateTo'
        - name: interval
          in: query
          description: Aggregation interval
          schema:
            type: string
            enum: [1h, 6h, 24h]
            default: 24h
      responses:
        '200':
          description: Deviation data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeviationResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'

  /latency:
    get:
      operationId: getLatency
      tags: [Analytics]
      summary: Latency statistics
      description: Latency percentile statistics (p50/p90/p95/p99) for oracle providers over a date range.
      security:
        - apiKey: []
      parameters:
        - name: provider
          in: query
          schema:
            $ref: '#/components/schemas/OracleProvider'
        - name: symbol
          in: query
          schema:
            type: string
        - $ref: '#/components/parameters/dateFrom'
        - $ref: '#/components/parameters/dateTo'
      responses:
        '200':
          description: Latency data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/LatencyResponse'

  /anomalies:
    get:
      operationId: getAnomalies
      tags: [Analytics]
      summary: Anomaly summary 🔒
      description: |
        Aggregate oracle anomalies over the last N days across all daily reports.
        Returns severity/provider/asset breakdowns, top events, and risk impacts.

        **Credit-metered** — any API key with sufficient credit balance.
      security:
        - apiKey: []
      parameters:
        - name: days
          in: query
          description: Lookback period in days
          schema:
            type: integer
            minimum: 1
            maximum: 30
            default: 7
      responses:
        '200':
          description: Anomaly data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AnomaliesResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'

  /incidents:
    get:
      operationId: getIncidents
      tags: [Risk Signals]
      summary: Incident list
      description: |
        Feed failure incidents and deviation events with severity classification.

        Public tier: anonymous callers may query a window of up to 30 days,
        up to 50 results and offset 200. Full-depth queries (any window,
        pages up to 200, deep paging) require an API key. The response
        carries a machine-readable `evidence` block pointing at the signed
        incident corpus and the verifiable settlement/attestation surfaces;
        aggregates describe what was observed, not why it happened.
      security:
        - {}
        - apiKey: []
      parameters:
        - name: provider
          in: query
          schema:
            $ref: '#/components/schemas/OracleProvider'
        - name: minSeverity
          in: query
          description: Minimum severity filter
          schema:
            type: string
            enum: [low, medium, high, critical]
        - $ref: '#/components/parameters/dateFrom'
        - $ref: '#/components/parameters/dateTo'
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 50
        - name: offset
          in: query
          schema:
            type: integer
            minimum: 0
            default: 0
      responses:
        '200':
          description: Incident list
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/IncidentsResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '402':
          $ref: '#/components/responses/CreditExhausted'

  # ── Risk 🔒 ─────────────────────────────────────────────
  /risk/summary:
    get:
      operationId: getRiskSummary
      tags: [Risk]
      summary: Composite risk metrics
      description: |
        7-dimensional risk assessment: HHI concentration, diversification, volatility,
        correlation risk, freshness risk, manipulation resistance, and shared-dependency risk.

        Public tier: anonymous callers may request period <= 168h and up to 4
        providers. Deeper reads (period up to 8760h, up to 10 providers)
        require an API key. The response includes a machine-readable
        `nextActions` block pointing at the signed pre-trade verdict and the
        attestation schema; a risk summary is context, not authorization.
      security:
        - {}
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/symbol'
        - name: providers
          in: query
          required: true
          description: Comma-separated list of 2–10 oracle providers
          schema:
            type: string
            example: chainlink,redstone,api3
        - name: period
          in: query
          description: Hours of historical data to analyze
          schema:
            type: integer
            minimum: 1
            maximum: 8760
            default: 168
      responses:
        '200':
          description: Risk summary
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RiskSummaryResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/InsufficientData'

  /cross-chain/spreads:
    get:
      operationId: getCrossChainSpreads
      tags: [Risk]
      summary: Cross-chain price spreads 🔒
      description: |
        Cross-chain price spread matrix for a given oracle provider and symbol.
        Identifies pricing discrepancies across blockchains.

        **Credit-metered** — protocol-level intelligence, open to any paying key.
      security:
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/provider'
        - $ref: '#/components/parameters/symbol'
        - name: baseChain
          in: query
          description: Blockchain to use as price reference
          schema:
            $ref: '#/components/schemas/Blockchain'
      responses:
        '200':
          description: Cross-chain spreads
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CrossChainSpreadResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'
        '422':
          $ref: '#/components/responses/InsufficientData'

  # ── Protocols 🔒 ────────────────────────────────────────
  /protocols:
    get:
      operationId: listProtocols
      tags: [Protocols]
      summary: List lending protocols
      description: List all integrated lending protocols with dynamic risk data.
      security:
        - apiKey: []
      responses:
        '200':
          description: Protocol list
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProtocolsListResponse'

  /protocols/risk-params:
    get:
      operationId: getAllProtocolRiskParams
      tags: [Protocols]
      summary: Bulk protocol risk parameters 🔒
      description: |
        Risk parameters (liquidation thresholds, LTVs, collateral factors) for all integrated lending protocols.

        **Credit-metered** — any API key with sufficient credit balance.
      security:
        - apiKey: []
      responses:
        '200':
          description: All protocol risk parameters
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BulkRiskParamsResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'

  /protocols/{id}/risk-params:
    get:
      operationId: getProtocolRiskParams
      tags: [Protocols]
      summary: Protocol risk parameters 🔒
      description: |
        Risk parameters for a single lending protocol (e.g. aave-v3-ethereum).
        Data sourced from on-chain parameters cached in the database.

        **Credit-metered** — any API key with sufficient credit balance.
      security:
        - apiKey: []
      parameters:
        - name: id
          in: path
          required: true
          description: Protocol ID (e.g. aave-v3-ethereum, compound-v3-ethereum)
          schema:
            type: string
      responses:
        '200':
          description: Protocol risk parameters
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProtocolRiskParamsResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'
        '404':
          $ref: '#/components/responses/NotFound'

  /protocols/{id}/oracle-exposure:
    get:
      operationId: getProtocolOracleExposure
      tags: [Protocols]
      summary: Protocol oracle exposure
      description: |
        Oracle provider concentration and single-point-of-failure analysis for a lending protocol.

        **Credit-metered** — protocol-level intelligence, open to any paying key.
      security:
        - apiKey: []
      parameters:
        - name: id
          in: path
          required: true
          description: Protocol ID
          schema:
            type: string
      responses:
        '200':
          description: Oracle exposure analysis
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OracleExposureResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'
        '404':
          $ref: '#/components/responses/NotFound'

  # ── Safety 🔒 ───────────────────────────────────────────
  /safety/liquidation:
    get:
      operationId: getLiquidationStressTest
      tags: [Safety]
      summary: Liquidation stress test 🔒
      description: |
        Daily stress-test results for benchmark positions across integrated lending protocols.
        Includes 1%, 3%, 5% deviation scenarios and joint-deviation analysis.

        **Credit-metered** — any API key with sufficient credit balance.
      security:
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/date'
      responses:
        '200':
          description: Liquidation stress test
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/LiquidationResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'
        '404':
          $ref: '#/components/responses/NotFound'

  /safety/oracle-watch-window:
    post:
      operationId: purchaseOracleWatchWindow
      tags: [Safety]
      summary: Purchase a 24h Oracle Watch monitored window
      description: >-
        Pre-pays continuous Oracle Watch coverage for one (symbol, chain)
        subject for 24 hours — the first non-per-call product. The purchase
        returns a one-time window token (shown exactly once; only its SHA-256
        hash is stored) used to poll and close the window. In-window signal
        polls are token-authenticated and never charged per call, bounded by
        the plan's poll cap (300 per window) and minimum poll interval (30s).
        Per API key, at most 5 windows may be open at once and polls are capped
        at 10 per rolling minute; exceeding either returns 429 (concurrency
        refusals carry no Retry-After — close a window; poll-rate refusals carry
        Retry-After until the minute resets). Keyless x402 buyers are bounded
        per window instead. Assessment and evidence
        only — no custody, no execution authority. API-key access (charged as
        one product-priced credit debit) or x402 payment is accepted.
      security:
        - apiKey: []
        - {}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [symbol]
              properties:
                symbol: { type: string, description: Asset to monitor, example: ETH }
                chain:
                  {
                    type: string,
                    description: Optional chain scope fixed for the window,
                    example: arbitrum,
                  }
      responses:
        '200':
          { description: Window opened, with the one-time window token and poll/close usage hints. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }
        '429':
          description: >-
            This API key already holds 5 open monitored windows. No Retry-After
            header: a slot frees only when a window is closed or its 24h term
            expires. The body carries scope, limit, current and a hint.

  /safety/oracle-watch-window/{windowId}:
    get:
      operationId: pollOracleWatchWindow
      tags: [Safety]
      summary: Poll the current halt/proceed signal inside an open window
      description: >-
        Free in-window poll of the current Oracle Watch signal for the
        monitored subject, authenticated by the one-time window token returned
        at purchase (`Authorization: Bearer oww_<hex>`). Each poll is counted
        against the window's poll budget and recorded as an auditable judgment.
        Unknown window ids and wrong tokens are indistinguishable (401).
      security: [{}]
      parameters:
        - in: path
          name: windowId
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200': { description: Current signal with window usage (polls used, poll cap). }
        '401': { description: Invalid or missing window token. }
        '404': { description: Monitored window not found. }
        '410': { description: Window closed or expired. }
        '429':
          description: >-
            Poll cap exhausted, polling before the minimum interval, or the
            per-key limit of 10 polls per rolling minute. Only the rolling-minute
            refusal carries Retry-After (seconds until the counter resets).
    post:
      operationId: closeOracleWatchWindow
      tags: [Safety]
      summary: Close the window early and return its coverage summary
      description: >-
        Idempotent close. Returns the summary rebuilt from the per-issuance
        audit rows: verdict/recommendation counts, halt count, and first/last
        halt timestamps. Works on an expired window — the summary is the record
        of what the window covered. Authenticated by the one-time window token.
      security: [{}]
      parameters:
        - in: path
          name: windowId
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200': { description: Window summary (polls issued, verdict counts, halt timeline). }
        '401': { description: Invalid or missing window token. }
        '404': { description: Monitored window not found. }

  /safety/position-lifecycle:
    post:
      operationId: purchasePositionLifecycle
      tags: [Safety]
      summary: Purchase a 24h Position Lifecycle Bundle
      description: >-
        Pre-pays 24h of lifecycle coverage for one (symbol, chain) position
        subject — the second non-per-call product, and the first bundle. One
        purchase includes an embedded Oracle Watch monitored window (300 free
        signal polls via the existing window routes with the same bearer
        token), 4 bundled guard assessments across any position-guard family,
        and 1 attested execution receipt. The purchase returns a one-time
        lifecycle token (shown exactly once; only its SHA-256 hash is stored).
        Per API key, at most 3 lifecycles and 5 monitored windows may be open
        at once (the embedded window counts toward the window cap); polls on the
        embedded window are capped at 10 per rolling minute. Exceeding a cap
        returns 429; the response body names the scope, limit and current count,
        and concurrency refusals carry no Retry-After (close one to free a slot).
        Assessment and evidence only — no custody, no execution authority.
        API-key access (charged as one product-priced credit debit) or x402
        payment is accepted.
      security:
        - apiKey: []
        - {}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [symbol]
              properties:
                symbol: { type: string, description: Position subject to cover, example: ETH }
                chain:
                  {
                    type: string,
                    description: Optional chain scope fixed for the lifecycle,
                    example: arbitrum,
                  }
      responses:
        '200': {
            description: Lifecycle opened,
            with the one-time lifecycle token,
            embedded
            windowId,
            and usage hints for watch/guard/receipt/close.,
          }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }
        '429':
          description: >-
            This API key already holds 3 open lifecycles (or 5 open windows).
            No Retry-After header: close one to free a slot. The body carries
            scope, limit, current and a hint.

  /safety/position-lifecycle/{lifecycleId}:
    post:
      operationId: closePositionLifecycle
      tags: [Safety]
      summary: Close the lifecycle early and return its combined summary
      description: >-
        Idempotent close. Returns the lifecycle's guard and receipt usage plus
        the embedded monitored window's coverage summary (verdict and
        recommendation counts, halt timeline). Works on an expired lifecycle —
        the summary is the record of what the lifecycle covered. Authenticated
        by the one-time lifecycle token (`Authorization: Bearer plc_<hex>`).
        Unknown lifecycle ids and wrong tokens are indistinguishable (401).
      security: [{}]
      parameters:
        - in: path
          name: lifecycleId
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          { description: Combined lifecycle summary (guard usage, receipt state, watch coverage). }
        '401': { description: Invalid or missing lifecycle token. }
        '404': { description: Position lifecycle not found. }

  /safety/position-lifecycle/{lifecycleId}/guard:
    post:
      operationId: runBundledPositionGuard
      tags: [Safety]
      summary: Run one bundled guard assessment inside an open lifecycle
      description: >-
        One bundled guard assessment, free within the lifecycle's guard budget
        (4 across the 24h window). The family is chosen per call
        (base_perp, hyperliquid_perp, base_lending, monad_lending,
        multichain_evm_lending, solana_lending) and params are validated against
        that family's native route schema. A BLOCK verdict is a complete
        assessment and consumes a budget slot; a schema or assessor technical
        failure does not. solana_lending additionally requires the exact
        unsigned Solana transaction as `transaction`. Assessment only — exact
        call binding stays on the native guard routes.
      security: [{}]
      parameters:
        - in: path
          name: lifecycleId
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [family, params]
              properties:
                family: { type: string, description: Guard family to assess with }
                params: { type: object, description: Native guard input for the chosen family }
                transaction:
                  {
                    type: object,
                    description: Required for solana_lending — the exact unsigned transaction,
                  }
      responses:
        '200': { description: Native guard result with guard budget usage. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { description: Invalid or missing lifecycle token. }
        '404': { description: Position lifecycle not found. }
        '410': { description: Lifecycle closed or expired. }
        '429': { description: Guard budget exhausted. }

  /safety/position-lifecycle/{lifecycleId}/receipt:
    post:
      operationId: issueBundledExecutionReceipt
      tags: [Safety]
      summary: Issue the bundled attested execution receipt (one per lifecycle)
      description: >-
        Issues one attested Execution Receipt, free within the lifecycle's
        single receipt credit. The body is identical to the native
        /api/v1/execution/attestation/issue body — the receipt binds to the
        caller's own pre-trade attestations exactly as it does à la carte; the
        bundle only changes who pays. The credit is consumed only by a
        successfully recorded issuance; failed attempts restore it.
      security: [{}]
      parameters:
        - in: path
          name: lifecycleId
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ExecutionIssueRequest'
      responses:
        '200': { description: Signed receipt with the lifecycle receipt state (consumed). }
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { description: Invalid or missing lifecycle token. }
        '404': { description: Position lifecycle not found. }
        '409': { description: The bundled receipt was already issued. }
        '410': { description: Lifecycle closed or expired. }
        '502': { description: On-chain execution fact collection failed. }
        '503': { description: Receipt signing unavailable. }

  /safety/position:
    post:
      operationId: calculatePositionSafety
      tags: [Safety]
      summary: Position safety calculation 🔒
      description: |
        Analyze liquidation risk for a custom lending position. Returns critical deviation
        percentages, safety buffer, 1%/3%/5% scenarios, and oracle warnings.

        **Credit-metered** — any API key with sufficient credit balance.
      security:
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PositionSafetyRequest'
      responses:
        '200':
          description: Position safety analysis
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PositionSafetyResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'

  /safety/pre-trade:
    get:
      operationId: preTradeSafetyCheck
      tags: [Safety]
      summary: Pre-trade oracle safety check 🔒
      description: |
        Pre-trade oracle safety checkpoint for AI agents. Call this BEFORE executing any on-chain
        swap/borrow/lend/liquidation/repay to verify oracle data integrity. Aggregates cross-oracle
        consensus prices, per-provider deviation, data freshness, stablecoin peg status, and
        reputation into a single verdict: `PASS` / `CAUTION` / `DANGER` / `BLOCK`. Agents MUST NOT
        execute trades when the verdict is `DANGER` or `BLOCK`. Also returns a recommended maximum
        position size. Every call is audit-logged to build a data flywheel for a future ML model.

        **Ways to pay:** use an API key with sufficient credits, or pay $0.02 USDC per successful
        check through x402. When the deployment has `MPP_ENABLED=true`, the same REST endpoint also
        accepts MPP `evm` `charge` at the same price, network, recipient, and facilitator. Failed
        checks are not settled. The MPP MCP pilot is available at `/api/mcp/mpp` only when
        `MPP_MCP_ENABLED=true`; it accepts `pre_trade_safety_check` and settles only after success.
        The live `/openapi.json` discovery document publishes canonical `x-payment-info.offers`
        using the deployment's actual USDC contract and atomic-unit amount. x402 details remain in
        the separate `x-x402-payment-info` extension.
      security:
        - apiKey: []
        - {}
      parameters:
        - name: asset
          in: query
          required: true
          description: Asset symbol, e.g. ETH, BTC, USDC.
          schema:
            type: string
            example: ETH
        - name: chainId
          in: query
          required: true
          description: Chain ID (e.g. 1=Ethereum, 0=chain-agnostic).
          schema:
            type: integer
            example: 1
        - name: action
          in: query
          required: true
          description: Type of DeFi operation.
          schema:
            type: string
            enum: [swap, borrow, lend, liquidate, repay]
            example: swap
        - name: tradeAmountUsd
          in: query
          required: true
          description: Trade size in USD.
          schema:
            type: number
            format: float
            exclusiveMinimum: 0
            example: 100000
        - name: targetProviders
          in: query
          required: false
          description: Comma-separated list of oracle providers to restrict the check to.
          schema:
            type: string
            example: chainlink,redstone,api3
        - name: tokenAddress
          in: query
          required: false
          description: |
            Optional token contract address whose third-party security scan (GoPlus token_security)
            is captured and signed as decision-input evidence. When set, the response carries a
            signed `contextAttestation` (Insight's capture statement, verifiable offline with a
            separately trusted key registry) and an advisory `tokenSecurity` view linked by both
            the source-response SHA-256 and a signed normalized-view SHA-256. This does not prove
            the source was correct, that an agent consumed the view, or that the decision was compliant.
            The response does not include the raw source body. When omitted, a built-in symbol map
            (Ethereum mainnet ETH/USDC/WBTC) is used. Advisory evidence only — these fields NEVER
            affect the verdict, are never part of the signed oracle attestation, and are omitted
            entirely (absent, not null) when the scan or signing fails (absence means "no evidence",
            not "safe").
          schema:
            type: string
            pattern: '^0x[0-9a-fA-F]{40}$'
            example: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'
        - name: decisionInputCheck
          in: query
          required: false
          description: Set to `1` to request the separate signed decision-input sufficiency assessment. It does not change the oracle safety verdict or authorize execution.
          schema: { type: string, enum: ['0', '1'] }
        - name: decisionPriceUsd
          in: query
          required: false
          description: Required with decisionInputCheck=1. Intended USD price for the operation.
          schema: { type: number, exclusiveMinimum: 0 }
        - name: quotePriceUsd
          in: query
          required: false
          description: Required with decisionInputCheck=1. Price returned by the actual venue quote.
          schema: { type: number, exclusiveMinimum: 0 }
        - name: quoteObservedAt
          in: query
          required: false
          description: Required with decisionInputCheck=1. Offset-qualified ISO-8601 venue quote timestamp.
          schema: { type: string, format: date-time }
        - name: maxReferenceDeviationBps
          in: query
          required: false
          description: Required with decisionInputCheck=1. Maximum decision-price deviation from each reference, in basis points.
          schema: { type: integer, minimum: 0, maximum: 10000 }
        - name: maxSlippageBps
          in: query
          required: false
          description: Required with decisionInputCheck=1. Maximum decision-price-to-venue-quote deviation, in basis points.
          schema: { type: integer, minimum: 0, maximum: 10000 }
        - name: maxQuoteAgeSeconds
          in: query
          required: false
          description: Required with decisionInputCheck=1. Maximum accepted age of the venue quote, 1 to 300 seconds.
          schema: { type: integer, minimum: 1, maximum: 300 }
        - name: quoteProvenance
          in: query
          required: false
          description: URL-encoded JSON hash-only quote-provenance envelope. Raw vendor request and response bytes stay with the caller. It binds source id, rights scope, asset, chain, price, timestamp, and request/response hashes.
          schema: { type: string, minLength: 2, maxLength: 4096 }
        - name: requireQuoteProvenance
          in: query
          required: false
          description: With decisionInputCheck=1, set to `1` to fail closed unless a permitted quoteProvenance envelope binds the submitted quote. A missing or prohibited envelope returns INSUFFICIENT_EVIDENCE.
          schema: { type: string, enum: ['0', '1'] }
        - name: reviewedUniswapV3AmountIn
          in: query
          required: false
          description: Exact source-token amount for the reviewed concentrated-liquidity pre-trade lane. Requires all reviewedUniswapV3 parameters, decisionInputCheck=1, and destinationAsset. Admitted routes are Monad MON/WMON→USDC, Base ETH/WETH→USDC, and Base PancakeSwap V3 USDC→USDT only.
          schema: { type: string, pattern: '^(?:0\.(?:0*[1-9][0-9]*)|[1-9][0-9]*(?:\.[0-9]+)?)$' }
        - name: reviewedUniswapV3MaxQuoteDeviationBps
          in: query
          required: false
          description: Maximum divergence between the pinned reviewed-pool quote and the submitted venue quote, in basis points.
          schema: { type: integer, minimum: 0, maximum: 10000 }
        - name: reviewedUniswapV3MaxTwapDeviationBps
          in: query
          required: false
          description: Maximum spot-to-TWAP divergence for the reviewed pool, in basis points.
          schema: { type: integer, minimum: 0, maximum: 10000 }
        - name: reviewedAerodromeSlipstreamAmountIn
          in: query
          required: false
          description: Exact WETH input for the reviewed Base Aerodrome Slipstream WETH/USDC CL100 lane. Requires all reviewedAerodromeSlipstream parameters, decisionInputCheck=1, and destinationAsset=USDC. It cannot be combined with the reviewedUniswapV3 lane.
          schema: { type: string, pattern: '^(?:0\.(?:0*[1-9][0-9]*)|[1-9][0-9]*(?:\.[0-9]+)?)$' }
        - name: reviewedAerodromeSlipstreamMaxQuoteDeviationBps
          in: query
          required: false
          description: Maximum divergence between the pinned reviewed Aerodrome pool quote and the submitted venue quote, in basis points.
          schema: { type: integer, minimum: 0, maximum: 10000 }
        - name: reviewedAerodromeSlipstreamMaxTwapDeviationBps
          in: query
          required: false
          description: Maximum spot-to-TWAP divergence for the reviewed Aerodrome pool, in basis points.
          schema: { type: integer, minimum: 0, maximum: 10000 }
      responses:
        '200':
          description: Pre-trade safety verdict, paid through x402 or MPP or authorized by API key.
          headers:
            PAYMENT-RESPONSE:
              description: x402 settlement receipt when x402 was used.
              schema: { type: string }
            Payment-Receipt:
              description: MPP settlement receipt when MPP was used.
              schema: { type: string }
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PreTradeSafetyResponse'
        '402':
          description: >-
            HTTP 402 carries an x402 quote in PAYMENT-REQUIRED and, when MPP_ENABLED is active,
            an MPP evm charge challenge in WWW-Authenticate. API-key calls can also return 402
            when the credit balance is insufficient.
          headers:
            PAYMENT-REQUIRED:
              description: x402 v2 quote, base64 encoded.
              schema: { type: string }
            WWW-Authenticate:
              description: MPP challenge when enabled on this deployment.
              schema: { type: string }

  /safety/base-agent-swap-guard/verify:
    get:
      operationId: getBaseAgentSwapGuardVerificationSchema
      tags: [Safety]
      summary: Get Base Agent Swap Guard attestation schema
      security: []
      responses:
        '200': { description: Attester status and supported EIP-712 schema. }
    post:
      operationId: verifyBaseAgentSwapGuardDecision
      tags: [Safety]
      summary: Verify a Base Agent Swap Guard decision
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result and expiry state. }

  /safety/base-agent-swap-guard/settlement:
    post:
      operationId: settleBaseAgentSwapGuard
      tags: [Safety]
      summary: Post-settlement closure for a Base Agent Swap Guard decision
      description: >-
        Pair a signed Base Agent Swap Guard decision with the swap transaction
        that settled it. Insight verifies the decision, requires the on-chain
        to/value/calldata to match the guarded approval and swap calls
        byte-for-byte, reconciles the observed ERC-20 input and output amounts
        against the guarded quote (amountInRaw, quotedAmountOutRaw,
        amountOutMinimumRaw, realized output-leg slippage vs the agent policy),
        and returns a signed BaseAgentSwapGuardSettlement bound to the
        decisionHash with explicit reason codes. A decision that does not
        verify, or a transaction whose bytes differ from the guarded calls, is
        rejected — never closed over. With verifyOnly=1 and a settlement
        object, only the settlement's own EIP-712 signature and integrity are
        checked.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision, swapTxHash]
              properties:
                decision:
                  type: object
                  additionalProperties: true
                  description: The signed Base Agent Swap Guard decision the agent executed under.
                swapTxHash:
                  type: string
                  pattern: '^0x[0-9a-fA-F]{64}$'
                  description: Hash of the executed swap transaction.
                approvalTxHash:
                  type: string
                  pattern: '^0x[0-9a-fA-F]{64}$'
                  description: Optional hash of the executed approval transaction. When presented it must match the guarded approval call exactly; when absent the settlement carries APPROVAL_TX_NOT_PRESENTED.
                verifyOnly:
                  type: boolean
                  description: Set to true to only verify a previously issued settlement signature; requires the settlement property.
                settlement:
                  type: object
                  additionalProperties: true
                  description: The signed settlement to verify in verifyOnly mode.
      responses:
        '200':
          description: Signed settlement closure (or, in verifyOnly mode, the signature verification result).
        '400':
          description: Rejected — the decision did not verify, the chain is unsupported, or the executed bytes differ from the guarded calls (ON_CHAIN_CALL_MISMATCH).
        '404':
          description: The presented swap or approval transaction was not found on the configured RPC.
        '502':
          description: RPC or collection failure while reading settlement evidence.

  /safety/base-lending-guard:
    get:
      operationId: assessBaseLendingGuard
      tags: [Safety]
      summary: Base lending risk decision
      description: >-
        Read-only risk gate for a caller-declared post-action lending position on
        Base. It checks live reviewed protocol controls and oracle safety evidence;
        it never signs, submits, or authorizes a transaction. API-key access or
        x402 payment is accepted. Morpho Blue requires a marketId.
      security:
        - apiKey: []
        - {}
      parameters:
        - {
            name: protocolId,
            in: query,
            required: true,
            schema:
              {
                type: string,
                enum: [aave-v3-base, morpho-blue-base, compound-v3-base, moonwell-base],
              },
          }
        - {
            name: action,
            in: query,
            required: true,
            schema: { type: string, enum: [supply, borrow] },
          }
        - {
            name: collateralSymbol,
            in: query,
            required: true,
            schema: { type: string, example: ETH },
          }
        - { name: loanSymbol, in: query, required: true, schema: { type: string, example: USDC } }
        - {
            name: collateralValueUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 10000 },
          }
        - {
            name: debtValueUsd,
            in: query,
            required: true,
            schema: { type: number, minimum: 0, example: 5000 },
          }
        - {
            name: marketId,
            in: query,
            required: false,
            description: Required 32-byte Morpho Blue market ID.,
            schema: { type: string, pattern: '^0x[0-9a-fA-F]{64}$' },
          }
      responses:
        '200': { description: Complete ALLOW, CAUTION, or BLOCK lending decision. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }
    post:
      operationId: createBaseLendingGuardExactDecision
      tags: [Safety]
      summary: Bind a Base lending decision to one exact direct call
      description: >-
        Creates a portable EIP-712 decision for a read-only assessment and one
        unsigned direct Base lending call. The decision remains non-authorizing
        and must be bound to user authorization before execution.
      security:
        - apiKey: []
        - {}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [guard, transaction]
              properties:
                guard: { type: object, description: The same lending fields accepted by GET. }
                transaction:
                  {
                    type: object,
                    description: Exact unsigned direct call,
                    sender,
                    nonce,
                    and zero value.,
                  }
      responses:
        '200':
          {
            description: Complete decision,
            optionally carrying an attestation when an eligible attester is configured.,
          }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }

  /safety/base-lending-guard/verify:
    get:
      operationId: getBaseLendingGuardVerificationSchema
      tags: [Safety]
      summary: Get Base lending guard attestation schema
      security: []
      responses:
        '200': { description: Attester status and supported EIP-712 schema. }
    post:
      operationId: verifyBaseLendingGuardDecision
      tags: [Safety]
      summary: Verify a Base lending guard decision
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result and expiry state. }

  /safety/base-perp-guard:
    get:
      operationId: assessBasePerpGuard
      tags: [Safety]
      summary: Base perp risk decision
      description: >-
        Read-only risk gate for a caller-declared Synthetix Perps V3 Base
        position. It separately evaluates the underlying and USDC margin oracle
        integrity and checks the declared post-action leverage against reviewed
        market caps; it never signs, submits, or authorizes an order. API-key
        access or x402 payment is accepted.
      security:
        - apiKey: []
        - {}
      parameters:
        - {
            name: protocolId,
            in: query,
            required: true,
            schema: { type: string, enum: [synthetix-perps-v3-base] },
          }
        - {
            name: action,
            in: query,
            required: true,
            schema: { type: string, enum: [open_long, open_short] },
          }
        - { name: assetSymbol, in: query, required: true, schema: { type: string, example: ETH } }
        - {
            name: marginAssetSymbol,
            in: query,
            required: true,
            schema: { type: string, enum: [USDC] },
          }
        - {
            name: sizeUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 5000 },
          }
        - {
            name: marginValueUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 2500 },
          }
      responses:
        '200': { description: Complete ALLOW, CAUTION, or BLOCK perp decision. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }
    post:
      operationId: createBasePerpGuardExactDecision
      tags: [Safety]
      summary: Bind a Base perp decision to one exact PerpsMarketProxy commitOrder
      description: >-
        Creates a portable EIP-712 decision that commits to the full
        PerpsMarketProxy commitOrder calldata, sender, nonce, and zero
        transaction value. The decision remains non-authorizing and must be
        bound to user authorization before execution.
      security:
        - apiKey: []
        - {}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [guard, transaction]
              properties:
                guard: { type: object, description: The same perp fields accepted by GET. }
                transaction:
                  {
                    type: object,
                    description: Exact unsigned PerpsMarketProxy commitOrder call with zero value.,
                  }
      responses:
        '200':
          {
            description: Complete decision,
            optionally carrying an attestation when an eligible attester is configured.,
          }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }

  /safety/base-perp-guard/verify:
    get:
      operationId: getBasePerpGuardVerificationSchema
      tags: [Safety]
      summary: Get Base Perp Guard attestation schema
      security: []
      responses:
        '200': { description: Attester status and supported EIP-712 schema. }
    post:
      operationId: verifyBasePerpGuardDecision
      tags: [Safety]
      summary: Verify a Base Perp Guard decision
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result and expiry state. }

  /safety/monad-perp-guard:
    get:
      operationId: assessMonadPerpGuard
      tags: [Safety]
      summary: Monad perp risk decision (Perpl)
      description: >-
        Read-only risk gate for a caller-declared Perpl AUSD-margined position
        on Monad mainnet. It evaluates the underlying cross-oracle consensus
        integrity on canonical mainnet feeds, binds the declared leverage to
        the reviewed profile capped by the live venue initial-margin
        requirement, and escalates on observed Perpl mark/oracle or consensus
        divergence; the AUSD margin peg is disclosed as not independently
        verified. It never signs, submits, or authorizes an order. API-key
        access or x402 payment is accepted.
      security:
        - apiKey: []
        - {}
      parameters:
        - {
            name: protocolId,
            in: query,
            required: true,
            schema: { type: string, enum: [perpl-perps-monad-mainnet] },
          }
        - {
            name: action,
            in: query,
            required: true,
            schema: { type: string, enum: [open_long, open_short] },
          }
        - { name: assetSymbol, in: query, required: true, schema: { type: string, example: BTC } }
        - {
            name: marginAssetSymbol,
            in: query,
            required: true,
            schema: { type: string, enum: [AUSD] },
          }
        - {
            name: sizeUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 20000 },
          }
        - {
            name: marginValueUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 4000 },
          }
      responses:
        '200': { description: Complete ALLOW, CAUTION, or BLOCK perp decision. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }
  /safety/bnb-perp-guard:
    get:
      operationId: assessBnbPerpGuard
      tags: [Safety]
      summary: BNB perp risk decision (Aster Perps)
      description: >-
        Read-only risk gate for a caller-declared Aster Perps USDT-margined
        position on BNB Smart Chain. It separately evaluates the underlying
        and USDT margin oracle integrity, binds the declared leverage to the
        reviewed profile capped by the live venue margin requirement, and
        escalates on observed Aster mark/index or consensus divergence; it
        never signs, submits, or authorizes an order. API-key access or x402
        payment is accepted.
      security:
        - apiKey: []
        - {}
      parameters:
        - {
            name: protocolId,
            in: query,
            required: true,
            schema: { type: string, enum: [aster-perps-bnb-mainnet] },
          }
        - {
            name: action,
            in: query,
            required: true,
            schema: { type: string, enum: [open_long, open_short] },
          }
        - { name: assetSymbol, in: query, required: true, schema: { type: string, example: BTC } }
        - {
            name: marginAssetSymbol,
            in: query,
            required: true,
            schema: { type: string, enum: [USDT] },
          }
        - {
            name: sizeUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 20000 },
          }
        - {
            name: marginValueUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 2000 },
          }
      responses:
        '200': { description: Complete ALLOW, CAUTION, or BLOCK perp decision. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }
  /safety/bnb-perp-guard/verify:
    get:
      operationId: getBnbPerpGuardVerificationSchema
      tags: [Safety]
      summary: Get BNB Perp Guard attestation schema
      security: []
      responses:
        '200': { description: Attester status and supported EIP-712 schema. }
    post:
      operationId: verifyBnbPerpGuardDecision
      tags: [Safety]
      summary: Verify a BNB (Aster) Perp Guard decision
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result and expiry state. }

  /safety/hyperliquid-perp-guard:
    get:
      operationId: assessHyperliquidPerpGuard
      tags: [Safety]
      summary: Hyperliquid perp risk decision
      description: >-
        Read-only risk gate for a caller-declared Hyperliquid perpetual position.
        It separately evaluates underlying and USDC cross-oracle consensus
        integrity on canonical mainnet feeds, checks the declared post-action
        leverage against a reviewed static profile capped by the freshly
        observed venue leverage limit, and attaches disclosed venue evidence
        (mark/oracle divergence, cross-venue consensus deviation) that can
        escalate the verdict; it never signs, submits, or authorizes an order.
        API-key access or x402 payment is accepted.
      security:
        - apiKey: []
        - {}
      parameters:
        - {
            name: protocolId,
            in: query,
            required: true,
            schema: { type: string, enum: [hyperliquid-perps-mainnet] },
          }
        - {
            name: action,
            in: query,
            required: true,
            schema: { type: string, enum: [open_long, open_short] },
          }
        - { name: assetSymbol, in: query, required: true, schema: { type: string, example: BTC } }
        - {
            name: marginAssetSymbol,
            in: query,
            required: true,
            schema: { type: string, enum: [USDC] },
          }
        - {
            name: sizeUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 25000 },
          }
        - {
            name: marginValueUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 2500 },
          }
      responses:
        '200': { description: Complete ALLOW, CAUTION, or BLOCK perp decision. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }
    post:
      operationId: createHyperliquidPerpGuardExactDecision
      tags: [Safety]
      summary: Bind a Hyperliquid perp decision to one exact unsigned order envelope
      description: >-
        Creates a portable EIP-712 decision that commits to the exact unsigned
        Hyperliquid IOC order envelope, including its intent hash, asset index,
        size, price, and expiry. The decision remains non-authorizing and must
        be bound to user authorization before the envelope is signed in the
        user wallet process.
      security:
        - apiKey: []
        - {}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [guard, order]
              properties:
                guard: { type: object, description: The same perp fields accepted by GET. }
                order:
                  {
                    type: object,
                    description: Exact unsigned Hyperliquid exchange envelope from the reviewed IOC preflight.,
                  }
      responses:
        '200':
          {
            description: Complete decision,
            optionally carrying an attestation when an eligible attester is configured.,
          }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }

  /safety/hyperliquid-perp-guard/verify:
    get:
      operationId: getHyperliquidPerpGuardVerificationSchema
      tags: [Safety]
      summary: Get Hyperliquid Perp Guard attestation schema
      security: []
      responses:
        '200': { description: Attester status and supported EIP-712 schema. }
    post:
      operationId: verifyHyperliquidPerpGuardDecision
      tags: [Safety]
      summary: Verify a Hyperliquid Perp Guard decision
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result and expiry state. }

  /safety/solana-perp-guard:
    get:
      operationId: assessSolanaPerpGuard
      tags: [Safety]
      summary: Solana perp risk decision (Drift v2 on-chain evidence)
      description: >-
        Read-only risk gate for a caller-declared Drift Protocol v2 perpetual
        position on Solana mainnet (reviewed SOL, BTC, and ETH markets, USDC
        margin). It separately evaluates underlying and USDC cross-oracle
        consensus integrity on canonical mainnet feeds, checks the declared
        post-action leverage against a reviewed static profile capped by the
        live Drift margin ratio, and attaches disclosed on-chain venue evidence
        (Drift mark price vs Pyth Lazer oracle deviation, funding rate, open
        interest, market status) that can escalate the verdict; it never signs,
        submits, or authorizes an order. API-key access or x402 payment is
        accepted.
      security:
        - apiKey: []
        - {}
      parameters:
        - {
            name: protocolId,
            in: query,
            required: true,
            schema: { type: string, enum: [drift-v2-mainnet] },
          }
        - {
            name: action,
            in: query,
            required: true,
            schema: { type: string, enum: [open_long, open_short] },
          }
        - { name: assetSymbol, in: query, required: true, schema: { type: string, example: SOL } }
        - {
            name: marginAssetSymbol,
            in: query,
            required: true,
            schema: { type: string, enum: [USDC] },
          }
        - {
            name: sizeUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 5000 },
          }
        - {
            name: marginValueUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 500 },
          }
      responses:
        '200': { description: Complete ALLOW, CAUTION, or BLOCK perp decision. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }

  /safety/solana-perp-guard/verify:
    get:
      operationId: getSolanaPerpGuardVerificationSchema
      tags: [Safety]
      summary: Get Solana perp guard Ed25519 attester information
      security: []
      responses:
        '200': { description: Attester public key and schema status. }
    post:
      operationId: verifySolanaPerpGuardDecision
      tags: [Safety]
      summary: Verify a Solana perp guard decision
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result and expiry state. }

  /safety/monad-lending-guard:
    get:
      operationId: assessMonadLendingGuard
      tags: [Safety]
      summary: Monad lending risk decision
      description: >-
        Read-only risk gate for a caller-declared post-action lending position on
        Monad (chain ID 143). It checks live Aave V3 or Morpho Blue controls and
        oracle safety evidence; it never signs, submits, or authorizes a transaction.
        API-key access or x402 payment is accepted. Morpho Blue requires a marketId.
      security:
        - apiKey: []
        - {}
      parameters:
        - {
            name: protocolId,
            in: query,
            required: true,
            schema: { type: string, enum: [aave-v3-monad, morpho-blue-monad] },
          }
        - {
            name: action,
            in: query,
            required: true,
            schema: { type: string, enum: [supply, borrow] },
          }
        - {
            name: collateralSymbol,
            in: query,
            required: true,
            schema: { type: string, example: WETH },
          }
        - { name: loanSymbol, in: query, required: true, schema: { type: string, example: USDC } }
        - {
            name: collateralValueUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 10000 },
          }
        - {
            name: debtValueUsd,
            in: query,
            required: true,
            schema: { type: number, minimum: 0, example: 5000 },
          }
        - {
            name: marketId,
            in: query,
            required: false,
            description: Required 32-byte Morpho Blue market ID.,
            schema: { type: string, pattern: '^0x[0-9a-fA-F]{64}$' },
          }
      responses:
        '200': { description: Complete ALLOW, CAUTION, or BLOCK lending decision. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }
    post:
      operationId: createMonadLendingGuardExactDecision
      tags: [Safety]
      summary: Bind a Monad lending decision to one exact direct call
      description: >-
        Creates a portable EIP-712 decision for a read-only assessment and one
        unsigned direct Monad lending call. The decision remains non-authorizing
        and must be bound to user authorization before execution.
      security:
        - apiKey: []
        - {}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [guard, transaction]
              properties:
                guard: { type: object, description: The same lending fields accepted by GET. }
                transaction:
                  {
                    type: object,
                    description: Exact unsigned direct call,
                    sender,
                    nonce,
                    and zero value.,
                  }
      responses:
        '200':
          {
            description: Complete decision,
            optionally carrying an attestation when an eligible attester is configured.,
          }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }

  /safety/monad-lending-guard/verify:
    get:
      operationId: getMonadLendingGuardVerificationSchema
      tags: [Safety]
      summary: Get Monad lending guard attestation schema
      security: []
      responses:
        '200': { description: Attester status and supported EIP-712 schema. }
    post:
      operationId: verifyMonadLendingGuardDecision
      tags: [Safety]
      summary: Verify a Monad lending guard decision
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result and expiry state. }

  /safety/hyperevm-lending-guard:
    get:
      operationId: assessHyperEvmLendingGuard
      tags: [Safety]
      summary: HyperEVM lending risk decision
      description: >-
        Read-only risk gate for a caller-declared post-action lending position on
        HyperEVM (chain ID 999). It checks live HyperLend Core (Aave V3 fork)
        controls and oracle safety evidence; it never signs, submits, or
        authorizes a transaction. API-key access or x402 payment is accepted.
      security:
        - apiKey: []
        - {}
      parameters:
        - {
            name: protocolId,
            in: query,
            required: true,
            schema: { type: string, enum: [hyperlend-core-hyperevm] },
          }
        - {
            name: action,
            in: query,
            required: true,
            schema: { type: string, enum: [supply, borrow] },
          }
        - {
            name: collateralSymbol,
            in: query,
            required: true,
            schema: { type: string, example: WHYPE },
          }
        - { name: loanSymbol, in: query, required: true, schema: { type: string, example: USDC } }
        - {
            name: collateralValueUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 10000 },
          }
        - {
            name: debtValueUsd,
            in: query,
            required: true,
            schema: { type: number, minimum: 0, example: 5000 },
          }
      responses:
        '200': { description: Complete ALLOW, CAUTION, or BLOCK lending decision. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }
    post:
      operationId: createHyperEvmLendingGuardExactDecision
      tags: [Safety]
      summary: Bind a HyperEVM lending decision to one exact direct call
      description: >-
        Creates a portable EIP-712 decision for a read-only assessment and one
        unsigned direct HyperLend Core lending call. The decision remains
        non-authorizing and must be bound to user authorization before execution.
      security:
        - apiKey: []
        - {}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [guard, transaction]
              properties:
                guard: { type: object, description: The same lending fields accepted by GET. }
                transaction:
                  {
                    type: object,
                    description: Exact unsigned direct call,
                    sender,
                    nonce,
                    and zero value.,
                  }
      responses:
        '200':
          {
            description: Complete decision,
            optionally carrying an attestation when an eligible attester is configured.,
          }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }

  /safety/hyperevm-lending-guard/verify:
    get:
      operationId: getHyperEvmLendingGuardVerificationSchema
      tags: [Safety]
      summary: Get HyperEVM lending guard attestation schema
      security: []
      responses:
        '200': { description: Attester status and supported EIP-712 schema. }
    post:
      operationId: verifyHyperEvmLendingGuardDecision
      tags: [Safety]
      summary: Verify a HyperEVM lending guard decision
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result and expiry state. }

  /safety/multichain-evm-lending-guard:
    get:
      operationId: assessMultichainEvmLendingGuard
      tags: [Safety]
      summary: Base, Polygon, Arbitrum, and BNB lending risk decision
      description: >-
        Read-only risk gate for a caller-declared post-action lending position on
        Base, Polygon, Arbitrum, or BNB Chain. It validates the requested
        reviewed direct-call market against live protocol controls and oracle
        safety evidence. It never signs, submits, or authorizes a transaction.
        API-key access or x402 payment is accepted.
      security:
        - apiKey: []
        - {}
      parameters:
        - {
            name: chainId,
            in: query,
            required: true,
            schema: { type: integer, enum: [8453, 137, 42161, 56] },
          }
        - {
            name: protocolId,
            in: query,
            required: true,
            schema:
              {
                type: string,
                enum:
                  [
                    aave-v3-polygon,
                    aave-v3-arbitrum,
                    aave-v3-bnb,
                    venus-core-bnb,
                    compound-v3-arbitrum,
                    morpho-blue-polygon,
                    morpho-blue-arbitrum,
                    lista-moolah-bnb,
                    euler-v2-base,
                    euler-v2-arbitrum,
                    dolomite-arbitrum,
                    fluid-vault-t1-base,
                    fluid-vault-t1-arbitrum,
                  ],
              },
          }
        - {
            name: action,
            in: query,
            required: true,
            schema: { type: string, enum: [supply, borrow] },
          }
        - {
            name: collateralSymbol,
            in: query,
            required: true,
            schema: { type: string, example: WETH },
          }
        - { name: loanSymbol, in: query, required: true, schema: { type: string, example: USDC } }
        - {
            name: collateralValueUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 10000 },
          }
        - {
            name: debtValueUsd,
            in: query,
            required: true,
            schema: { type: number, minimum: 0, example: 5000 },
          }
      responses:
        '200': { description: Complete ALLOW, CAUTION, or BLOCK lending decision. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }
    post:
      operationId: createMultichainEvmLendingGuardExactDecision
      tags: [Safety]
      summary: Bind a multichain lending decision to one exact direct call
      description: >-
        Creates a portable EIP-712 decision for a read-only assessment and one
        unsigned direct EVM lending call. The decision remains non-authorizing
        and must be bound to user authorization before execution.
      security:
        - apiKey: []
        - {}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [guard, transaction]
              properties:
                guard: { type: object, description: The same lending fields accepted by GET. }
                transaction:
                  {
                    type: object,
                    description: Exact unsigned direct EVM call with sender,
                    nonce,
                    and zero value.,
                  }
      responses:
        '200':
          {
            description: Complete decision,
            optionally carrying an attestation when an eligible attester is configured.,
          }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }

  /safety/multichain-evm-lending-guard/verify:
    get:
      operationId: getMultichainEvmLendingGuardVerificationSchema
      tags: [Safety]
      summary: Get multichain EVM lending guard attestation schema
      security: []
      responses:
        '200': { description: Attester status and supported EIP-712 schema. }
    post:
      operationId: verifyMultichainEvmLendingGuardDecision
      tags: [Safety]
      summary: Verify a multichain EVM lending guard decision
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result and expiry state. }

  /safety/loopscale-vault-deposit:
    post:
      operationId: prepareLoopscaleVaultDeposit
      tags: [Safety]
      summary: Build and simulate one exact Loopscale vault deposit
      description: >-
        Read-only pre-signing gate that requests an unsigned deposit message
        only from Loopscale's official API, resolves its address tables, checks
        the vault and principal mint, and simulates the exact message on Solana
        mainnet. An ALLOW never signs, submits, or authorizes a transaction.
        API-key access or x402 payment is accepted.
      security:
        - apiKey: []
        - {}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                [
                  wallet,
                  vault,
                  assetMint,
                  collateralSymbol,
                  loanSymbol,
                  collateralValueUsd,
                  principalAmount,
                ]
              properties:
                wallet: { type: string, description: Solana wallet public key. }
                vault: { type: string, description: Loopscale vault public key. }
                assetMint: { type: string, description: Vault principal SPL mint. }
                collateralSymbol: { type: string, example: USDC }
                loanSymbol: { type: string, example: USDC }
                collateralValueUsd: { type: number, exclusiveMinimum: 0, example: 1000 }
                principalAmount: { type: string, pattern: '^[1-9][0-9]*$', example: '1000000' }
                minLpAmount: { type: string, pattern: '^(?:0|[1-9][0-9]*)$', default: '0' }
      responses:
        '200':
          {
            description: Complete BLOCK,
            CAUTION,
            or ALLOW decision with an exact unsigned message when accepted.,
          }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }

  /safety/solana-lending-guard:
    post:
      operationId: createSolanaLendingGuardExactDecision
      tags: [Safety]
      summary: Simulate and attest one exact Solana lending instruction
      description: >-
        Read-only pre-signing gate for one direct Kamino Lend, Marginfi v2,
        Jupiter Lend Earn, Save Lend, or Loopscale vault supply/borrow profile
        on Solana mainnet. It verifies protocol-owned accounts and simulates the
        exact unsigned message before issuing an Ed25519 decision when configured.
        It never signs, submits, or authorizes a transaction. API-key access or
        x402 payment is accepted.
      security:
        - apiKey: []
        - {}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [guard, transaction]
              properties:
                guard:
                  type: object
                  required:
                    [
                      protocolId,
                      action,
                      collateralSymbol,
                      loanSymbol,
                      collateralValueUsd,
                      debtValueUsd,
                    ]
                  properties:
                    protocolId:
                      {
                        type: string,
                        enum:
                          [kamino-lend, marginfi-v2, jupiter-lend-earn, save-lend, loopscale-vault],
                      }
                    action: { type: string, enum: [supply, borrow] }
                    collateralSymbol: { type: string, example: SOL }
                    loanSymbol: { type: string, example: USDC }
                    collateralValueUsd: { type: number, exclusiveMinimum: 0, example: 10000 }
                    debtValueUsd: { type: number, minimum: 0, example: 4000 }
                transaction:
                  type: object
                  description: >-
                    Complete unsigned legacy or v0 Solana message. Every
                    address lookup table must include its resolved addresses.
      responses:
        '200':
          {
            description: Complete BLOCK/CAUTION/ALLOW decision,
            optionally with a short-lived Ed25519 attestation.,
          }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }

  /safety/solana-lending-guard/verify:
    get:
      operationId: getSolanaLendingGuardVerificationSchema
      tags: [Safety]
      summary: Get Solana lending guard Ed25519 attester information
      security: []
      responses:
        '200': { description: Attester public key and schema status. }
    post:
      operationId: verifySolanaLendingGuardDecision
      tags: [Safety]
      summary: Verify a Solana lending guard decision
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result and expiry state. }

  /safety/solana-swap-guard:
    post:
      operationId: createSolanaSwapGuardExactDecision
      tags: [Safety]
      summary: Simulate and attest one exact Orca Whirlpool swap
      description: >-
        Read-only pre-signing gate for one legacy Whirlpool `swap` instruction in
        the reviewed USDC/USDT pool on Solana mainnet. It re-derives every
        reviewed identity from live mainnet state, prices the pool from its own
        sqrtPrice, runs both oracle checks, and simulates the exact unsigned
        message before issuing an Ed25519 decision when configured. It never
        signs, submits, or authorizes a transaction. API-key access or x402
        payment on the native Solana rail is accepted.
      security:
        - apiKey: []
        - {}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [guard, transaction]
              properties:
                guard:
                  type: object
                  required:
                    [
                      profileId,
                      direction,
                      sourceDecisionPriceUsd,
                      destinationDecisionPriceUsd,
                      policy,
                    ]
                  properties:
                    profileId: { type: string, enum: [solana-orca-whirlpool-usdc-usdt-1] }
                    direction: { type: string, enum: [usdc-to-usdt, usdt-to-usdc] }
                    sourceDecisionPriceUsd: { type: number, exclusiveMinimum: 0, example: 1 }
                    destinationDecisionPriceUsd:
                      { type: number, exclusiveMinimum: 0, example: 0.9987 }
                    policy:
                      type: object
                      required: [maxSlippageBps, maxReferenceDeviationBps]
                      properties:
                        maxSlippageBps: { type: integer, minimum: 0, maximum: 1000, example: 50 }
                        maxReferenceDeviationBps:
                          { type: integer, minimum: 0, maximum: 1000, example: 100 }
                transaction:
                  type: object
                  description: >-
                    Complete unsigned legacy Solana message containing exactly one
                    reviewed Whirlpool swap instruction. Every address lookup table
                    must include its resolved addresses.
      responses:
        '200':
          {
            description: Complete BLOCK/CAUTION/ALLOW decision,
            optionally with a short-lived Ed25519 attestation.,
          }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }

  /safety/solana-swap-guard/verify:
    get:
      operationId: getSolanaSwapGuardVerificationSchema
      tags: [Safety]
      summary: Get Solana swap guard Ed25519 attester information
      security: []
      responses:
        '200': { description: Attester public key and schema status. }
    post:
      operationId: verifySolanaSwapGuardDecision
      tags: [Safety]
      summary: Verify a Solana swap guard decision
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result and expiry state. }

  /safety/solana-swap-guard/settlement:
    post:
      operationId: settleSolanaSwapGuard
      tags: [Safety]
      summary: Close a Solana swap guard decision against on-chain facts
      description: >-
        Presents the signed guard decision plus the on-chain transaction
        signature. Insight re-verifies the decision, collects execution facts
        from Solana JSON-RPC, reconciles the observed wallet-level SPL balance
        deltas against the guarded exact amounts and minimum output, and returns
        a signed `SolanaSwapGuardSettlement` bound to the `decisionHash`. With
        `verifyOnly: true`, only the signed settlement's own Ed25519 signature is
        verified.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision, signature]
              properties:
                decision: { type: object, additionalProperties: true }
                signature:
                  { type: string, description: Base58 on-chain transaction signature (87-88 chars) }
                verifyOnly: { type: boolean, default: false }
                settlement: { type: object, additionalProperties: true }
      responses:
        '200':
          { description: Signed settlement receipt, or a verification result in verifyOnly mode. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '404': { description: The on-chain transaction signature was not found. }

  /safety/swap-intent:
    get:
      operationId: createPaidSwapIntent
      tags: [Safety]
      summary: Create a two-gate Swap Intent 🔒
      description: |
        The paid x402 path for a transaction-verifiable same-chain swap decision.
        It issues two signed schema-v3 Pre-Trade gates, one for each asset, and
        returns a `journeyId` plus one receipt credit once the x402 payment has
        settled. `venue` and `router` are caller claims, not verified venue facts.
        A `BLOCK` is a complete paid decision. Cross-chain intents are not supported.
      security:
        - apiKey: []
        - {}
      parameters:
        - { name: sourceAsset, in: query, required: true, schema: { type: string, example: ETH } }
        - {
            name: destinationAsset,
            in: query,
            required: true,
            schema: { type: string, example: USDC },
          }
        - { name: subjectChainId, in: query, required: true, schema: { type: integer, example: 1 } }
        - {
            name: settlementChainId,
            in: query,
            required: true,
            schema: { type: integer, example: 1 },
          }
        - {
            name: declaredNotionalUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0, example: 1000 },
          }
        - { name: venue, in: query, required: false, schema: { type: string, example: uniswap-v3 } }
        - {
            name: router,
            in: query,
            required: false,
            schema: { type: string, pattern: '^0x[0-9a-fA-F]{40}$' },
          }
      responses:
        '200':
          description: Two signed checks and next actions for receipt redemption or a voluntary non-execution report.
        '402':
          description: x402 v2 quote in PAYMENT-REQUIRED for anonymous calls.
    post:
      operationId: createApiKeySwapIntent
      tags: [Safety]
      summary: Create a two-gate Swap Intent with an API key 🔒
      description: API-key variant of Swap Intent. JSON body uses the same fields as the GET query contract.
      security:
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                [
                  sourceAsset,
                  destinationAsset,
                  subjectChainId,
                  settlementChainId,
                  declaredNotionalUsd,
                ]
              properties:
                sourceAsset: { type: string }
                destinationAsset: { type: string }
                subjectChainId: { type: integer }
                settlementChainId: { type: integer }
                declaredNotionalUsd: { type: number, exclusiveMinimum: 0 }
                venue: { type: string }
                router: { type: string, pattern: '^0x[0-9a-fA-F]{40}$' }
      responses:
        '200': { description: Two signed gates and a receipt capability. }

  /trade-journeys/outcome:
    post:
      operationId: reportSwapJourneyNotExecuted
      tags: [Execution Evidence]
      summary: Record a voluntary non-execution report
      description: |
        Records a caller statement that it did not execute the checked journey.
        It is intentionally not a claim about chain state: no callback or report
        is ever interpreted as proof that a transaction did not occur.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [journeyId, outcomeToken, reason]
              properties:
                journeyId: { type: string, format: uuid }
                outcomeToken: { type: string, minLength: 32 }
                reason:
                  type: string
                  enum: [risk_caution, market_changed, user_cancelled, integration_failed, other]
      responses:
        '200': { description: Voluntary report recorded. }
        '404': { description: Unknown journey or invalid caller capability. }
        '409': { description: Journey already has an execution or terminal state. }

  /oracle-watch:
    get:
      operationId: oracleWatch
      tags: [Safety]
      summary: Oracle Watch — always-on cross-oracle trust signal 🔒
      description: |
        Always-on companion to the pre-trade safety check. Condenses live cross-oracle
        consensus deviation, agreement, quorum, outliers and staleness into a single
        `NORMAL` / `CAUTION` / `DANGER` verdict with a `proceed` / `proceed_with_caution` /
        `halt` recommendation. Agents should poll this signal to monitor oracle risk for long-running strategies
        (yield, keepers, portfolios) between trades and pause when the verdict turns
        `DANGER`. When an asset has no cross-oracle coverage, the endpoint degrades to a
        `DANGER` / `halt` verdict instead of erroring. Verdict thresholds reuse the pre-trade
        rule set (deviation 1% / 3%, agreement 0.95 / 0.85) so both surfaces speak the same
        severity language.

        **Credit-metered** — any API key with sufficient credit balance.
      security:
        - apiKey: []
      parameters:
        - name: symbol
          in: query
          required: true
          description: Asset symbol, e.g. ETH, BTC.
          schema:
            type: string
            example: ETH
        - name: chain
          in: query
          required: false
          description: Optional blockchain filter, e.g. ethereum, arbitrum, base.
          schema:
            type: string
            example: ethereum
      responses:
        '200':
          description: Oracle Watch verdict
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OracleWatchResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'

  /oracle-watch/history:
    get:
      operationId: getOracleWatchHistory
      tags: [Safety]
      summary: Retrospective Oracle Watch credibility trend 🔒
      description: |
        Returns verdict stability, degraded-time ratio, worst deviation, mean credibility,
        and a time series for Oracle Watch. API-key requests receive the full retained
        90-day window on every paid plan. To keep responses bounded and complete, 30-minute
        points are available for windows up to 7 days, 8–30 day windows are rolled up hourly,
        and windows over 30 days are rolled up daily.

        Omitting `chain` selects the global (`chain IS NULL`) series; it does not mix rows
        from multiple blockchains.

        **Credit-metered** — any API key with sufficient credit balance.
      security:
        - apiKey: []
      parameters:
        - name: symbol
          in: query
          required: true
          description: Asset symbol, e.g. ETH, BTC.
          schema:
            type: string
            example: ETH
        - name: chain
          in: query
          required: false
          description: Optional blockchain filter. Omit for the global series.
          schema:
            type: string
            example: arbitrum
        - name: days
          in: query
          required: false
          description: Look-back window. API-key requests are capped at 90 days.
          schema:
            type: integer
            minimum: 1
            maximum: 365
            default: 30
        - name: interval
          in: query
          required: false
          description: Requested grain; long windows are automatically rolled up as described above.
          schema:
            type: string
            enum: [30min, hourly, daily]
      responses:
        '200':
          description: Oracle Watch historical credibility trend
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OracleWatchHistoryResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'

  # ── Risk Signals ─────────────────────────────────────────
  /oracles/health:
    get:
      operationId: getOracleHealth
      tags: [Risk Signals]
      summary: Oracle health report
      description: Comprehensive daily oracle health report with provider risk levels, feed diagnostics, shared-source dependency analysis, and risk impacts.
      security:
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/date'
      responses:
        '200':
          description: Oracle health report
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OracleHealthResponse'
        '404':
          $ref: '#/components/responses/NotFound'

  /stablecoins/depeg:
    get:
      operationId: getStablecoinDepeg
      tags: [Risk Signals]
      summary: Peg Risk — stablecoins
      description: Analyze the stablecoin category of Peg Risk by comparing oracle prices with DEX market prices.
      security:
        - apiKey: []
      parameters:
        - name: symbol
          in: query
          description: Stablecoin symbol (USDC, USDT, DAI, FRAX, LUSD, USDD). Omit for all.
          schema:
            type: string
            enum: [USDC, USDT, DAI, FRAX, LUSD, USDD]
      responses:
        '200':
          description: Depeg data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DepegResponse'

  /testing/scenarios:
    get:
      operationId: listOracleTestingScenarios
      tags: [Testing]
      summary: List built-in oracle scenario fixtures
      description: Replayable mechanism reconstructions of publicly documented oracle failures plus labeled synthetic scenarios, each with provenance.
      security: []
      responses:
        '200': { description: Scenario catalog with incident provenance }

  /testing/runs:
    get:
      operationId: getOracleTestingHarnessMeta
      tags: [Testing]
      summary: Get oracle testing harness metadata
      security: []
      responses:
        '200':
          { description: Harness version, scenario kinds, and expected detection codes per kind }
    post:
      operationId: runOracleScenario
      tags: [Testing]
      summary: Replay an oracle scenario against the detection policy
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                scenarioId: { type: string, description: Id of a built-in fixture scenario }
                scenario:
                  {
                    type: object,
                    additionalProperties: true,
                    description: Inline OracleScenario (validated server-side),
                  }
      responses:
        '200':
          {
            description: Deterministic run result plus a signed test attestation when an attester key is configured,
          }
        '400': { description: Inline scenario failed validation }
        '404': { description: Unknown scenarioId }

  /testing/attestations/verify:
    get:
      operationId: getOracleTestAttestationSchema
      tags: [Testing]
      summary: Get Oracle Test attestation schema and attester identity
      security: []
      responses:
        '200': { description: Attester identity and the frozen OracleScenarioRun EIP-712 schema }
    post:
      operationId: verifyOracleTestAttestation
      tags: [Testing]
      summary: Verify an Oracle Test attestation
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [attestation]
              properties:
                attestation: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result }

  /wrapped-assets/peg:
    get:
      operationId: getWrappedAssetPeg
      tags: [Risk Signals]
      summary: Peg Risk — wrapped and LST assets 🔒
      description: |
        Analyze the wrapped/LST category of Peg Risk (WBTC, cbBTC, tBTC, wstETH, cbETH, etc.).
        Compares market price against the underlying reference price.

        **Credit-metered** — any API key with sufficient credit balance.
      security:
        - apiKey: []
      parameters:
        - name: symbol
          in: query
          description: Wrapped asset symbol. Omit for all.
          schema:
            type: string
      responses:
        '200':
          description: Peg data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WrappedPegResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'

  # ── Data ────────────────────────────────────────────────
  /coverage:
    get:
      operationId: getCoverage
      tags: [Data]
      summary: Oracle coverage analysis
      description: |
        Coverage analysis by chain, provider, and symbol. Identifies single-provider risk assets.

        Public tier: registry aggregation requires no authentication. Live
        probes (`probe=true`) and cross-chain evidence
        (`includeCrossChainCandidate=true`) hit external provider endpoints
        and require an API key.
      security:
        - {}
        - apiKey: []
      responses:
        '200':
          description: Coverage data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CoverageResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'

  /coverage/policy:
    get:
      operationId: getCoveragePolicy
      tags: [Data]
      summary: Discover the versioned coverage readiness policy
      description: Returns policy bytes and their keccak256 canonical JSON content ID. Consumers must pin policy and signer trust independently. Does not activate a partner or execution gate. Uses coverage C2 metering.
      security:
        - apiKey: []
      parameters:
        - name: policyId
          in: query
          schema: { type: string }
          description: Optional exact policy ID; unknown IDs return 404.
      responses:
        '200':
          description: Standard success envelope containing policyId and policy
        '404':
          description: Unknown policy ID
        '402':
          $ref: '#/components/responses/CreditExhausted'

  /coverage/assessment:
    get:
      operationId: getCoverageAssessment
      tags: [Data]
      summary: Issue a live, scope-bound data-readiness report
      description: |
        Opt-in coverage v1. Checks classified providers, explicit evidence chain,
        oracle timestamp provenance, freshness, quorum, independent groups and spread.
        A PASS is not trade safety or execution permission. Separate Insight Coverage
        EIP-712 domain commits every observation and the policy ID. Consumers verify
        signature, policy, scope, key validity/revocation and current expiry locally.
        Missing signing configuration returns null signer/signature, which cannot
        authorize execution. Uses coverage C2 metering; Cache-Control is no-store.
      security:
        - apiKey: []
      parameters:
        - name: asset
          in: query
          required: true
          schema: { type: string, example: USDC }
        - name: chainId
          in: query
          required: true
          schema: { type: integer, minimum: 1, example: 1 }
        - name: policyId
          in: query
          required: true
          schema: { type: string, pattern: '^0x[0-9a-f]{64}$' }
      responses:
        '200':
          description: Coverage result; insufficient coverage is a signed result, not an HTTP error
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    required: [report, digest, signer, signature]
                    properties:
                      digest: { type: string, description: EIP-712 typed-data digest }
                      signer: { type: string, nullable: true }
                      signature: { type: string, nullable: true }
                      report:
                        type: object
                        required:
                          [
                            schema,
                            policyId,
                            asset,
                            evidenceChainId,
                            evaluatedAt,
                            validUntil,
                            observations,
                            evaluation,
                          ]
                        properties:
                          schema: { type: string, enum: [insight.coverage-report.v1] }
                          policyId: { type: string }
                          asset: { type: string }
                          evidenceChainId: { type: integer }
                          evaluatedAt: { type: integer, description: Unix seconds }
                          validUntil:
                            { type: integer, description: Exclusive Unix seconds deadline }
                          observations: { type: array, maxItems: 32, items: { type: object } }
                          evaluation:
                            type: object
                            properties:
                              status: { type: string, enum: [PASS, INSUFFICIENT_COVERAGE] }
                              eligibleProviders: { type: integer }
                              independentGroups: { type: integer }
                              spreadBps: { type: number, nullable: true }
                              reasons: { type: array, items: { type: string } }
                              providers: { type: array, items: { type: object } }
        '400':
          description: Invalid scope or unknown policy
        '402':
          $ref: '#/components/responses/CreditExhausted'
        '500':
          description: Registry, source service or signer unavailable; no authorization-grade proof

  /coverage/slo:
    get:
      operationId: getCoverageSlo
      tags: [Data]
      summary: Sampled data and signed-report readiness by asset, chain and policy
      description: Complete 15-minute slots from enrollment onward. Missing and failed samples remain in the denominator. Current partial slots are excluded. Empty history is WARMING_UP, never 100 percent. Internal objective, not a continuous-uptime SLA or execution verdict. Uses coverage C2 metering.
      security:
        - apiKey: []
      parameters:
        - name: hours
          in: query
          schema: { type: integer, enum: [24, 168, 672], default: 24 }
      responses:
        '200':
          description: Standard success envelope containing windowHours, cadenceSeconds, measuredAt and per-target counts, readiness rates, missing slots, error budget, burn rate and latest reasons
        '402':
          $ref: '#/components/responses/CreditExhausted'
        '500':
          description: Measurement store unavailable; must not be interpreted as healthy

  /hourly-snapshots:
    get:
      operationId: getHourlySnapshots
      tags: [Data]
      summary: Hourly price snapshots
      description: Query hourly price snapshots from the database for analysis and backtesting.
      security:
        - apiKey: []
      parameters:
        - name: symbol
          in: query
          schema:
            type: string
        - name: provider
          in: query
          schema:
            $ref: '#/components/schemas/OracleProvider'
        - $ref: '#/components/parameters/dateFrom'
        - $ref: '#/components/parameters/dateTo'
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 10000
            default: 2000
        - name: offset
          in: query
          schema:
            type: integer
            minimum: 0
            default: 0
      responses:
        '200':
          description: Hourly snapshots
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HourlySnapshotsResponse'

  /price-snapshots:
    get:
      operationId: getPriceSnapshots
      tags: [Data]
      summary: 15-minute price snapshots 🔒
      description: |
        Fine-grained (15-minute) price snapshots for deep analysis, backtesting,
        and anomaly research. 4x denser than the hourly snapshots, populated by
        the GitHub Actions snapshot-collect workflow. 6-month rolling archive.

        **Credit-metered** — any API key with sufficient credit balance.
      security:
        - apiKey: []
      parameters:
        - name: symbol
          in: query
          schema:
            type: string
        - name: provider
          in: query
          schema:
            $ref: '#/components/schemas/OracleProvider'
        - name: chainId
          in: query
          schema:
            type: integer
            minimum: 0
        - $ref: '#/components/parameters/dateFrom'
        - $ref: '#/components/parameters/dateTo'
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 10000
            default: 2000
        - name: offset
          in: query
          schema:
            type: integer
            minimum: 0
            default: 0
      responses:
        '200':
          description: 15-minute price snapshots
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PriceSnapshotsResponse'

  /price-records/export:
    get:
      operationId: exportPriceRecords
      tags: [Data]
      summary: Export price records 🔒
      description: |
        Export raw price records for external analysis. Supports filtering by symbol, provider, and date range.

        **Credit-metered** — any API key with sufficient credit balance.
      security:
        - apiKey: []
      parameters:
        - name: symbol
          in: query
          schema:
            type: string
        - name: provider
          in: query
          schema:
            $ref: '#/components/schemas/OracleProvider'
        - $ref: '#/components/parameters/dateFrom'
        - $ref: '#/components/parameters/dateTo'
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 50000
            default: 1000
        - name: offset
          in: query
          schema:
            type: integer
            minimum: 0
            default: 0
      responses:
        '200':
          description: Price records
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PriceExportResponse'
        '402':
          $ref: '#/components/responses/CreditExhausted'

  /reports/latest:
    get:
      operationId: getLatestDailyReport
      tags: [Data]
      summary: Latest daily risk report
      description: |
        Most recently published daily report. Public, no authentication
        required. Resolves today's report first, then walks back up to 7 days
        so a temporarily failed publication cycle still serves the newest
        available report. The payload carries `reportDate` and `ageDays` so
        consumers can detect staleness explicitly; poll this endpoint rather
        than expecting push delivery.
      security: []
      responses:
        '200':
          description: Latest daily report
          content:
            application/json:
              schema:
                type: object
                properties:
                  reportDate: { type: string, pattern: '^[0-9]{4}-[0-9]{2}-[0-9]{2}$' }
                  ageDays: { type: integer, minimum: 0, maximum: 7 }
                  report:
                    $ref: '#/components/schemas/DailyReportResponse'
        '404':
          description: No report published within the lookback window
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ApiErrorResponse' }

  /reports/daily/{date}:
    get:
      operationId: getDailyReport
      tags: [Data]
      summary: Daily risk report
      description: Full daily oracle risk report including metrics, provider rankings, deviation events, coverage matrix, and recommendations.
      security:
        - apiKey: []
      parameters:
        - name: date
          in: path
          required: true
          description: Report date (YYYY-MM-DD)
          schema:
            type: string
            pattern: '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
      responses:
        '200':
          description: Daily report
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DailyReportResponse'
        '404':
          $ref: '#/components/responses/NotFound'

  /health/ready:
    get:
      operationId: getHealthReadiness
      tags: [System]
      summary: Dependency readiness
      description: Checks database availability and freshness of the latest 15-minute price snapshot.
      security: []
      responses:
        '200':
          description: Dependencies are ready
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '503':
          description: Database unavailable or price data stale
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ApiErrorResponse' }

  /safety/prediction-guard:
    get:
      operationId: assessPolymarketGuard
      tags: [Safety]
      summary: Polymarket prediction-market screening decision
      description: >-
        Read-only screening gate for one Polymarket market. Cross-oracle
        consensus is deliberately not applied to event markets; the guard
        verifies machine-parseable price-contract metadata, lifecycle and
        resolution timing, quoted-probability integrity, and whether the
        declared settlement venue can be verified post-hoc. It never signs,
        submits, or authorizes an order. API-key access or x402 payment is
        accepted.
      security:
        - apiKey: []
        - {}
      parameters:
        - {
            name: protocolId,
            in: query,
            required: true,
            schema: { type: string, enum: [polymarket-prediction-mainnet] },
          }
        - {
            name: action,
            in: query,
            required: true,
            schema: { type: string, enum: [buy_up, buy_down] },
          }
        - {
            name: marketSlug,
            in: query,
            required: true,
            schema: { type: string, example: btc-updown-5m-1766162100 },
          }
      responses:
        '200': { description: Complete ALLOW, CAUTION, or BLOCK screening decision. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }
  /safety/tokenized-stock-guard:
    get:
      operationId: assessTokenizedStockGuard
      tags: [Safety]
      summary: Tokenized stock decision-input guard
      description: >-
        Read-only, pre-signing decision-input check for one Coinbase-tokenized
        stock (B20) on Base, evaluated against the issuer's official NAV
        reference. Applies a dedicated staleness lane for equity references —
        24h heartbeat, off-hours freeze (a documented design, not a fault),
        paused features, total-return multiplier, and caller-price deviation —
        and may return an Insight EIP-712 decision attestation. It never
        signs, submits, or authorizes an order. API-key access or x402
        payment is accepted.
      security:
        - apiKey: []
        - {}
      parameters:
        - { name: asset, in: query, required: true, schema: { type: string, example: TSLAc } }
        - {
            name: action,
            in: query,
            required: true,
            schema: { type: string, enum: [swap, borrow, lend, liquidate, repay] },
          }
        - {
            name: tradeAmountUsd,
            in: query,
            required: true,
            schema: { type: number, exclusiveMinimum: 0 },
          }
        - {
            name: decisionPriceUsd,
            in: query,
            required: false,
            schema: { type: number, exclusiveMinimum: 0 },
          }
        - {
            name: maxDeviationBps,
            in: query,
            required: false,
            schema: { type: integer, minimum: 0, maximum: 10000 },
          }
      responses:
        '200': { description: Complete ALLOW, WAIT, BLOCK, or NOT_PRICEABLE decision. }
        '400': { $ref: '#/components/responses/ValidationError' }
        '402': { $ref: '#/components/responses/CreditExhausted' }
  /safety/tokenized-stock-guard/verify:
    get:
      operationId: getTokenizedStockGuardVerificationSchema
      tags: [Safety]
      summary: Get tokenized stock guard attestation schema
      security: []
      responses:
        '200': { description: Attester status and supported EIP-712 schema. }
    post:
      operationId: verifyTokenizedStockGuardDecision
      tags: [Safety]
      summary: Verify a tokenized stock guard decision
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result and expiry state. }
  /safety/preflight:
    get:
      operationId: executionPreflight
      tags: [Safety]
      summary: Chain-neutral execution preflight decision 🔒
      description: |
        Converts Insight's strict oracle assessment and an optional fresh venue quote into a
        data-sufficiency decision: `allow` / `caution` / `block`. A result evaluates only the
        declared data inputs; it never certifies contract code, custody, MEV outcome, execution,
        or profitability. On Monad (chain ID 143), the result surfaces Pyth Core evidence when
        available. `allow` requires both a passing oracle assessment and an eligible supplied
        venue quote; without decision-input evidence, a healthy oracle result remains `caution`.

        **Ways to pay:** use an API key with sufficient credits, or pay $0.02 USDC per successful
        check through x402. A payment settles only after the preflight returns successfully.
      security:
        - apiKey: []
        - {}
      parameters:
        - name: asset
          in: query
          required: true
          description: Asset symbol, e.g. MON, ETH, BTC.
          schema: { type: string, example: MON }
        - name: chainId
          in: query
          required: true
          description: Execution chain ID; Monad mainnet is 143.
          schema: { type: integer, example: 143 }
        - name: action
          in: query
          required: true
          description: Type of intended DeFi operation.
          schema: { type: string, enum: [swap, borrow, lend, liquidate, repay], example: swap }
        - name: tradeAmountUsd
          in: query
          required: true
          description: Intended operation size in USD.
          schema: { type: number, exclusiveMinimum: 0, example: 1000 }
        - name: targetProviders
          in: query
          required: false
          description: Optional comma-separated provider scope. On Monad, `pyth` reads the pinned Pyth Core fast path; one provider remains insufficient for an `allow` response.
          schema: { type: string, example: pyth }
        - name: destinationAsset
          in: query
          required: false
          description: Optional route destination asset, e.g. USDC.
          schema: { type: string, example: USDC }
        - name: decisionInputCheck
          in: query
          required: false
          description: Set to `1` to supply a venue quote and explicit limits. Required for an `allow` response.
          schema: { type: string, enum: ['0', '1'] }
        - name: decisionPriceUsd
          in: query
          required: false
          description: Required with decisionInputCheck=1. Intended USD decision price.
          schema: { type: number, exclusiveMinimum: 0 }
        - name: quotePriceUsd
          in: query
          required: false
          description: Required with decisionInputCheck=1. Fresh venue quote in USD.
          schema: { type: number, exclusiveMinimum: 0 }
        - name: quoteObservedAt
          in: query
          required: false
          description: Required with decisionInputCheck=1. Offset-qualified ISO-8601 quote time.
          schema: { type: string, format: date-time }
        - name: maxReferenceDeviationBps
          in: query
          required: false
          schema: { type: integer, minimum: 0, maximum: 10000 }
        - name: maxSlippageBps
          in: query
          required: false
          schema: { type: integer, minimum: 0, maximum: 10000 }
        - name: maxQuoteAgeSeconds
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 300 }
        - name: reviewedUniswapV3AmountIn
          in: query
          required: false
          description: Exact source-token amount for the reviewed Monad/Base concentrated-liquidity lane. Requires decisionInputCheck=1, destinationAsset, and both reviewedUniswapV3 bps limits. The Base USDC→USDT profile is PancakeSwap V3; all other admitted profiles are Uniswap V3.
          schema: { type: string, pattern: '^(?:0\.(?:0*[1-9][0-9]*)|[1-9][0-9]*(?:\.[0-9]+)?)$' }
        - name: reviewedUniswapV3MaxQuoteDeviationBps
          in: query
          required: false
          description: Maximum reviewed-pool quote divergence from the submitted venue quote, in basis points.
          schema: { type: integer, minimum: 0, maximum: 10000 }
        - name: reviewedUniswapV3MaxTwapDeviationBps
          in: query
          required: false
          description: Maximum reviewed-pool spot-to-TWAP divergence, in basis points.
          schema: { type: integer, minimum: 0, maximum: 10000 }
        - name: reviewedAerodromeSlipstreamAmountIn
          in: query
          required: false
          description: Exact WETH input for the reviewed Base Aerodrome Slipstream WETH/USDC CL100 lane. Requires all reviewedAerodromeSlipstream parameters, decisionInputCheck=1, and destinationAsset=USDC. It cannot be combined with the reviewedUniswapV3 lane.
          schema: { type: string, pattern: '^(?:0\.(?:0*[1-9][0-9]*)|[1-9][0-9]*(?:\.[0-9]+)?)$' }
        - name: reviewedAerodromeSlipstreamMaxQuoteDeviationBps
          in: query
          required: false
          description: Maximum divergence between the pinned reviewed Aerodrome pool quote and the submitted venue quote, in basis points.
          schema: { type: integer, minimum: 0, maximum: 10000 }
        - name: reviewedAerodromeSlipstreamMaxTwapDeviationBps
          in: query
          required: false
          description: Maximum spot-to-TWAP divergence for the reviewed Aerodrome pool, in basis points.
          schema: { type: integer, minimum: 0, maximum: 10000 }
      responses:
        '200':
          description: Completed preflight decision with gates, reasons, and underlying strict assessment.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    required: [verdict, recommendation, gates, assessment]
                    properties:
                      verdict: { type: string, enum: [allow, caution, block] }
                      recommendation:
                        { type: string, enum: [proceed, review_before_execution, do_not_execute] }
                      gates: { type: object, additionalProperties: true }
                      assessment: { type: object, additionalProperties: true }
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '402': { $ref: '#/components/responses/CreditExhausted' }

  /safety/pre-trade/recheck:
    post:
      operationId: recheckPreTradeSafety
      tags: [Safety]
      summary: Re-check a previously attested trade
      description: Re-runs the safety check with fresh oracle state and binds the result to the original UID and request hash.
      security:
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [asset, chainId, action, tradeAmountUsd, originalUid, originalRequestHash]
              properties:
                asset: { type: string }
                chainId: { type: integer }
                action: { type: string, enum: [swap, borrow, lend, liquidate, repay] }
                tradeAmountUsd: { type: number, exclusiveMinimum: 0 }
                originalUid: { type: string }
                originalRequestHash: { type: string, pattern: '^0x[0-9a-fA-F]{64}$' }
                originalConsensusPrice: { type: number, exclusiveMinimum: 0 }
                maxDriftPct: { type: number, exclusiveMinimum: 0 }
                schemaVersion: { type: integer, enum: [2, 3] }
      responses:
        '200': { description: Fresh bound re-check result }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '402': { $ref: '#/components/responses/CreditExhausted' }

  /safety/attestation/verify:
    get:
      operationId: getSafetyAttestationVerificationSchema
      tags: [Safety]
      summary: Get safety attestation verification schemas
      security: []
      responses:
        '200': { description: Attester identity and supported EIP-712 schemas }
    post:
      operationId: verifySafetyAttestation
      tags: [Safety]
      summary: Verify a safety attestation
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [attestation]
              properties:
                attestation: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result }

  /safety/decision-input/evidence-pack:
    get:
      operationId: getDecisionEvidencePack
      tags: [Safety]
      summary: Assemble one operation's verifiable decision evidence pack
      description: Public assembly of one pre-trade operation's evidence chain (signed decision-input assessments, oracle pre-trade provenance, combined input-gate audit, signed execution receipt) into a manifest-hashed pack keyed by a 32-byte hex UID. The UID is the capability; the read is rate-limited and never cached. The pack is evidence for review and dispute, not authorization.
      security: []
      parameters:
        - name: preTradeUid
          in: query
          required: false
          schema: { type: string, pattern: '^0x[0-9a-fA-F]{64}$' }
          description: Anchor the pack on a pre-trade attestation UID
        - name: receiptUid
          in: query
          required: false
          schema: { type: string, pattern: '^0x[0-9a-fA-F]{64}$' }
          description: Anchor the pack on an execution receipt UID
      responses:
        '200':
          description: The assembled evidence pack, its computed manifest hashes, and a completeness summary of optional artifacts
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Malformed or missing UID, or nothing anchored to it }
    post:
      operationId: verifyDecisionEvidencePack
      tags: [Safety]
      summary: Verify a decision evidence pack without persisting anything
      description: Recomputes the manifest hashes, verifies carried decision-input assessment signatures, client-held oracle envelopes, anchor linkage, and (when the full triangle is present) the closed-loop execution pair. Nothing is persisted.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [pack]
              properties:
                pack:
                  type: object
                  description: A decision evidence pack as returned by the GET endpoint, optionally merged with client-held artifacts
                  additionalProperties: true
              additionalProperties: false
      responses:
        '200':
          description: Integrity result with manifest validity, per-assessment checks, client-envelope checks, closed-loop status, and anchor linkage
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Malformed verification request }

  /safety/decision-input/verify:
    get:
      operationId: getDecisionInputAttestationDescriptor
      tags: [Safety]
      summary: Get the decision-input attester and EIP-712 schema
      description: Public signer-readiness and verification descriptor. The status is READY, UNCONFIGURED, or UNTRUSTED_SIGNER.
      security: []
      responses:
        '200':
          description: Attester identity, readiness status, and frozen EIP-712 verification descriptor
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
    post:
      operationId: verifyDecisionInputAssessment
      tags: [Safety]
      summary: Verify a signed decision-input assessment
      description: Recomputes the canonical assessment digest and verifies the frozen EIP-712 signature, trusted attester, UID, linked pre-trade UID, and expiry. A valid signature proves integrity and issuer identity; it does not prove quote-source authenticity or authorize a transaction.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [assessment]
              properties:
                assessment:
                  type: object
                  description: Exact decisionInputAssessment object returned by the pre-trade endpoint, including its nested attestation
                  additionalProperties: true
              additionalProperties: false
      responses:
        '200':
          description: Cryptographic verification result, including validity, signer, digest, linked UID, expiry, and failure reason
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Malformed verification request }

  /oracle-watch/attestation/verify:
    get:
      operationId: getOracleWatchAttestationVerificationSchema
      tags: [Oracle Watch]
      summary: Get Oracle Watch verification schema
      security: []
      responses:
        '200': { description: Attester identity and supported EIP-712 schemas }
    post:
      operationId: verifyOracleWatchAttestation
      tags: [Oracle Watch]
      summary: Verify an Oracle Watch attestation
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [attestation]
              properties:
                attestation: { type: object, additionalProperties: true }
      responses:
        '200': { description: Cryptographic verification result }

  /safety/envelope:
    get:
      operationId: verifySafetyEnvelope
      tags: [Safety]
      summary: Verify the two-receipt safety envelope
      description: Public prototype that combines price-integrity and market-state receipts and fails closed.
      security: []
      parameters:
        - name: demo
          in: query
          schema: { type: string, enum: [live, expired, tampered, tampered-market], default: live }
        - name: mic
          in: query
          schema: { type: string, pattern: '^[A-Z]{4}$', default: XCOI }
      responses:
        '200': { description: Envelope verdict and independently verifiable member receipts }
        '400': { description: Invalid demo mode or MIC }

# ══════════════════════════════════════════════════════════
components:
  # ── Security Schemes ────────────────────────────────────
  securitySchemes:
    apiKey:
      type: apiKey
      in: header
      name: X-API-Key
      description: 'API key with `ins_` prefix (e.g. ins_a3f1...)'
  # ── Reusable Parameters ─────────────────────────────────
  parameters:
    PartnerId:
      name: partnerId
      in: path
      required: true
      schema:
        $ref: '#/components/schemas/PartnerId'
    provider:
      name: provider
      in: query
      required: true
      description: Oracle provider name
      schema:
        $ref: '#/components/schemas/OracleProvider'
    symbol:
      name: symbol
      in: query
      required: true
      description: 'Asset symbol (e.g. BTC/USD, ETH/USD)'
      schema:
        type: string
        minLength: 1
        maxLength: 20
    chain:
      name: chain
      in: query
      description: Blockchain slug
      schema:
        $ref: '#/components/schemas/Blockchain'
    forceRefresh:
      name: forceRefresh
      in: query
      description: Bypass cache and fetch fresh data
      schema:
        type: boolean
    date:
      name: date
      in: query
      description: 'Date in YYYY-MM-DD format. Defaults to today UTC.'
      schema:
        type: string
        pattern: '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
    dateFrom:
      name: from
      in: query
      description: 'Start date in YYYY-MM-DD format. Defaults to 7 days ago.'
      schema:
        type: string
        pattern: '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
    dateTo:
      name: to
      in: query
      description: 'End date in YYYY-MM-DD format. Defaults to today.'
      schema:
        type: string
        pattern: '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
    limit:
      name: limit
      in: query
      description: Maximum number of results
      schema:
        type: integer
        minimum: 1
        maximum: 500
        default: 100
    offset:
      name: offset
      in: query
      description: Number of results to skip
      schema:
        type: integer
        minimum: 0
        default: 0

  # ── Reusable Responses ──────────────────────────────────
  responses:
    Unauthorized:
      description: Missing or invalid authentication
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ApiErrorResponse'
          example:
            success: false
            error:
              code: UNAUTHORIZED
              message: 'Missing or invalid X-API-Key header.'
              retryable: false

    NotFound:
      description: Resource not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ApiErrorResponse'
          example:
            success: false
            error:
              code: SYMBOL_NOT_SUPPORTED
              message: 'No active oracle feed for the requested symbol.'
              retryable: false

    CreditExhausted:
      description: Wallet balance insufficient to cover the call's metering cost
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ApiErrorResponse'
          example:
            success: false
            error:
              code: CREDIT_EXHAUSTED
              message: 'Insufficient credit balance. Top up at /api#pricing.'
              retryable: false

    InsufficientData:
      description: Not enough data points to compute the requested metric
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ApiErrorResponse'
          example:
            success: false
            error:
              code: INSUFFICIENT_DATA
              message: 'Not enough data points to compute the requested metric.'
              retryable: false

    RateLimitExceeded:
      description: Too many requests
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ApiErrorResponse'
          example:
            success: false
            error:
              code: RATE_LIMIT_EXCEEDED
              message: 'Too many requests. Retry after the timestamp in the response header.'
              retryable: true

  # ── Schemas ─────────────────────────────────────────────
  schemas:
    PartnerId:
      type: string
      enum:
        - agent-passport
        - andydgrea
        - emilia
        - frontier-compute
        - headless
        - interai
        - raul
        - vaara
        - veritas

    ImmutablePartnerPolicyId:
      type: string
      pattern: '^0x[0-9a-fA-F]{64}$'
      description: Content-addressed immutable partner admission policy selected by the current activation set.

    ExecutionReceipt:
      type: object
      required: [uid, schemaVersion, attester, signature, data]
      properties:
        uid:
          type: string
          pattern: '^0x[0-9a-fA-F]{64}$'
        schemaVersion:
          type: integer
          enum: [1, 2, 3, 4, 5]
        attester:
          type: string
          pattern: '^0x[0-9a-fA-F]{40}$'
        signature:
          type: string
        data:
          type: object
          additionalProperties: true
        eip712:
          type: object
          additionalProperties: true
      additionalProperties: true

    ExecutionIssueRequest:
      type: object
      required:
        - preTradeUid
        - requestHash
        - sourceAssetId
        - destinationAssetId
        - subjectChainId
        - settlementChainId
        - participantCount
        - sourceGroupCount
        - preTradeSignedAt
        - quotedPrice
        - txHash
      properties:
        preTradeUid: { type: string, pattern: '^0x[0-9a-fA-F]{64}$' }
        requestHash: { type: string, pattern: '^0x[0-9a-fA-F]{64}$' }
        sourceAssetId: { type: string }
        destinationAssetId: { type: string }
        subjectChainId: { type: integer, minimum: 1 }
        settlementChainId: { type: integer, minimum: 1 }
        participantCount: { type: integer, minimum: 0 }
        sourceGroupCount: { type: integer, minimum: 0 }
        preTradeSignedAt: { type: integer }
        quotedPrice: { type: number }
        maxSlippageBps:
          type: integer
          enum: [50]
          description: Current signed platform policy; custom post-settlement values are rejected.
        action: { type: string }
        txHash: { type: string, pattern: '^0x[0-9a-fA-F]{64}$' }
        taker: { type: string, pattern: '^0x[0-9a-fA-F]{40}$' }
        preTradeAttestations:
          type: object
          required: [source, destination]
          properties:
            source: { type: object, additionalProperties: true }
            destination: { type: object, additionalProperties: true }

    # ── Enums ────────────────────────────────────────
    OracleProvider:
      type: string
      enum:
        - chainlink
        - api3
        - redstone
        - dia
        - winklink
        - supra
        - twap
        - reflector
        - flare

    Blockchain:
      type: string
      enum:
        - ethereum
        - arbitrum
        - optimism
        - polygon
        - solana
        - avalanche
        - fantom
        - cronos
        - juno
        - cosmos
        - osmosis
        - bnb-chain
        - base
        - scroll
        - zksync
        - aptos
        - sui
        - gnosis
        - mantle
        - linea
        - celestia
        - injective
        - sei
        - tron
        - ton
        - near
        - aurora
        - celo
        - starknet
        - blast
        - cardano
        - polkadot
        - kava
        - moonbeam
        - moonriver
        - metis
        - starkex
        - stellar
        - flare
        - supra-chain

    RiskLevel:
      type: string
      enum: [low, medium, high, critical]

    FeedHealthLevel:
      type: string
      enum: [healthy, fair, degraded, critical]

    ConsensusMethod:
      type: string
      enum: [median, trimmed_mean, weighted_median, iqr_filtered]

    FailureMode:
      type: string
      enum:
        - none
        - source_unavailable
        - stale_timestamp
        - delayed_update
        - fallback_metadata
        - partial_data
        - invalid_response
        - network_error
        - timeout
        - rate_limited

    # ── Common ───────────────────────────────────────
    ApiMeta:
      type: object
      properties:
        timestamp:
          type: integer
          description: Unix timestamp in milliseconds
        requestId:
          type: string
          description: Unique request identifier
      required: [timestamp]

    ApiError:
      type: object
      properties:
        code:
          type: string
          description: Machine-readable error code
        message:
          type: string
          description: Human-readable error message
        retryable:
          type: boolean
        details:
          type: object
          additionalProperties: true
      required: [code, message, retryable]

    ApiErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          enum: [false]
        error:
          $ref: '#/components/schemas/ApiError'
        meta:
          $ref: '#/components/schemas/ApiMeta'
      required: [success, error]

    OnChainVerification:
      type: object
      properties:
        type:
          type: string
          enum: [on-chain, api]
        contractAddress:
          type: string
        chainId:
          type: integer
        explorerUrl:
          type: string
          description: Link to blockchain explorer contract overview page
        method:
          type: string
          description: The on-chain method used to read the price (e.g. latestRoundData)
        blockNumber:
          type: integer

    ConfidenceInterval:
      type: object
      properties:
        bid:
          type: number
        ask:
          type: number
        widthPercentage:
          type: number

    # ── Price Data ────────────────────────────────────
    PriceData:
      type: object
      properties:
        symbol:
          type: string
        price:
          type: number
        timestamp:
          type: integer
        provider:
          $ref: '#/components/schemas/OracleProvider'
        chain:
          $ref: '#/components/schemas/Blockchain'
        source:
          type: string
          description: Display name of the oracle source
        decimals:
          type: integer
        confidence:
          type: number
        confidenceInterval:
          $ref: '#/components/schemas/ConfidenceInterval'
        dataAge:
          type: number
          description: Seconds since the price was last updated
        verification:
          $ref: '#/components/schemas/OnChainVerification'
        failureMode:
          $ref: '#/components/schemas/FailureMode'
      required: [symbol, price, timestamp, provider]

    # ── Health ────────────────────────────────────────
    HealthResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            status:
              type: string
              example: ok
            version:
              type: string
              example: v1
            timestamp:
              type: integer
        meta:
          $ref: '#/components/schemas/ApiMeta'
      required: [success, data]

    # ── Symbols ───────────────────────────────────────
    SymbolsResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: array
          items:
            type: string
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Metrics ───────────────────────────────────────
    MetricsResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            providers:
              type: integer
            activeFeeds:
              type: integer
            symbols:
              type: integer
            chains:
              type: integer
            categories:
              type: integer
            topProviders:
              type: array
              items:
                type: object
                properties:
                  provider:
                    type: string
                  score:
                    type: number
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Price ─────────────────────────────────────────
    PriceResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          $ref: '#/components/schemas/PriceData'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    BatchPriceRequest:
      type: object
      properties:
        queries:
          type: array
          items:
            type: object
            properties:
              provider:
                $ref: '#/components/schemas/OracleProvider'
              symbol:
                type: string
              chain:
                $ref: '#/components/schemas/Blockchain'
            required: [provider, symbol]
          minItems: 1
          maxItems: 20
        forceRefresh:
          type: boolean
          default: false
      required: [queries]

    BatchPriceResult:
      type: object
      properties:
        provider:
          type: string
        symbol:
          type: string
        chain:
          $ref: '#/components/schemas/Blockchain'
        price:
          $ref: '#/components/schemas/PriceData'
        error:
          type: string
          nullable: true

    BatchPriceResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: array
          items:
            $ref: '#/components/schemas/BatchPriceResult'
        meta:
          type: object
          properties:
            timestamp:
              type: integer
            partialErrors:
              type: array
              items:
                type: object
                required: [provider, symbol, error]
                properties:
                  provider:
                    $ref: '#/components/schemas/OracleProvider'
                  symbol:
                    type: string
                  chain:
                    $ref: '#/components/schemas/Blockchain'
                    nullable: true
                  error:
                    type: string
            queryCount:
              type: integer

    # ── Consensus ─────────────────────────────────────
    ConsensusProviderPrice:
      type: object
      properties:
        provider:
          $ref: '#/components/schemas/OracleProvider'
        symbol:
          type: string
        chain:
          $ref: '#/components/schemas/Blockchain'
        price:
          type: number
        deviationPct:
          type: number
          nullable: true
        isOutlier:
          type: boolean
        confidence:
          type: number
          nullable: true
        timestamp:
          type: integer
        dataAgeSeconds:
          type: number
          nullable: true
        source:
          type: string
        verification:
          $ref: '#/components/schemas/OnChainVerification'
        reputationScore:
          type: number
          nullable: true
        status:
          type: string
          enum: [success, unsupported, error]
        errorMessage:
          type: string

    ConsensusPriceResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            symbol:
              type: string
            chain:
              $ref: '#/components/schemas/Blockchain'
            consensusPrice:
              type: number
            method:
              $ref: '#/components/schemas/ConsensusMethod'
            recommendedMethod:
              $ref: '#/components/schemas/ConsensusMethod'
            confidence:
              type: number
              description: 0–1 confidence score
            confidenceLevel:
              type: string
              enum: [high, medium, low, very_low]
            agreement:
              type: number
              description: 0–1 agreement score among providers
            participantCount:
              type: integer
            excludedCount:
              type: integer
            excludedProviders:
              type: array
              items:
                type: string
            priceRange:
              type: object
              properties:
                min:
                  type: number
                max:
                  type: number
            methodResults:
              type: object
              description: Consensus price computed by each method
              additionalProperties:
                type: number
            providers:
              type: array
              items:
                $ref: '#/components/schemas/ConsensusProviderPrice'
            recommendedProvider:
              $ref: '#/components/schemas/OracleProvider'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── History ───────────────────────────────────────
    HistoryPriceResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: array
          items:
            $ref: '#/components/schemas/PriceData'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Feeds ─────────────────────────────────────────
    SettlementEvidencePack:
      type: object
      description: >-
        Hash-bound derived-analytics pack for one prediction-market settlement.
        Payload field order and semantics are frozen for schemaVersion 1 — this
        is what the attestation hash-binds.
      required: [payload, payloadHash]
      properties:
        payload:
          type: object
          required:
            [
              schemaVersion,
              marketSlug,
              question,
              asset,
              settlementVenue,
              windowStartMs,
              windowEndMs,
              windowSeconds,
              grade,
              gradeReasonCodes,
              generatedAtMs,
            ]
          properties:
            schemaVersion: { type: integer, const: 1 }
            marketSlug: { type: string }
            question: { type: string }
            asset: { type: string }
            settlementVenue:
              type: string
              enum: [chainlink-stream, binance, unknown]
            resolutionSourceUrl: { type: [string, 'null'] }
            windowStartMs: { type: integer, minimum: 0 }
            windowEndMs: { type: integer, minimum: 0 }
            windowSeconds: { type: integer, minimum: 60, maximum: 604800 }
            declaredOutcome: { type: [string, 'null'], enum: [Up, Down, null] }
            independentOutcome: { type: [string, 'null'], enum: [Up, Down, null] }
            priceChangeBps: { type: [number, 'null'] }
            oracleDeviationBps: { type: [number, 'null'] }
            oracleConsensusPrice: { type: [number, 'null'] }
            oracleSlotMs: { type: [integer, 'null'], minimum: 0 }
            candleCoverageE4: { type: [integer, 'null'], minimum: 0, maximum: 10000 }
            candleSource: { type: [string, 'null'] }
            candleRightsScope: { type: [string, 'null'] }
            candleDeliveryPolicy: { type: [string, 'null'] }
            grade:
              type: string
              enum: [consistent, inconsistent, insufficient_data]
            gradeReasonCodes:
              type: array
              items: { type: string }
            generatedAtMs: { type: integer, minimum: 0 }
        payloadHash:
          type: string
          description: keccak256 of the canonical payload JSON — the byte-stable identity.
        attestation:
          type: [object, 'null']
          description: >-
            EIP-712 attestation against Insight's published attester; null when
            the pack was persisted unsigned (signing key unavailable).
          required: [uid, schemaVersion, attester, signedAt, signature, eip712]
          properties:
            uid: { type: string }
            schemaVersion: { type: integer, const: 1 }
            attester: { type: string }
            attesterLabel: { type: string }
            signedAt: { type: string }
            validForSeconds: { type: integer }
            signature: { type: string }
            eip712:
              type: object
              properties:
                domain:
                  type: object
                  properties:
                    name: { type: string }
                    version: { type: string }
                    chainId: { type: integer }
                primaryType: { type: string }

    FeedEntry:
      type: object
      properties:
        id:
          type: string
          format: uuid
        provider:
          $ref: '#/components/schemas/OracleProvider'
        symbol:
          type: string
        chain_id:
          type: integer
        address:
          type: string
          nullable: true
        name:
          type: string
        decimals:
          type: integer
        category:
          type: string
        is_active:
          type: boolean
        consecutive_failures:
          type: integer
        last_success_at:
          type: string
          nullable: true
        last_failure_at:
          type: string
          nullable: true

    FeedsListResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            feeds:
              type: array
              items:
                $ref: '#/components/schemas/FeedEntry'
        meta:
          type: object
          properties:
            timestamp:
              type: integer
            total:
              type: integer

    FreshnessEntry:
      type: object
      properties:
        feedId:
          type: string
        provider:
          type: string
        symbol:
          type: string
        chainId:
          type: integer
        name:
          type: string
        category:
          type: string
        consecutiveFailures:
          type: integer
        lastSuccessAt:
          type: string
          nullable: true
        lastFailureAt:
          type: string
          nullable: true
        secondsSinceLastSuccess:
          type: number
          nullable: true
        secondsSinceLastFailure:
          type: number
          nullable: true
        status:
          type: string
          enum: [fresh, stale, outdated, never]

    FeedsFreshnessResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            timestamp:
              type: integer
            summary:
              type: object
              properties:
                totalFeeds:
                  type: integer
                byStatus:
                  type: object
                  properties:
                    fresh:
                      type: integer
                    stale:
                      type: integer
                    outdated:
                      type: integer
                    never:
                      type: integer
            feeds:
              type: array
              items:
                $ref: '#/components/schemas/FreshnessEntry'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    HeartbeatStatsEntry:
      type: object
      properties:
        provider:
          type: string
        symbol:
          type: string
        totalSnapshots:
          type: integer
        successfulSnapshots:
          type: integer
        successRate:
          type: number
        hoursWithData:
          type: integer
        totalHours:
          type: integer
        coveragePct:
          type: number
        avgSnapshotsPerDay:
          type: number

    HeartbeatStatsResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            from:
              type: string
            to:
              type: string
            totalHours:
              type: integer
            entries:
              type: array
              items:
                $ref: '#/components/schemas/HeartbeatStatsEntry'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    FeedHealthResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            feed:
              $ref: '#/components/schemas/FeedEntry'
            health:
              type: object
              properties:
                status:
                  type: string
                  enum: [healthy, degraded, critical]
                consecutiveFailures:
                  type: integer
                lastSuccessAt:
                  type: string
                  nullable: true
                lastFailureAt:
                  type: string
                  nullable: true
                timeSinceLastSuccess:
                  type: number
                  nullable: true
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Reputation ────────────────────────────────────
    OracleReputation:
      type: object
      properties:
        provider:
          $ref: '#/components/schemas/OracleProvider'
        overall_score:
          type: number
        accuracy_score:
          type: number
        reliability_score:
          type: number
        freshness_score:
          type: number
        uptime_percentage:
          type: number
        avg_deviation_pct:
          type: number
        avg_latency_ms:
          type: number
        total_queries:
          type: integer
        failed_queries:
          type: integer
        supported_symbols_count:
          type: integer
        supported_chains_count:
          type: integer
        last_calculated_at:
          type: string
          nullable: true

    ReputationTrendPoint:
      type: object
      properties:
        snapshot_time:
          type: string
        success_rate:
          type: number
        avg_deviation_pct:
          type: number
        avg_latency_ms:
          type: number
        query_count:
          type: integer

    ReputationListResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            reputations:
              type: array
              items:
                $ref: '#/components/schemas/OracleReputation'
        meta:
          type: object
          properties:
            timestamp:
              type: integer
            calculating:
              type: boolean

    RankingEntry:
      type: object
      properties:
        rank:
          type: integer
        provider:
          $ref: '#/components/schemas/OracleProvider'
        overallScore:
          type: number
        accuracyScore:
          type: number
        uptimePercentage:
          type: number
        reliabilityScore:
          type: number
        freshnessScore:
          type: number
        avgLatencyMs:
          type: number
        avgDeviationPct:
          type: number
        previousRank:
          type: integer
          nullable: true
        rankChange:
          type: integer
          nullable: true
        trend:
          type: string
          enum: [up, down, unchanged, no_data]

    RankingsResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            period:
              type: integer
            generatedAt:
              type: string
            totalProviders:
              type: integer
            scoreDistribution:
              type: object
              properties:
                average:
                  type: number
                max:
                  type: number
                min:
                  type: number
            rankings:
              type: array
              items:
                $ref: '#/components/schemas/RankingEntry'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    ProviderReputationResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            reputation:
              $ref: '#/components/schemas/OracleReputation'
            trend:
              type: array
              items:
                $ref: '#/components/schemas/ReputationTrendPoint'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Correlation ───────────────────────────────────
    CorrelationPair:
      type: object
      properties:
        provider1:
          type: string
        provider2:
          type: string
        correlation:
          type: number
        interpretation:
          type: string

    CorrelationResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            symbol:
              type: string
            from:
              type: string
            to:
              type: string
            dataPoints:
              type: integer
            providers:
              type: array
              items:
                type: string
            matrix:
              type: object
              additionalProperties:
                type: object
                additionalProperties:
                  type: number
            pairs:
              type: array
              items:
                $ref: '#/components/schemas/CorrelationPair'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Signals ───────────────────────────────────────
    SignalEntry:
      type: object
      properties:
        provider:
          type: string
        symbol:
          type: string
        timestamp:
          type: integer
        price:
          type: number
        confidence:
          type: number
        failureMode:
          $ref: '#/components/schemas/FailureMode'
        signalVector:
          type: object
          description: 5-dimensional signal vector
          properties:
            freshness:
              type: number
            sourceReliability:
              type: number
            metadataCompleteness:
              type: number
            consistency:
              type: number
            auditStatus:
              type: number
        metadata:
          type: object
          additionalProperties: true

    SignalsResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            from:
              type: string
            to:
              type: string
            count:
              type: integer
            dimensionAverages:
              type: object
              additionalProperties:
                type: number
            signals:
              type: array
              items:
                $ref: '#/components/schemas/SignalEntry'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Deviation ─────────────────────────────────────
    DeviationTimelinePoint:
      type: object
      properties:
        timestamp:
          type: integer
        consensusPrice:
          type: number
        providers:
          type: object
          additionalProperties:
            type: object
            properties:
              price:
                type: number
              deviationPct:
                type: number

    DeviationProviderSummary:
      type: object
      properties:
        provider:
          type: string
        snapshots:
          type: integer
        avgDeviationPct:
          type: number
        maxDeviationPct:
          type: number
        avgLatencyMs:
          type: number
        successRate:
          type: number

    DeviationResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            symbol:
              type: string
            dateRange:
              type: object
              properties:
                from:
                  type: string
                to:
                  type: string
            providers:
              type: array
              items:
                $ref: '#/components/schemas/DeviationProviderSummary'
            timeline:
              type: array
              items:
                $ref: '#/components/schemas/DeviationTimelinePoint'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Latency ───────────────────────────────────────
    LatencyEntry:
      type: object
      properties:
        provider:
          type: string
        symbol:
          type: string
        sampleSize:
          type: integer
        successRate:
          type: number
        min:
          type: number
        max:
          type: number
        mean:
          type: number
        p50:
          type: number
        p90:
          type: number
        p95:
          type: number
        p99:
          type: number

    LatencyResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            from:
              type: string
            to:
              type: string
            latencyDataAvailable:
              type: boolean
            overall:
              type: object
              nullable: true
              properties:
                p50:
                  type: number
                p90:
                  type: number
                p95:
                  type: number
                p99:
                  type: number
            entries:
              type: array
              items:
                $ref: '#/components/schemas/LatencyEntry'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Anomalies ─────────────────────────────────────
    AnomalyEvent:
      type: object
      properties:
        provider:
          type: string
        symbol:
          type: string
        deviationPct:
          type: number
        severity:
          type: string
          enum: [low, medium, high, critical]
        timestamp:
          type: integer
        reportDate:
          type: string
        message:
          type: string

    RiskImpact:
      type: object
      properties:
        category:
          type: string
          enum: [liquidation, stablecoin_depeg, wrapped_asset, oracle_reliability, systemic]
        severity:
          type: string
          enum: [low, medium, high, critical]
        title:
          type: string
        affectedEntities:
          type: array
          items:
            type: string
        description:
          type: string
        relatedAssets:
          type: array
          items:
            type: string
        relatedProviders:
          type: array
          items:
            type: string

    AnomaliesResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            periodDays:
              type: integer
            dateRange:
              type: object
              properties:
                start:
                  type: string
                end:
                  type: string
            totalEvents:
              type: integer
            bySeverity:
              type: object
              properties:
                low:
                  type: integer
                medium:
                  type: integer
                high:
                  type: integer
                critical:
                  type: integer
            byProvider:
              type: object
              additionalProperties:
                type: integer
            byAsset:
              type: object
              additionalProperties:
                type: integer
            topEvents:
              type: array
              items:
                $ref: '#/components/schemas/AnomalyEvent'
            topRiskImpacts:
              type: array
              items:
                $ref: '#/components/schemas/RiskImpact'
            reports:
              type: array
              items:
                type: object
                properties:
                  reportDate:
                    type: string
                  totalAnomalies:
                    type: integer
                  criticalEvents:
                    type: integer
                  highEvents:
                    type: integer
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Incidents ─────────────────────────────────────
    FeedFailureIncident:
      type: object
      properties:
        type:
          type: string
          enum: [feed_failure]
        severity:
          type: string
          enum: [low, medium, high, critical]
        status:
          type: string
          enum: [ongoing, recovered]
        provider:
          type: string
        symbol:
          type: string
        chainId:
          type: integer
        feedName:
          type: string
        feedId:
          type: string
        consecutiveFailures:
          type: integer
        isActive:
          type: boolean
        lastSuccessAt:
          type: string
          nullable: true
        lastFailureAt:
          type: string
          nullable: true
        description:
          type: string

    DeviationEventIncident:
      type: object
      properties:
        type:
          type: string
          enum: [deviation_event]
        severity:
          type: string
          enum: [low, medium, high, critical]
        status:
          type: string
          enum: [recorded]
        provider:
          type: string
        symbol:
          type: string
        snapshotTime:
          type: integer
        isSuccess:
          type: boolean
        failureMode:
          type: string
        deviationPct:
          type: number
        errorMessage:
          type: string
          nullable: true
        description:
          type: string

    IncidentsResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            from:
              type: string
            to:
              type: string
            total:
              type: integer
            bySeverity:
              type: object
              properties:
                low:
                  type: integer
                medium:
                  type: integer
                high:
                  type: integer
                critical:
                  type: integer
            byType:
              type: object
              additionalProperties:
                type: integer
            incidents:
              type: array
              items:
                oneOf:
                  - $ref: '#/components/schemas/FeedFailureIncident'
                  - $ref: '#/components/schemas/DeviationEventIncident'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Risk Summary ──────────────────────────────────
    HHIResult:
      type: object
      properties:
        value:
          type: number
        level:
          $ref: '#/components/schemas/RiskLevel'
        description:
          type: string
        concentrationRatio:
          type: number

    DiversificationResult:
      type: object
      properties:
        score:
          type: number
        level:
          $ref: '#/components/schemas/RiskLevel'
        description:
          type: string
        factors:
          type: object
          properties:
            chainDiversity:
              type: number
            protocolDiversity:
              type: number
            assetDiversity:
              type: number

    VolatilityResult:
      type: object
      properties:
        index:
          type: number
        level:
          $ref: '#/components/schemas/RiskLevel'
        description:
          type: string
        annualizedVolatility:
          type: number
        dailyVolatility:
          type: number

    CorrelationRiskResult:
      type: object
      properties:
        score:
          type: number
        level:
          $ref: '#/components/schemas/RiskLevel'
        description:
          type: string
        avgCorrelation:
          type: number
        highCorrelationPairs:
          type: array
          items:
            type: string
        correlationMatrix:
          type: array
          items:
            type: array
            items:
              type: number
        oracleNames:
          type: array
          items:
            type: string

    FreshnessRiskResult:
      type: object
      properties:
        score:
          type: number
        level:
          $ref: '#/components/schemas/RiskLevel'
        description:
          type: string
        staleOracleCount:
          type: integer
        maxStalenessSeconds:
          type: number
        staleOracles:
          type: array
          items:
            type: object
            properties:
              name:
                type: string
              stalenessSeconds:
                type: number

    ManipulationResistanceResult:
      type: object
      properties:
        score:
          type: number
        level:
          $ref: '#/components/schemas/RiskLevel'
        description:
          type: string
        factors:
          type: object
          properties:
            dataSourceDiversity:
              type: number
            aggregationRobustness:
              type: number
            updateFrequency:
              type: number
            onChainVerification:
              type: number

    SharedDependencyResult:
      type: object
      properties:
        score:
          type: number
        level:
          $ref: '#/components/schemas/RiskLevel'
        description:
          type: string
        sharedSourceGroups:
          type: array
          items:
            type: object
            properties:
              source:
                type: string
              oracles:
                type: array
                items:
                  type: string
        systemicRiskFactor:
          type: number

    RiskMetrics:
      type: object
      properties:
        overallRisk:
          type: object
          properties:
            score:
              type: number
            level:
              $ref: '#/components/schemas/RiskLevel'
            timestamp:
              type: integer
        hhi:
          $ref: '#/components/schemas/HHIResult'
        diversification:
          $ref: '#/components/schemas/DiversificationResult'
        volatility:
          $ref: '#/components/schemas/VolatilityResult'
        correlationRisk:
          $ref: '#/components/schemas/CorrelationRiskResult'
        freshnessRisk:
          $ref: '#/components/schemas/FreshnessRiskResult'
        manipulationResistance:
          $ref: '#/components/schemas/ManipulationResistanceResult'
        sharedDependency:
          $ref: '#/components/schemas/SharedDependencyResult'

    ProviderPriceResult:
      type: object
      properties:
        provider:
          $ref: '#/components/schemas/OracleProvider'
        price:
          type: number
        timestamp:
          type: integer
        chain:
          $ref: '#/components/schemas/Blockchain'
        error:
          type: string

    RiskSummaryResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            symbol:
              type: string
            providers:
              type: array
              items:
                $ref: '#/components/schemas/OracleProvider'
            periodHours:
              type: integer
            riskMetrics:
              $ref: '#/components/schemas/RiskMetrics'
            providerErrors:
              type: array
              items:
                $ref: '#/components/schemas/ProviderPriceResult'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Cross-Chain Spreads ───────────────────────────
    ChainPrice:
      type: object
      properties:
        chain:
          $ref: '#/components/schemas/Blockchain'
        chainName:
          type: string
        price:
          type: number
        timestamp:
          type: integer
        dataAgeSeconds:
          type: number
          nullable: true

    SpreadPair:
      type: object
      properties:
        xChain:
          $ref: '#/components/schemas/Blockchain'
        yChain:
          $ref: '#/components/schemas/Blockchain'
        x:
          type: string
        y:
          type: string
        value:
          type: number
        percent:
          type: number

    PriceDifference:
      type: object
      properties:
        chain:
          $ref: '#/components/schemas/Blockchain'
        chainName:
          type: string
        price:
          type: number
        diff:
          type: number
        diffPercent:
          type: number

    CrossChainSpreadResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            summary:
              type: object
              properties:
                provider:
                  $ref: '#/components/schemas/OracleProvider'
                symbol:
                  type: string
                baseChain:
                  $ref: '#/components/schemas/Blockchain'
                chainCount:
                  type: integer
                maxSpreadPercent:
                  type: number
            prices:
              type: array
              items:
                $ref: '#/components/schemas/ChainPrice'
            spreads:
              type: array
              items:
                $ref: '#/components/schemas/SpreadPair'
            priceDifferences:
              type: array
              items:
                $ref: '#/components/schemas/PriceDifference'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Protocols ─────────────────────────────────────
    ProtocolRiskParamsResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            protocolId:
              type: string
            protocolName:
              type: string
            chain:
              type: string
            protocolType:
              type: string
              enum: [lending, dex]
            assetCount:
              type: integer
            fetchedAt:
              type: string
              nullable: true
            assets:
              type: array
              items:
                type: object
                properties:
                  symbol:
                    type: string
                  liquidationThreshold:
                    type: number
                  maxLtv:
                    type: number
                  collateralFactor:
                    type: number
                  exchangeRate:
                    type: number
                  source:
                    type: string
                    enum: [on-chain, registry]
                  fetchedAt:
                    type: string
                    nullable: true
        meta:
          $ref: '#/components/schemas/ApiMeta'

    BulkRiskParamsResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: array
          items:
            type: object
            properties:
              protocolId:
                type: string
              protocolName:
                type: string
              chain:
                type: string
              protocolType:
                type: string
              assetCount:
                type: integer
              fetchedAt:
                type: string
                nullable: true
              assets:
                type: array
                items:
                  type: object
                  properties:
                    symbol:
                      type: string
                    liquidationThreshold:
                      type: number
                    maxLtv:
                      type: number
                    collateralFactor:
                      type: number
                    exchangeRate:
                      type: number
                    source:
                      type: string
                    fetchedAt:
                      type: string
                      nullable: true
        meta:
          $ref: '#/components/schemas/ApiMeta'

    ProtocolsListResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: array
          items:
            type: object
            properties:
              id:
                type: string
              name:
                type: string
              chain:
                type: string
              type:
                type: string
        meta:
          $ref: '#/components/schemas/ApiMeta'

    OracleExposureEntry:
      type: object
      properties:
        provider:
          type: string
        assetCount:
          type: integer
        assets:
          type: array
          items:
            type: string
        assetShare:
          type: number
        feedCount:
          type: integer
        overallScore:
          type: number
        freshnessScore:
          type: number
        reliabilityScore:
          type: number
        uptimePercentage:
          type: number
        avgDeviationPct:
          type: number

    OracleExposureResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            protocolId:
              type: string
            protocolName:
              type: string
            chain:
              type: string
            protocolType:
              type: string
            totalAssets:
              type: integer
            oracleProviders:
              type: array
              items:
                type: string
            isSingleOracleProvider:
              type: boolean
            concentrationRisk:
              type: object
              properties:
                level:
                  type: string
                  enum: [low, medium, high, critical]
                dominantProvider:
                  type: string
                dominantProviderAssetShare:
                  type: number
                description:
                  type: string
            exposures:
              type: array
              items:
                $ref: '#/components/schemas/OracleExposureEntry'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Safety ────────────────────────────────────────
    LiquidationScenario:
      type: object
      properties:
        label:
          type: string
        deviationPercent:
          type: number
        isJoint:
          type: boolean
        healthFactor:
          type: number
        collateralRatio:
          type: number
        status:
          type: string
          enum: [safe, warning, danger, liquidated]
        distanceToLiquidationPercent:
          type: number

    LiquidationRisk:
      type: object
      properties:
        protocolId:
          type: string
        protocolName:
          type: string
        chain:
          type: string
        collaterals:
          type: array
          items:
            type: object
            properties:
              symbol:
                type: string
              amount:
                type: number
              price:
                type: number
              value:
                type: number
        borrows:
          type: array
          items:
            type: object
            properties:
              symbol:
                type: string
              amount:
                type: number
              price:
                type: number
              value:
                type: number
        totalCollateralValue:
          type: number
        totalBorrowValue:
          type: number
        currentHealthFactor:
          type: number
        currentCollateralRatio:
          type: number
        liquidationThreshold:
          type: number
        jointCriticalDeviationPercent:
          type: number
        worstSingleAssetDeviation:
          type: object
          properties:
            symbol:
              type: string
            criticalDeviationPercent:
              type: number
            direction:
              type: string
        scenarios:
          type: array
          items:
            $ref: '#/components/schemas/LiquidationScenario'

    LiquidationResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            reportDate:
              type: string
            disclaimer:
              type: string
            risks:
              type: array
              items:
                $ref: '#/components/schemas/LiquidationRisk'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    PositionSafetyRequest:
      type: object
      properties:
        protocolId:
          type: string
          minLength: 1
        collaterals:
          type: array
          items:
            type: object
            properties:
              symbol:
                type: string
              amount:
                type: number
            required: [symbol, amount]
          minItems: 1
        borrows:
          type: array
          items:
            type: object
            properties:
              symbol:
                type: string
              amount:
                type: number
            required: [symbol, amount]
          minItems: 1
        collateralSymbol:
          type: string
          description: Single-asset mode — use instead of collaterals/borrows arrays
        collateralAmount:
          type: number
        borrowSymbol:
          type: string
        borrowAmount:
          type: number

    OracleWarning:
      type: object
      properties:
        provider:
          type: string
        overallScore:
          type: number
        freshnessScore:
          type: number
        reliabilityScore:
          type: number
        avgDeviationPct:
          type: number
        level:
          type: string
          enum: [healthy, fair, degraded, critical]
        message:
          type: string
        impact:
          type: string
        affectedSymbols:
          type: array
          items:
            type: string

    AssetDeviation:
      type: object
      properties:
        symbol:
          type: string
        currentPrice:
          type: number
        criticalDeviationPercent:
          type: number
        criticalPrice:
          type: number
        direction:
          type: string
        description:
          type: string

    SafetyBuffer:
      type: object
      properties:
        overallLevel:
          type: string
        bufferPercent:
          type: number
        theoreticalBufferPercent:
          type: number
        oracleAvgDeviationPercent:
          type: number
        liveDepegRiskPercent:
          type: number
        liveDepegBreakdown:
          type: object
          additionalProperties:
            type: number
        description:
          type: string
        recommendations:
          type: array
          items:
            type: string

    PositionSafetyResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            protocolId:
              type: string
            protocolName:
              type: string
            chain:
              type: string
            collaterals:
              type: array
              items:
                type: object
                properties:
                  symbol:
                    type: string
                  amount:
                    type: number
                  price:
                    type: number
                  value:
                    type: number
                  collateralFactor:
                    type: number
                  liquidationThreshold:
                    type: number
                  exchangeRate:
                    type: number
            borrows:
              type: array
              items:
                type: object
                properties:
                  symbol:
                    type: string
                  amount:
                    type: number
                  price:
                    type: number
                  value:
                    type: number
            totalCollateralValue:
              type: number
            totalAdjustedCollateralValue:
              type: number
            totalBorrowValue:
              type: number
            currentCollateralRatio:
              type: number
            currentHealthFactor:
              type: number
            assetDeviations:
              type: array
              items:
                $ref: '#/components/schemas/AssetDeviation'
            jointDeviation:
              $ref: '#/components/schemas/AssetDeviation'
            worstDeviation:
              $ref: '#/components/schemas/AssetDeviation'
            deviationRatios:
              type: object
              additionalProperties:
                type: number
            safetyBuffer:
              $ref: '#/components/schemas/SafetyBuffer'
            oracleWarnings:
              type: array
              items:
                $ref: '#/components/schemas/OracleWarning'
            deviationScenarios:
              type: array
              items:
                $ref: '#/components/schemas/LiquidationScenario'
            lastUpdated:
              type: integer
        meta:
          $ref: '#/components/schemas/ApiMeta'

    PreTradeSafetyResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            verdict:
              type: string
              enum: [PASS, CAUTION, DANGER, BLOCK]
              description: |
                Overall safety verdict. Agents MUST NOT execute trades when `DANGER` or `BLOCK`.
            consensusPrice:
              type: number
              description: Cross-oracle consensus price for the asset.
            maxDeviationPct:
              type: number
              description: Largest per-provider deviation from consensus (percentage).
            manipulationRiskScore:
              type: number
              minimum: 0
              maximum: 1
              description: Weighted manipulation risk score (0=low, 1=high).
            staleDataRisk:
              type: boolean
              description: True if any oracle data exceeds the staleness caution threshold.
            crossProviderAgreement:
              type: number
              minimum: 0
              maximum: 1
              description: Agreement score across providers (1=perfect agreement).
            recommendedMaxPositionUsd:
              type: number
              description: Suggested maximum position size in USD given current risk.
            participantCount:
              type: integer
              description: Number of oracle providers that contributed a price.
            providerPrices:
              type: object
              additionalProperties:
                type: object
                properties:
                  price:
                    type: number
                  deviationPct:
                    type: number
                    nullable: true
                  isOutlier:
                    type: boolean
                  dataAgeSeconds:
                    type: integer
                    nullable: true
                  isStale:
                    type: boolean
                  confidence:
                    type: number
                    nullable: true
                  reputationScore:
                    type: number
                    nullable: true
                  status:
                    type: string
                    enum: [success, unsupported, error]
            depegWarnings:
              type: array
              items:
                type: object
                properties:
                  stablecoin:
                    type: string
                  deviationPct:
                    type: number
                  riskLevel:
                    type: string
            warnings:
              type: array
              items:
                type: string
            contributingFactors:
              type: array
              items:
                type: object
                properties:
                  rule:
                    type: string
                  value:
                    type: number
                  threshold:
                    type: number
                  triggeredVerdict:
                    type: string
                    enum: [CAUTION, DANGER, BLOCK]
                  message:
                    type: string
            evaluatedAt:
              type: string
              format: date-time
            latencyMs:
              type: integer
            contextAttestation:
              type: object
              description: Independent EIP-712 capture statement. V2 binds the normalized tokenSecurity view; V1 verifies cryptographically but does not bind the returned view.
              required: [schemaVersion, capturedAt, entries]
              properties:
                schemaVersion:
                  type: integer
                  enum: [1, 2]
                capturedAt:
                  type: string
                  format: date-time
                entries:
                  type: array
                  minItems: 1
                  items:
                    type: object
                    required: [kind, source, request, rawResponseSha256, retrievedAt, priorSeal]
                    properties:
                      kind: { type: string, example: third_party_token_scan }
                      source: { type: string, example: gopluslabs }
                      request:
                        type: object
                        required: [chainId, contractAddress]
                        properties:
                          chainId: { type: integer, minimum: 1 }
                          contractAddress: { type: string, pattern: '^0x[0-9a-fA-F]{40}$' }
                      rawResponseSha256: { type: string, pattern: '^0x[0-9a-f]{64}$' }
                      normalizedResultSha256:
                        type: string
                        pattern: '^0x[0-9a-f]{64}$'
                        description: Required by schemaVersion 2; SHA-256 over canonical normalized tokenSecurity JSON.
                      retrievedAt: { type: string, format: date-time }
                      toolVersion: { type: string }
                      authorization: { type: string }
                      latencyMs: { type: integer, minimum: 0 }
                      transactionContext: { type: string }
                      priorSeal:
                        type: object
                        required: [manifest, signature, keyId]
                        properties:
                          manifest:
                            { type: string, enum: [context-attestation.v1, context-attestation.v2] }
                          signature: { type: string, pattern: '^0x[0-9a-fA-F]{130}$' }
                          keyId: { type: string, pattern: '^0x[0-9a-fA-F]{40}$' }
            tokenSecurity:
              type: object
              description: Advisory normalized third-party scan view. SchemaVersion 2 contextAttestation binds this exact view digest; it remains non-authorizing and source truth is not independently established.
              required: [schema, sourcedFrom, rawHash, advisory]
              properties:
                schema: { type: string, const: insight.token-security-view.v1 }
                sourcedFrom: { type: string, example: gopluslabs }
                rawHash: { type: string, pattern: '^0x[0-9a-f]{64}$' }
                advisory: { type: boolean, const: true }
                isHoneypot: { type: boolean }
                buyTaxPct: { type: number, minimum: 0, maximum: 100 }
                sellTaxPct: { type: number, minimum: 0, maximum: 100 }
                isOpenSource: { type: boolean }
                isProxy: { type: boolean }
                isMintable: { type: boolean }
                hiddenOwner: { type: boolean }
                holderCount: { type: integer, minimum: 0 }
                isInCex: { type: boolean }
                trustList: { type: boolean }
                tokenSymbol: { type: string, maxLength: 128 }
        meta:
          $ref: '#/components/schemas/ApiMeta'

    OracleWatchResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            symbol:
              type: string
              description: Asset symbol.
            chain:
              type: string
              nullable: true
              description: Blockchain the signal was scoped to, if any.
            verdict:
              type: string
              enum: [normal, caution, danger]
              description: |
                Always-on trust verdict. `danger` means pause dependent operations; it also
                covers assets with no cross-oracle coverage.
            recommendation:
              type: string
              enum: [proceed, proceed_with_caution, halt]
              description: Actionable recommendation for an agent.
            maxDeviationPct:
              type: number
              nullable: true
              description: Max |deviation from consensus| across responding providers.
            agreement:
              type: number
              minimum: 0
              maximum: 1
              description: Cross-provider agreement (1 = perfect agreement).
            participantCount:
              type: integer
              description: Number of providers that contributed a price.
            outlierCount:
              type: integer
              description: Number of responding providers flagged as outliers.
            staleCount:
              type: integer
              description: Number of responding providers whose data is stale.
            consensusPrice:
              type: number
              nullable: true
              description: Cross-oracle consensus price for the asset.
            reason:
              type: string
              description: Machine-readable reason for the verdict.
            quorumSatisfied:
              type: boolean
              description: True when at least 3 independent providers are responding.
            trustScore:
              type: number
              minimum: 0
              maximum: 100
              description: Composite 0-100 credibility rating an agent can gate on.
            trustLevel:
              type: string
              enum: [low, medium, high]
              description: Discrete credibility gate derived from trustScore.
            providers:
              type: array
              items:
                type: object
                properties:
                  provider:
                    type: string
                  status:
                    type: string
                    enum: [success, unsupported, error]
                  deviationPct:
                    type: number
                    nullable: true
                  isOutlier:
                    type: boolean
                  isStale:
                    type: boolean
            evaluatedAt:
              type: string
              format: date-time
        meta:
          $ref: '#/components/schemas/ApiMeta'

    OracleWatchHistoryPoint:
      type: object
      properties:
        evaluatedAt:
          type: string
          format: date-time
          description: Start of the returned aggregation bucket.
        verdict:
          type: string
          enum: [normal, caution, danger]
        recommendation:
          type: string
        maxDeviationPct:
          type: number
          nullable: true
        agreement:
          type: number
          minimum: 0
          maximum: 1
        participantCount:
          type: integer
        mlRiskScore:
          type: number
          nullable: true
        mlRiskLevel:
          type: string
          nullable: true
          enum: [low, medium, high]
        trustScore:
          type: number
          nullable: true
          minimum: 0
          maximum: 100
        trustLevel:
          type: string
          nullable: true
          enum: [low, medium, high]

    OracleWatchHistorySummary:
      type: object
      properties:
        pointCount:
          type: integer
        currentVerdict:
          type: string
          nullable: true
          enum: [normal, caution, danger]
        normal:
          type: integer
        caution:
          type: integer
        danger:
          type: integer
        degradedRatio:
          type: number
          minimum: 0
          maximum: 1
        stabilityScore:
          type: number
          minimum: 0
          maximum: 100
        avgAgreement:
          type: number
          minimum: 0
          maximum: 1
        maxDeviationPct:
          type: number
          nullable: true
        trustScore:
          type: number
          nullable: true
          minimum: 0
          maximum: 100
        trustLevel:
          type: string
          nullable: true
          enum: [low, medium, high]
        lastCollectedAt:
          type: string
          format: date-time
          nullable: true
        spineStale:
          type: boolean

    OracleWatchHistoryResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            symbol:
              type: string
            chain:
              type: string
              nullable: true
            days:
              type: integer
            grain:
              type: string
              enum: [30min, hourly, daily]
              description: Effective grain after automatic long-window rollup.
            series:
              type: array
              items:
                $ref: '#/components/schemas/OracleWatchHistoryPoint'
            summary:
              $ref: '#/components/schemas/OracleWatchHistorySummary'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Oracle Health ─────────────────────────────────
    OracleHealthIssue:
      type: object
      properties:
        code:
          type: string
          enum:
            [
              heartbeat_missing,
              update_delay,
              provider_deviation,
              failure_rate,
              single_source_dependency,
              shared_source_dependency,
            ]
        severity:
          type: string
          enum: [low, medium, high]
        message:
          type: string

    OracleHealthProviderStatus:
      type: object
      properties:
        provider:
          $ref: '#/components/schemas/OracleProvider'
        displayName:
          type: string
        riskLevel:
          type: string
          enum: [low, medium, high]
        reason:
          type: string
        issues:
          type: array
          items:
            $ref: '#/components/schemas/OracleHealthIssue'
        stats:
          type: object
          properties:
            totalSnapshots:
              type: integer
            successRate:
              type: number
            avgLatencyMs:
              type: number
            avgDeviationPct:
              type: number
            maxDeviationPct:
              type: number
            avgDataAgeSeconds:
              type: number
            maxDataAgeSeconds:
              type: number
            observedAssets:
              type: array
              items:
                type: string
        feedHealth:
          type: object
          properties:
            score:
              type: number
            level:
              $ref: '#/components/schemas/FeedHealthLevel'
            rhythmStability:
              type: number
            confidenceStability:
              type: number
            heartbeatReliability:
              type: number
            freshness:
              type: number
            expectedIntervalSeconds:
              type: number
            actualAvgIntervalSeconds:
              type: number
            intervalCv:
              type: number
            isHeartbeatLost:
              type: boolean
            missedBeats:
              type: number
            maxGapSeconds:
              type: number
        dependency:
          type: object
          properties:
            riskLevel:
              type: string
              enum: [low, medium, high]
            reason:
              type: string
            primaryDataSources:
              type: array
              items:
                type: string
            dataSourceCount:
              type: integer
            sharedWithProviders:
              type: array
              items:
                type: string
            overlapRatio:
              type: number
            aggregationMethod:
              type: string
            hasOnChainVerification:
              type: boolean

    OracleHealthResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            reportDate:
              type: string
            summary:
              type: object
              properties:
                total:
                  type: integer
                bySeverity:
                  type: object
                  properties:
                    low:
                      type: integer
                    medium:
                      type: integer
                    high:
                      type: integer
                    critical:
                      type: integer
                byProvider:
                  type: object
                  additionalProperties:
                    type: integer
                byAsset:
                  type: object
                  additionalProperties:
                    type: integer
            overview:
              type: object
              properties:
                riskLevel:
                  type: string
                reason:
                  type: string
                monitoredProviders:
                  type: integer
                lowRiskProviders:
                  type: integer
                mediumRiskProviders:
                  type: integer
                highRiskProviders:
                  type: integer
                overallHealthAvg:
                  type: number
                overallHealthLevel:
                  $ref: '#/components/schemas/FeedHealthLevel'
                anomalyCount:
                  type: integer
            providers:
              type: array
              items:
                $ref: '#/components/schemas/OracleHealthProviderStatus'
            sharedDependency:
              type: object
              properties:
                score:
                  type: number
                level:
                  $ref: '#/components/schemas/RiskLevel'
                systemicRiskFactor:
                  type: number
                sharedSourceGroups:
                  type: array
                  items:
                    type: object
                    properties:
                      source:
                        type: string
                      oracles:
                        type: array
                        items:
                          type: string
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Depeg / Peg ──────────────────────────────────
    DepegSource:
      type: object
      properties:
        sourceId:
          type: string
        provider:
          type: string
        chain:
          type: string
        symbol:
          type: string
        price:
          type: number
        timestamp:
          type: integer
        deviationPercent:
          type: number
        category:
          type: string
          enum: [oracle, market]
        dexName:
          type: string
        poolAddress:
          type: string

    DepegData:
      type: object
      properties:
        symbol:
          type: string
        displayName:
          type: string
        targetPeg:
          type: number
        referencePrice:
          type: number
        referenceMethod:
          type: string
        maxDeviationPercent:
          type: number
        spreadPercent:
          type: number
        marketReferencePrice:
          type: number
        marketSpreadPercent:
          type: number
        oracleMarketDivergencePercent:
          type: number
        oracleMarketDirection:
          type: string
        riskLevel:
          type: string
          enum: [normal, low, medium, high, critical]
        riskReason:
          type: string
        sources:
          type: array
          items:
            $ref: '#/components/schemas/DepegSource'
        affectedProtocols:
          type: array
          items:
            type: string
        lastUpdated:
          type: integer

    DepegResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          oneOf:
            - $ref: '#/components/schemas/DepegData'
            - type: array
              items:
                $ref: '#/components/schemas/DepegData'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    WrappedPegSource:
      type: object
      properties:
        sourceId:
          type: string
        provider:
          type: string
        chain:
          type: string
        symbol:
          type: string
        price:
          type: number
        timestamp:
          type: integer
        deviationPercent:
          type: number
        category:
          type: string
        verification:
          $ref: '#/components/schemas/OnChainVerification'

    WrappedPegData:
      type: object
      properties:
        symbol:
          type: string
        displayName:
          type: string
        type:
          type: string
        underlyingSymbol:
          type: string
        wrappedMarketPrice:
          type: number
        underlyingReferencePrice:
          type: number
        exchangeRate:
          type: number
        fairUnderlyingPrice:
          type: number
        deviationPercent:
          type: number
        riskLevel:
          type: string
          enum: [normal, low, medium, high, critical]
        sources:
          type: array
          items:
            $ref: '#/components/schemas/WrappedPegSource'
        affectedProtocols:
          type: array
          items:
            type: string
        lastUpdated:
          type: integer

    WrappedPegResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          oneOf:
            - $ref: '#/components/schemas/WrappedPegData'
            - type: array
              items:
                $ref: '#/components/schemas/WrappedPegData'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Coverage ──────────────────────────────────────
    CoverageByChain:
      type: object
      properties:
        chainId:
          type: integer
        feedCount:
          type: integer
        providers:
          type: array
          items:
            type: string
        symbols:
          type: array
          items:
            type: string
        categories:
          type: array
          items:
            type: string
        providerCount:
          type: integer
        symbolCount:
          type: integer

    CoverageByProvider:
      type: object
      properties:
        provider:
          type: string
        feedCount:
          type: integer
        chains:
          type: array
          items:
            type: string
        symbols:
          type: array
          items:
            type: string
        categories:
          type: array
          items:
            type: string
        chainCount:
          type: integer
        symbolCount:
          type: integer

    CoverageBySymbol:
      type: object
      properties:
        symbol:
          type: string
        feedCount:
          type: integer
        providers:
          type: array
          items:
            type: string
        chains:
          type: array
          items:
            type: string
        categories:
          type: array
          items:
            type: string
        providerCount:
          type: integer
        chainCount:
          type: integer

    CoverageResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            summary:
              type: object
              properties:
                totalFeeds:
                  type: integer
                totalProviders:
                  type: integer
                totalSymbols:
                  type: integer
                totalChains:
                  type: integer
                singleProviderRiskCount:
                  type: integer
            byChain:
              type: array
              items:
                $ref: '#/components/schemas/CoverageByChain'
            byProvider:
              type: array
              items:
                $ref: '#/components/schemas/CoverageByProvider'
            bySymbol:
              type: array
              items:
                $ref: '#/components/schemas/CoverageBySymbol'
            singleProviderRisk:
              type: array
              items:
                type: object
                properties:
                  symbol:
                    type: string
                  provider:
                    type: string
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Hourly Snapshots ──────────────────────────────
    HourlySnapshot:
      type: object
      properties:
        snapshot_hour:
          type: string
        provider:
          type: string
        symbol:
          type: string
        price:
          type: number
        consensus_price:
          type: number
        deviation_pct:
          type: number
        latency_ms:
          type: number
        data_age_seconds:
          type: number
        confidence:
          type: number
        is_success:
          type: boolean

    HourlySnapshotsResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            from:
              type: string
            to:
              type: string
            count:
              type: integer
            snapshots:
              type: array
              items:
                $ref: '#/components/schemas/HourlySnapshot'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── 15-min Price Snapshots ───────────────────────
    PriceSnapshot:
      type: object
      properties:
        snapshot_ts:
          type: string
          description: Precise 15-minute grain timestamp.
        snapshot_hour:
          type: string
          description: snapshot_ts truncated to the hour (aligns with hourly snapshots).
        provider:
          type: string
        symbol:
          type: string
        chain_id:
          type: integer
        price:
          type: number
        consensus_price:
          type: number
        deviation_pct:
          type: number
        latency_ms:
          type: number
        data_age_seconds:
          type: number
        confidence:
          type: number
        is_success:
          type: boolean

    PriceSnapshotsResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            grain:
              type: string
              example: '15min'
            from:
              type: string
            to:
              type: string
            count:
              type: integer
            snapshots:
              type: array
              items:
                $ref: '#/components/schemas/PriceSnapshot'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Price Export ──────────────────────────────────
    PriceExportRecord:
      type: object
      properties:
        provider:
          type: string
        symbol:
          type: string
        chain:
          type: string
        price:
          type: number
        timestamp:
          type: integer
        confidence:
          type: number
        source:
          type: string
        verification:
          $ref: '#/components/schemas/OnChainVerification'

    PriceExportResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            exportedAt:
              type: string
            filters:
              type: object
              properties:
                symbol:
                  type: string
                provider:
                  type: string
                from:
                  type: string
                to:
                  type: string
            count:
              type: integer
            records:
              type: array
              items:
                $ref: '#/components/schemas/PriceExportRecord'
        meta:
          $ref: '#/components/schemas/ApiMeta'

    # ── Daily Report ──────────────────────────────────
    ProviderRanking:
      type: object
      properties:
        provider:
          $ref: '#/components/schemas/OracleProvider'
        totalQueries:
          type: integer
        successQueries:
          type: integer
        successRate:
          type: number
        avgLatencyMs:
          type: number
        avgDeviationPct:
          type: number
        maxDeviationPct:
          type: number
        anomalyCount:
          type: integer
        score:
          type: number

    DailyReportResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            reportDate:
              type: string
            reportTitle:
              type: string
            summary:
              type: string
            recommendations:
              type: array
              items:
                type: string
            metrics:
              type: object
              properties:
                totalSnapshots:
                  type: integer
                successfulSnapshots:
                  type: integer
                failedSnapshots:
                  type: integer
                overallSuccessRate:
                  type: number
                avgDeviationPct:
                  type: number
                totalAnomalies:
                  type: integer
                criticalEvents:
                  type: integer
                highEvents:
                  type: integer
                activeProviders:
                  type: integer
                activeAssets:
                  type: integer
            topAssets:
              type: array
              items:
                type: object
                properties:
                  symbol:
                    type: string
                  avgDeviationPct:
                    type: number
                  maxDeviationPct:
                    type: number
                  anomalyCount:
                    type: integer
            providerRankings:
              type: array
              items:
                $ref: '#/components/schemas/ProviderRanking'
            deviationEvents:
              type: array
              items:
                $ref: '#/components/schemas/AnomalyEvent'
            anomalySummary:
              type: object
              properties:
                total:
                  type: integer
                bySeverity:
                  type: object
                  properties:
                    low:
                      type: integer
                    medium:
                      type: integer
                    high:
                      type: integer
                    critical:
                      type: integer
            previousDayComparison:
              type: object
              properties:
                reportAvailable:
                  type: boolean
                successRateChangePct:
                  type: number
                avgDeviationChangePct:
                  type: number
                anomalyChangePct:
                  type: number
            riskImpacts:
              type: array
              items:
                $ref: '#/components/schemas/RiskImpact'
        meta:
          $ref: '#/components/schemas/ApiMeta'
