openapi: 3.1.0
info:
  title: PayFi signing service
  version: 1.0.0
  summary: The HTTP API of Untangled's PayFi signing service, one service for many lines.
  description: |
    The signing service checks, co-signs and submits the PayFi flows of each line: pay-ins,
    advances, releases, repayments, cover withdrawals, liquidations and default take-overs.
    A line is one PO with its own market, POT, settlement account, gate, and gated and gate-free adapters.

    Conventions:

    - Amounts are decimal strings of whole tokens with at most 7 decimals ("1000", "0.5").
      Ledger numbers and seconds are integers.
    - Every response carries `request_id`, also sent as the `X-Request-Id` header.
    - Every failure has the same envelope, `Error`, with a machine-readable `code`.
    - Every POST and DELETE that moves money or changes state takes an `Idempotency-Key`
      header. The service keeps the key, the route, a hash of the body and the response for
      24 hours. The same key with the same body returns the stored response with the header
      `Idempotent-Replayed: true`. The same key with a different body is refused with 409
      `IDEMPOTENCY_KEY_REUSED`. A request still running under the key answers 409
      `IDEMPOTENCY_IN_PROGRESS`.
    - Lists are cursor-paged: `?limit=` (default 50, at most 200) and `?cursor=` from the
      previous page's `next_cursor`. `next_cursor` is null on the last page.
    - There are no bearer tokens. Money moves are proved by the PO's or the admin's signature
      on the transaction, so they need nothing extra. Off-chain changes and private reads need
      a request signed by a key the line registers (`x-payfi-auth` on each operation): `po` is
      one of the PO's keys (`poOps`, `poAdmin` or an API key in `po.apiKeys`), `admin` is
      Untangled's admin key, `signed` is either, and `read` also takes a read grant. `open`
      routes take anyone; a caller with a key or read grant of the line is told more (the
      screening reasons). `none` and `open` routes are rate-limited per client address.
    - A signed request carries `PayFi-Key: G…`, `PayFi-Signature` (base64), `PayFi-Time`
      (ISO-8601 UTC to the second) and `PayFi-Nonce` (16 hex). The key signs, with SEP-53
      (ed25519 over sha256("Stellar Signed Message:\n" + message)), this text:

          PayFi request
          Line: beta
          Action: Renew the release of payout P-1017-121859-0c62
          POST /v1/lines/beta/payins/P-1017-121859-0c62/release/renew
          Body: <sha256 hex of the exact body bytes ("{}" is hashed too), or "-" for no body>
          Time: 2026-10-17T13:20:00Z
          Nonce: 9f2c4e1a7b3d5f60

      The path line carries the query as sent. `Action` is the SDK's `actionLabel(method,
      path, body)`; the service recomputes the whole text, so a signature over another action,
      body or path fails. A time more than 5 minutes off, a nonce used before, or a key not
      registered for the route's role on that line is refused.
    - `POST /v1/lines/{line}/read-grants` gives a signed caller a read grant for 15 minutes,
      sent as `Authorization: PayFi-Grant <grant>`. It reaches the `read` routes of that line,
      and names the caller on its `open` routes (a step asked for, which records nothing); it
      never changes state.
    - A payout is prepared with `POST …/payins` (`open`): the service screens the receiver,
      checks the terms and returns the advance as a step. Nothing is recorded and nothing is
      held against a limit. The pay-in exists once the PO's operations key signs the step and
      it is submitted; the service then screens again, checks the live limits and sends it.
      The step's approvals last about a minute (12 ledgers).
    - An action that needs a signature the service does not hold is a step. The first call
      checks, builds the batch and returns a `Step` with the preimage or transaction the
      other party signs; the service adds its own signature at submit. `POST /v1/lines/{line}/steps/{id}/submit` takes the signature.
      Steps are stored in SQLite, so a restart of the service loses none; a step whose
      approvals lapsed answers 410 `STEP_EXPIRED`.
  license:
    name: MIT
    identifier: MIT
servers:
  - url: https://payfi-beta.untangled.finance
    description: The testnet beta (also under /api); https://payfi-beta.untangledfinance.workers.dev serves the same API
tags:
  - name: lines
    description: The lines the service serves, and what each one looks like now
  - name: payins
    description: The PO's pay-ins and their advances, releases and repayments
  - name: cover
    description: The basket that covers the debt, and the PO's withdrawals of it
  - name: liquidations
    description: Liquidation by anyone, in one transaction through the line's gate-free adapter
  - name: takeovers
    description: The default take-over of a basket asset by Untangled's recovery account
  - name: steps
    description: Two-step actions waiting for a signature
  - name: operator
    description: Untangled's controls
  - name: events
    description: The pull feed of what changed on each line
security:
  - payfiSignature: []
paths:
  /v1/health:
    get:
      tags: [lines]
      operationId: health
      summary: Whether the service is up
      security: []
      responses:
        '200':
          description: The service answers
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Health' }
        '429': { $ref: '#/components/responses/RateLimited' }
  /v1/lines:
    get:
      tags: [lines]
      operationId: listLines
      summary: Every line the service serves, from the deployment registry
      security: []
      responses:
        '200':
          description: The lines
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LineList' }
        '429': { $ref: '#/components/responses/RateLimited' }
  /v1/lines/{line}/whoami:
    parameters:
      - $ref: '#/components/parameters/Line'
    get:
      tags: [lines]
      operationId: whoami
      x-payfi-auth: read
      security: [{ payfiSignature: [] }, { payfiGrant: [] }]
      summary: The role the signing key or the read grant holds on the line
      responses:
        '200':
          description: The role
          content:
            application/json:
              schema:
                type: object
                required: [line, role, key, request_id]
                properties:
                  line: { $ref: '#/components/schemas/LineId' }
                  role: { $ref: '#/components/schemas/Role' }
                  key: { type: string, description: "The key that signed, or the grant's key" }
                  request_id: { type: string }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/lines/{line}:
    parameters:
      - $ref: '#/components/parameters/Line'
    get:
      tags: [lines]
      operationId: getLine
      x-payfi-auth: none
      security: []
      summary: The line now, from the chain and the service's book
      description: Anyone. Receivers are masked and the blocked payees left out.
      responses:
        '200':
          description: The line
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LineView' }
        '404': { $ref: '#/components/responses/NotFound' }
        '503': { $ref: '#/components/responses/ChainUnavailable' }
  /v1/lines/{line}/read-grants:
    parameters:
      - $ref: '#/components/parameters/Line'
    post:
      tags: [lines]
      operationId: createReadGrant
      x-payfi-auth: signed
      security: [{ payfiSignature: [] }]
      summary: A read grant for 15 minutes
      description: |
        Signed by a PO key or the admin key; the action is "Read access for 15 minutes". The
        grant reaches this line's `read` routes for that key's role until it expires, and while
        the key stays registered. It can never change anything.
      responses:
        '201':
          description: The grant
          content:
            application/json:
              schema:
                type: object
                required: [grant, role, key, expires_at, request_id]
                properties:
                  grant: { type: string, description: 'Send as Authorization: PayFi-Grant <grant>' }
                  role: { $ref: '#/components/schemas/Role' }
                  key: { type: string }
                  expires_at: { type: string, format: date-time }
                  request_id: { type: string }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/lines/{line}/receivers:
    parameters:
      - $ref: '#/components/parameters/Line'
    get:
      tags: [payins]
      operationId: listReceivers
      x-payfi-auth: read
      security: [{ payfiSignature: [] }, { payfiGrant: [] }]
      summary: The line's receivers
      description: The receivers the line's operator lists (the testnet's prepared accounts) and every one the book was asked to pay.
      responses:
        '200':
          description: The receivers
          content:
            application/json:
              schema:
                type: object
                required: [items, request_id]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/Receiver' }
                  request_id: { type: string }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/lines/{line}/basket:
    parameters:
      - $ref: '#/components/parameters/Line'
    get:
      tags: [cover]
      operationId: getBasket
      x-payfi-auth: none
      security: []
      summary: The basket that covers the debt, its prices and the cover ratio
      description: Public and rate-limited. It shows what the chain already shows.
      responses:
        '200':
          description: The basket
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BasketView' }
        '404': { $ref: '#/components/responses/NotFound' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '503': { $ref: '#/components/responses/ChainUnavailable' }
  /v1/lines/{line}/payins:
    parameters:
      - $ref: '#/components/parameters/Line'
    get:
      tags: [payins]
      operationId: listPayins
      x-payfi-auth: read
      security: [{ payfiSignature: [] }, { payfiGrant: [] }]
      summary: The line's pay-ins, newest first
      parameters:
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
        - name: status
          in: query
          required: false
          description: Only pay-ins in this status
          schema: { $ref: '#/components/schemas/PayinStatus' }
      responses:
        '200':
          description: One page of pay-ins
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PayinPage' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
    post:
      tags: [payins]
      operationId: preparePayin
      x-payfi-auth: open
      security: [{}, { payfiSignature: [] }, { payfiGrant: [] }]
      summary: Prepare a payout, as the advance step for the PO to sign
      description: |
        Anyone may ask, and nothing is recorded: no pay-in, no decision, no event. The service screens
        the receiver, checks the face against the line's limits and returns the payout batch (mint the face
        in POT, post it, borrow the advance, pull the top-up) as a step of kind `advance`, with approvals
        valid for about a minute. The pay-in enters the book when the PO's operations key signs the step and
        it is submitted (`POST /steps/{id}/submit`): the limits are checked again then, in the line's queue,
        and the answer is the advance's, with the release. A step never signed is dropped once its approvals
        lapse, 5 minutes after it was made at the earliest. A caller without a key of the line is told only that
        a receiver cannot be paid; a PO or admin key (a signature or a read grant) is told why, and is served
        ahead of anonymous callers. A reference the book holds is refused, except a pay-in
        whose signed advance did not run, which may be prepared again with the same terms.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PayinInput' }
      responses:
        '201':
          description: The advance step to sign
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StepResult' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '503': { $ref: '#/components/responses/ChainUnavailable' }
  /v1/lines/{line}/payins/{reference}:
    parameters:
      - $ref: '#/components/parameters/Line'
      - $ref: '#/components/parameters/Reference'
    get:
      tags: [payins]
      operationId: getPayin
      x-payfi-auth: read
      security: [{ payfiSignature: [] }, { payfiGrant: [] }]
      summary: One pay-in, with its advance and its release
      responses:
        '200':
          description: The pay-in
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PayinResult' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/lines/{line}/payins/{reference}/release/step:
    parameters:
      - $ref: '#/components/parameters/Line'
      - $ref: '#/components/parameters/Reference'
    post:
      tags: [payins]
      operationId: releaseStep
      x-payfi-auth: open
      security: [{}, { payfiSignature: [] }, { payfiGrant: [] }]
      summary: The release as a transaction for the PO to sign
      description: |
        Anyone may ask, stating the release it expects: `receiver` and `amount` from its own record of the payout. The
        step names the receiver and carries the whole transaction, so the service answers only when both are the
        pay-in's; otherwise, and for a reference it does not hold, the same 404 with nothing in it. The release the service signed, built into a transaction whose source is
        the PO's operations key, with that account's sequence number now. The step has kind `release` and carries
        `transaction` instead of `preimage`: the PO signs the envelope and submits it on the step as `signed_transaction`.
        The service sends it and marks the pay-in paid. Another transaction from the PO's account in between makes the
        step stale (409): make it again. A release whose approvals ran out is renewed first.

        The step is built outside the line's queue, so it does not wait behind other payouts' advances. While this
        pay-in's own advance is still settling (being submitted, or sent and not yet seen on chain) the answer is a 409
        STATE_CONFLICT with `detail.settling: true`, `detail.retry_after_s` and a `Retry-After` header: ask again after
        that wait, unchanged; renewing does not help. A release that changed while the step was being built answers a
        409 with `detail.changed: true` and `Retry-After`: ask again too. Any other 409 here (no release out, or the
        approvals end too soon) means renew it (`POST …/release/renew`), then ask again. The SDK's `isSettling(err)`,
        `isAskAgain(err)` and `payins.releaseWhenReady()` tell these apart.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [receiver, amount]
              properties:
                receiver: { $ref: '#/components/schemas/Address' }
                amount: { $ref: '#/components/schemas/Amount' }
      responses:
        '201':
          description: The step to sign
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StepResult' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/ReleaseRefused' }
        '422': { $ref: '#/components/responses/RefusedByContracts' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '503': { $ref: '#/components/responses/ChainUnavailable' }
  /v1/lines/{line}/payins/{reference}/release:
    parameters:
      - $ref: '#/components/parameters/Line'
      - $ref: '#/components/parameters/Reference'
    post:
      tags: [payins]
      operationId: reportRelease
      x-payfi-auth: po
      security: [{ payfiSignature: [] }]
      summary: Report the release transaction the PO submitted
      description: Signed by a PO key. The service reads the transaction and marks the pay-in paid when it is exactly this advance's release.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TxReport' }
      responses:
        '200':
          description: Paid
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PayinResult' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
  /v1/lines/{line}/payins/{reference}/release/renew:
    parameters:
      - $ref: '#/components/parameters/Line'
      - $ref: '#/components/parameters/Reference'
    post:
      tags: [payins]
      operationId: renewRelease
      x-payfi-auth: po
      security: [{ payfiSignature: [] }]
      summary: Sign the release again once the last one's approvals ran out
      description: Signed by a PO key.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '200':
          description: A new release, or the pay-in already paid
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PayinResult' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
  /v1/lines/{line}/payins/{reference}/returned:
    parameters:
      - $ref: '#/components/parameters/Line'
      - $ref: '#/components/parameters/Reference'
    post:
      tags: [operator]
      operationId: markReturned
      x-payfi-auth: po
      security: [{ payfiSignature: [] }]
      summary: Report the owners' sweep that returned an unreleased advance to custody
      description: Signed by a PO key. The sweep moves the whole balance, so it returns every unreleased advance funded before it.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TxReport' }
      responses:
        '200':
          description: Returned
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PayinResult' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
  /v1/lines/{line}/payins/{reference}/resolve:
    parameters:
      - $ref: '#/components/parameters/Line'
      - $ref: '#/components/parameters/Reference'
    post:
      tags: [operator]
      operationId: resolvePayin
      x-payfi-auth: signed
      security: [{ payfiSignature: [] }]
      summary: An operator's answer for an advance or a release the service cannot settle on its own
      description: |
        Signed. For an advance whose outcome the network no longer shows (status `unknown`): `funded` with the
        advance's `tx_hash`, which the service checks on chain, by the PO's key or the admin's; `registered` (it
        never ran) frees the pay-in's reservation without proof, so only the line's admin key may say it.

        For a release whose release step landed but which the chain shows as something else (the service then signs
        nothing for the pay-in, alerts in its log at most once an hour, and asks the chain again with a back-off up
        to an hour), the line's admin key only: `paid` with the `tx_hash` that paid it, accepted when the chain shows
        that transaction as this release, or, when no node can show it, only for the landed step's own transaction;
        `not_paid` when the release never paid, accepted only when the chain answers FAILED for the landed step's own
        transaction and its TUSD events show no transfer of this release in it (SUCCESS, NOT_FOUND or an unreadable
        answer refuse it, with the reason): the step no longer counts as the payment, the advance counts as awaiting
        release again, and it can be renewed (the balance check counts every unreleased and in-flight advance) or
        returned. Each answer is recorded as a decision. The dispute is also posted as a `release_disputed` event.
        Resolve it within the RPC's retention window (120,960 ledgers, about 7 days, on the testnet RPC), counted
        from the step's ledger: past it the chain no longer shows the transaction or its events, so `not_paid` is
        refused for good. An advance of unknown outcome holds every release on the line (it is counted as in the
        settlement account) until it is resolved here; that is posted as a `release_blocked` event.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [outcome]
              properties:
                outcome:
                  type: string
                  enum: [registered, funded, paid, not_paid]
                  description: "registered: the advance never ran. funded: it ran in `tx_hash`. paid: the release paid in `tx_hash`. not_paid: the release never paid."
                tx_hash: { $ref: '#/components/schemas/TxHash' }
      responses:
        '200':
          description: Resolved
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PayinResult' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
  /v1/lines/{line}/screenings:
    parameters:
      - $ref: '#/components/parameters/Line'
    post:
      tags: [payins]
      operationId: screen
      x-payfi-auth: read
      security: [{ payfiSignature: [] }, { payfiGrant: [] }]
      summary: Screen a receiver, with the reasons
      description: |
        For the PO's or the admin's key, signed or with its read grant: the reasons name the deny list
        and the receiver's state. Nothing is stored but the decision. Anyone else learns only, from
        `POST /payins`, that a receiver cannot be paid.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [receiver]
              properties:
                receiver: { $ref: '#/components/schemas/AccountAddress' }
      responses:
        '200':
          description: The screening
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Screening' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/lines/{line}/repayments:
    parameters:
      - $ref: '#/components/parameters/Line'
    post:
      tags: [payins]
      operationId: reportRepayment
      x-payfi-auth: po
      security: [{ payfiSignature: [] }]
      summary: Report the repayment transaction the PO submitted for one pay-in
      description: |
        Signed by a PO key. The PO repays alone. One transaction can close several pay-ins; report it
        once per pay-in. The service closes a pay-in from the market's own numbers in the
        transaction.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [payin_reference, tx_hash]
              properties:
                payin_reference: { $ref: '#/components/schemas/Reference' }
                tx_hash: { $ref: '#/components/schemas/TxHash' }
      responses:
        '200':
          description: Closed
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PayinResult' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
  /v1/lines/{line}/repayments/step:
    parameters:
      - $ref: '#/components/parameters/Line'
    post:
      tags: [payins]
      operationId: repayStep
      x-payfi-auth: open
      security: [{}, { payfiSignature: [] }, { payfiGrant: [] }]
      summary: A full or partial repayment as a transaction for the PO to sign
      description: |
        Anyone may ask: the step needs the PO's signature. A caller that shows a key of the line (a signature, or the read grant the SDK sends when it has a signer) is
        served ahead of anonymous callers: it skips the anonymous rate limits and has steps kept for it. The step has kind `repay` and carries `transaction`: the PO signs the
        envelope (its operations key is the source) and submits it as `signed_transaction`. The summary names what it
        does: `pull`, `closes` (the advances it repays whole), `withdraw` (their POT, withdrawn and burned), `debt_after`
        and `partial`.

        Without `amount`, the whole debt: everything the settlement account owes, and the withdrawal and burn of all the
        POT posted, across every open advance. The market's figure depends on the second the ledger closes, so the batch
        carries one candidate amount a second and the transaction is bounded to the window they cover, which opens
        `delay_s` seconds from now. Refused when it could take more than `max`.

        With `amount`, exactly that, less than the debt. Each open advance owes its loan left plus a share of the
        interest in proportion; the amount repays the oldest advances whole while it covers them, and pays the rest
        towards the next one, which stays open with `repaid` and its remaining due shown. The settlement account's
        repay rule lets a repayment pay at most the POT it withdraws, and only a closed advance's POT is withdrawn: an
        amount that closes no advance, or pays more than the faces it closes, is refused (LIMIT_EXCEEDED) with the
        amounts that would pass.

        The service sends it (after the window opens) and closes each advance it repays whole (`closed`); the answer has
        `partial` and the `debt` left. With no debt left, the advances the last repayment covered are closed (409).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                amount:
                  $ref: '#/components/schemas/Amount'
                  description: A partial repayment of exactly this, in TUSD. Leave it out to repay the whole debt.
                max:
                  $ref: '#/components/schemas/Amount'
                  description: The most the PO pays, in TUSD; at least `amount` when both are given
                delay_s:
                  type: integer
                  minimum: 0
                  maximum: 120
                  default: 30
                  description: A full repayment's seconds until its window opens. 30 gives a person time to sign; an automated PO can use 0.
      responses:
        '201':
          description: The step to sign
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StepResult' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
        '422': { $ref: '#/components/responses/RefusedByContracts' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '503': { $ref: '#/components/responses/ChainUnavailable' }
  /v1/lines/{line}/market:
    parameters:
      - $ref: '#/components/parameters/Line'
    get:
      tags: [operator]
      operationId: getMarket
      x-payfi-auth: none
      security: []
      summary: The line's market as its admin sees it
      description: |
        Everything the line's market (OctoLend) holds, read from the chain: its admin and whether that account still
        holds the admin role, pause and delegation, the fee beneficiary, the collateral vault, the oracle and its
        price, a pending oracle update and its 48 hour timelock, the settings fixed at deployment, the totals and the
        accruals, and what each admin action can do now. The market exposes no role management, and its market and
        IRM configurations are set once only, so they are shown and never changed. Kept 4 seconds.
      responses:
        '200':
          description: The market
          content:
            application/json:
              schema:
                type: object
                required: [market, request_id]
                properties:
                  market: { $ref: '#/components/schemas/Market' }
                  request_id: { type: string }
        '404': { $ref: '#/components/responses/NotFound' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '503': { $ref: '#/components/responses/ChainUnavailable' }
  /v1/lines/{line}/market/step:
    parameters:
      - $ref: '#/components/parameters/Line'
    post:
      tags: [operator]
      operationId: marketStep
      x-payfi-auth: admin
      security: [{ payfiSignature: [] }]
      summary: A market admin change as a transaction for the market admin to sign
      description: |
        Signed by the operator's admin key. The service checks the action as the contract would (an oracle update
        pending and its timelock, pause state, a collateral vault before delegation, a new oracle that prices the
        collateral asset, a contract at a vault address, the admin still holding its role), builds the call from the
        market admin's account and simulates it. The step has kind `market` and carries `transaction`: the market
        admin signs the envelope (it is the source, and the call's `admin` argument) and submits it as
        `signed_transaction`. On the submit the action is checked again against the market as it is then, and sent.
        The summary names the `action`, its `address` or `enabled`, the `function` and a `title`, with a `warning`
        where the change needs one.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [action]
              properties:
                action: { $ref: '#/components/schemas/MarketAction' }
                address:
                  type: string
                  description: set_fee_beneficiary (G or C), propose_oracle and set_collateral_vault (C)
                enabled:
                  type: boolean
                  description: set_delegate_enabled
      responses:
        '201':
          description: The step to sign
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StepResult' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
        '422': { $ref: '#/components/responses/RefusedByContracts' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '503': { $ref: '#/components/responses/ChainUnavailable' }
  /v1/lines/{line}/withdrawals:
    parameters:
      - $ref: '#/components/parameters/Line'
    post:
      tags: [cover]
      operationId: withdrawCover
      x-payfi-auth: open
      security: [{}, { payfiSignature: [] }, { payfiGrant: [] }]
      summary: Move a basket asset from the settlement account to custody
      description: |
        Anyone may ask: the step needs the PO's signature. A caller that shows a key of the line (a signature, or the read grant the SDK sends when it has a signer) is
        served ahead of anonymous callers: it skips the anonymous rate limits and has steps kept for it. Step 1 of 2: the PO's operations key signs the returned preimage and submits
        it on the step. The withdrawal rule keeps the cover above its floor.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [asset, amount]
              properties:
                asset: { $ref: '#/components/schemas/AssetSymbol' }
                amount: { $ref: '#/components/schemas/Amount' }
      responses:
        '201':
          description: The step to sign
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StepResult' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
        '422': { $ref: '#/components/responses/Invalid' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '503': { $ref: '#/components/responses/ChainUnavailable' }
  /v1/lines/{line}/liquidations/quote:
    parameters:
      - $ref: '#/components/parameters/Line'
    post:
      tags: [liquidations]
      operationId: quoteLiquidation
      x-payfi-auth: none
      security: []
      summary: What a liquidation of one basket asset would repay and take now
      description: |
        Public and rate-limited. Nothing is signed or stored. The quote names the line's gate-free adapter and
        is made on the debt as the market reads it now, interest included, with `max_repay` `margin` below half
        of it. `asset_amount` is quoted `slippage_bps` (50) under the liquidation rule's edge, `fair_asset_amount`, so a
        price rise of up to about 0.5% before the transaction runs still passes. The SDK's
        `chain.liquidations.quote` gives the same figures from chain reads alone.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [asset]
              properties:
                asset: { $ref: '#/components/schemas/AssetSymbol' }
                repay: { $ref: '#/components/schemas/Amount' }
      responses:
        '200':
          description: The quote; `ok` false with reasons when no liquidation is possible
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Quote' }
        '404': { $ref: '#/components/responses/NotFound' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '422': { $ref: '#/components/responses/Invalid' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '503': { $ref: '#/components/responses/ChainUnavailable' }
  /v1/lines/{line}/liquidations:
    parameters:
      - $ref: '#/components/parameters/Line'
    post:
      tags: [liquidations]
      operationId: liquidate
      x-payfi-auth: none
      security: []
      summary: Liquidate an unhealthy position
      description: |
        Public and rate-limited. The step is a transaction step: `transaction` is the liquidator's own
        transaction, its source the liquidator, its one operation the gate-free adapter's `execute`
        with the five calls of a liquidation. The liquidator's TUSD transfer carries source-account
        credentials, and the settlement account's approval is vouched for by the gate-free adapter, so
        the service signs nothing. The liquidator checks it (the SDK's `checkStepTerms`), signs the
        envelope once and submits it on the step as `signed_transaction`; it pays its own fee. The
        SDK's `chain.liquidations.buildLiquidation` builds the same transaction from chain reads alone, for a
        liquidator that sends it without the service; the service records such a liquidation from the
        chain's events.

        A freeze does not stop a liquidation.
        A refusal (a healthy position, a price above the quote) is answered but neither kept
        as a decision nor under the Idempotency-Key, which is the caller's own: keys are
        scoped by the caller's address (an IPv6 /64). While four liquidations of the line
        are being prepared, another is answered 429 with Retry-After.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [asset, liquidator]
              properties:
                asset: { $ref: '#/components/schemas/AssetSymbol' }
                liquidator:
                  $ref: '#/components/schemas/AccountAddress'
                  description: The G account that pays the TUSD and receives the asset
                repay: { $ref: '#/components/schemas/Amount' }
                asset_amount:
                  $ref: '#/components/schemas/Amount'
                  description: At most the quote's `asset_amount`; less is allowed
      responses:
        '201':
          description: The step to sign
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StepResult' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '422': { $ref: '#/components/responses/Invalid' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '503': { $ref: '#/components/responses/ChainUnavailable' }
  /v1/lines/{line}/liquidations/scan:
    parameters:
      - $ref: '#/components/parameters/Line'
    post:
      tags: [operator]
      operationId: scanLiquidations
      x-payfi-auth: admin
      security: [{ payfiSignature: [] }]
      summary: Read a ledger range again for liquidations the book missed
      description: |
        Signed by the admin key. The backfill: the service reads the market's repay events for the settlement
        account in ledgers `from_ledger` to `to_ledger` (the last ledger the node has every event of when absent),
        reads each transaction whole and records each liquidation and each T1′ take-over run once (a run as a
        `takeover_run` event), as the scan does. Safe to repeat: a liquidation or run already in the book is left as it
        is, and the scan's own cursor does not move. One call reads at
        most 20,000 ledgers. A range older than the node keeps starts at its oldest ledger, and a
        `liquidation_scan_skipped` event names what was left out; a transaction the node cannot show is listed in
        `unreadable`. Use it after a `liquidation_scan_skipped` event, once the node shows the range.

        Each liquidation or run is allocated as of its own ledger: to the advances funded before it and still open
        now. When an advance open then has closed since, when no released advance was open then, or when it would
        close the last open advance while the market still holds debt, it is recorded with `allocated: false` and a
        `liquidation_unallocated` event (with `data.kind: takeover` for a run), and no advance changes. One from before
        the book's first scan is allocated only with `allocate_before_first_scan`. The call runs in the line's queue: advances and steps wait
        behind it while it reads.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [from_ledger]
              properties:
                from_ledger: { type: integer, minimum: 1 }
                to_ledger: { type: integer, minimum: 1 }
                allocate_before_first_scan:
                  type: boolean
                  description: Allocate liquidations from before the book's first scan too (to the advances open then and still open)
      responses:
        '200':
          description: What the backfill read and recorded
          content:
            application/json:
              schema:
                type: object
                required: [scan, request_id]
                properties:
                  scan: { $ref: '#/components/schemas/LiquidationScan' }
                  request_id: { type: string }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '422': { $ref: '#/components/responses/Invalid' }
        '503': { $ref: '#/components/responses/ChainUnavailable' }
  /v1/lines/{line}/takeovers:
    parameters:
      - $ref: '#/components/parameters/Line'
    get:
      tags: [takeovers]
      operationId: listTakeovers
      x-payfi-auth: read
      security: [{ payfiSignature: [] }, { payfiGrant: [] }]
      summary: The take-overs queued on the line, newest first
      parameters:
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: One page of take-overs
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TakeoverPage' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
    post:
      tags: [takeovers]
      operationId: queueTakeover
      x-payfi-auth: admin
      security: [{ payfiSignature: [] }]
      summary: Queue a default take-over of a basket asset
      description: |
        Signed by the admin key. Step 1 of 2: the Untangled admin signs the preimage. The batch is
        stored on the adapter for the wait, then the admin may run it.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [asset, repay]
              properties:
                asset: { $ref: '#/components/schemas/AssetSymbol' }
                repay:
                  $ref: '#/components/schemas/Amount'
                  description: The TUSD the recovery account pays in
                reason: { type: string, maxLength: 200 }
      responses:
        '201':
          description: The step to sign
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StepResult' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '422': { $ref: '#/components/responses/Invalid' }
  /v1/lines/{line}/takeovers/{number}:
    parameters:
      - $ref: '#/components/parameters/Line'
      - $ref: '#/components/parameters/TakeoverNumber'
    get:
      tags: [takeovers]
      operationId: getTakeover
      x-payfi-auth: read
      security: [{ payfiSignature: [] }, { payfiGrant: [] }]
      summary: One take-over
      responses:
        '200':
          description: The take-over
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TakeoverResult' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/lines/{line}/takeovers/{number}/run:
    parameters:
      - $ref: '#/components/parameters/Line'
      - $ref: '#/components/parameters/TakeoverNumber'
    post:
      tags: [takeovers]
      operationId: runTakeover
      x-payfi-auth: admin
      security: [{ payfiSignature: [] }]
      summary: Run a queued take-over once its wait is over
      description: Signed by the admin key. The recovery account signs through the service; nothing else to sign.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '200':
          description: Run
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TakeoverResult' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
        '422': { $ref: '#/components/responses/RefusedByContracts' }
        '502': { $ref: '#/components/responses/SubmitFailed' }
  /v1/lines/{line}/takeovers/{number}/cancel:
    parameters:
      - $ref: '#/components/parameters/Line'
      - $ref: '#/components/parameters/TakeoverNumber'
    post:
      tags: [takeovers]
      operationId: cancelTakeover
      x-payfi-auth: admin
      security: [{ payfiSignature: [] }]
      summary: The owners cancel a queued take-over
      description: Signed by the admin key. Step 1 of 2; the Untangled admin signs the preimage.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '201':
          description: The step to sign
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StepResult' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
  /v1/lines/{line}/takeovers/{number}/cancel-by-po:
    parameters:
      - $ref: '#/components/parameters/Line'
      - $ref: '#/components/parameters/TakeoverNumber'
    post:
      tags: [takeovers]
      operationId: cancelTakeoverByPo
      x-payfi-auth: none
      security: []
      summary: The PO cancels a queued take-over alone, once its debt is 0
      description: "No signature: the step needs the PO's. Step 1 of 2; the PO's operations key signs the preimage."
      responses:
        '201':
          description: The step to sign
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StepResult' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
  /v1/lines/{line}/steps/{id}:
    parameters:
      - $ref: '#/components/parameters/Line'
      - $ref: '#/components/parameters/StepId'
    get:
      tags: [steps]
      operationId: getStep
      x-payfi-auth: none
      security: []
      summary: A step and where it stands
      description: Anyone; the id is 128 random bits.
      responses:
        '200':
          description: The step
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StepResult' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/lines/{line}/steps/{id}/submit:
    parameters:
      - $ref: '#/components/parameters/Line'
      - $ref: '#/components/parameters/StepId'
    post:
      tags: [steps]
      operationId: submitStep
      x-payfi-auth: none
      security: []
      summary: Hand in the step signer's signature; the service submits
      description: |
        No signature on the request: the step signer's signature is the proof. A step with a `preimage` takes
        `signature`, verified against the signer and the preimage before anything is sent. A step with a
        `transaction` (release, repay and liquidation) takes `signed_transaction`: exactly that
        transaction, signed by the signer.
        An advance step answers with the advance (PayinResult fields); a release step with the paid pay-in; a repay
        step with `closed`, one entry per advance.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              minProperties: 1
              maxProperties: 1
              properties:
                signature:
                  type: string
                  pattern: '^[A-Za-z0-9+/]{86}==$'
                  description: Base64 of the 64-byte ed25519 signature over sha256 of the preimage XDR
                signed_transaction:
                  type: string
                  maxLength: 100000
                  description: The step's transaction signed by the step signer, base64 XDR envelope
      responses:
        '200':
          description: Submitted and confirmed
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StepResult' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Refused' }
        '410': { $ref: '#/components/responses/StepExpired' }
        '422': { $ref: '#/components/responses/RefusedByContracts' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/SubmitFailed' }
  /v1/lines/{line}/freeze:
    parameters:
      - $ref: '#/components/parameters/Line'
    get:
      tags: [operator]
      operationId: getFreeze
      x-payfi-auth: none
      security: []
      summary: Whether the line is frozen
      description: Anyone; the line summary shows the freeze too.
      responses:
        '200':
          description: The freeze
          content:
            application/json:
              schema: { $ref: '#/components/schemas/FreezeResult' }
        '404': { $ref: '#/components/responses/NotFound' }
    post:
      tags: [operator]
      operationId: freeze
      x-payfi-auth: admin
      security: [{ payfiSignature: [] }]
      summary: Freeze the line
      description: Signed by the admin key. A frozen line signs no new advance, release or withdrawal; a release signed before the freeze can still be sent. Liquidations, take-overs and repayments go on.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [reason]
              properties:
                reason: { type: string, minLength: 1, maxLength: 200 }
      responses:
        '200':
          description: Frozen
          content:
            application/json:
              schema: { $ref: '#/components/schemas/FreezeResult' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
    delete:
      tags: [operator]
      operationId: unfreeze
      x-payfi-auth: admin
      security: [{ payfiSignature: [] }]
      summary: Unfreeze the line
      description: Signed by the admin key.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '200':
          description: Unfrozen
          content:
            application/json:
              schema: { $ref: '#/components/schemas/FreezeResult' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/lines/{line}/limits:
    parameters:
      - $ref: '#/components/parameters/Line'
    post:
      tags: [operator]
      operationId: setLimits
      x-payfi-auth: admin
      security: [{ payfiSignature: [] }]
      summary: Set the line's overdue window and line cap
      description: Signed by the admin key. The overdue window is how far after its registration a pay-in's expected settlement may fall. It applies to pay-ins prepared from now on; an open advance keeps the settlement date it was advanced with, and an open advance past that date still stops new advances. The line cap is the service's own cap on the market debt after a draw, at most the cap the line's payout rule holds on chain. The change is recorded as a `limits` decision. GET /v1/lines/{line} shows the limits.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              minProperties: 1
              properties:
                overdue_window_seconds: { type: integer, minimum: 60, maximum: 2592000 }
                line_cap: { $ref: '#/components/schemas/Amount' }
      responses:
        '200':
          description: The limits after the change
          content:
            application/json:
              schema:
                type: object
                required: [limits, request_id]
                properties:
                  limits: { $ref: '#/components/schemas/Limits' }
                  request_id: { type: string }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/lines/{line}/decisions:
    parameters:
      - $ref: '#/components/parameters/Line'
    get:
      tags: [lines]
      operationId: listDecisions
      x-payfi-auth: read
      security: [{ payfiSignature: [] }, { payfiGrant: [] }]
      summary: Every decision the service made on the line, newest first
      parameters:
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
        - name: outcome
          in: query
          required: false
          schema: { $ref: '#/components/schemas/Outcome' }
      responses:
        '200':
          description: One page of decisions
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DecisionPage' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/lines/{line}/events:
    parameters:
      - $ref: '#/components/parameters/Line'
    get:
      tags: [events]
      operationId: listEvents
      x-payfi-auth: read
      security: [{ payfiSignature: [] }, { payfiGrant: [] }]
      summary: What changed on the line, oldest first after the cursor
      description: |
        A pull feed. Start without `cursor` to read from the beginning, then pass the last
        page's `next_cursor`. Each event is written in the same SQLite transaction as the change
        it reports, so the feed misses nothing the book holds. On the last page `next_cursor`
        is the cursor to poll with next, never null.
      parameters:
        - $ref: '#/components/parameters/Cursor'
        - name: types
          in: query
          required: false
          description: Comma-separated event types
          schema: { type: string, maxLength: 512 }
        - $ref: '#/components/parameters/Limit'
      responses:
        '200':
          description: One page of events
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EventPage' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthenticated' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
components:
  securitySchemes:
    payfiSignature:
      type: apiKey
      in: header
      name: PayFi-Signature
      description: |
        A signed request: PayFi-Key, PayFi-Signature, PayFi-Time and PayFi-Nonce, over the
        canonical text in the description above (SEP-53). The key must be registered on the
        line for the operation's `x-payfi-auth`.
    payfiGrant:
      type: apiKey
      in: header
      name: Authorization
      description: '`PayFi-Grant <grant>`, from POST /v1/lines/{line}/read-grants: the `read` routes of one line for 15 minutes'
  parameters:
    Line:
      name: line
      in: path
      required: true
      description: The line's id in the deployment registry
      schema: { $ref: '#/components/schemas/LineId' }
    Reference:
      name: reference
      in: path
      required: true
      schema: { $ref: '#/components/schemas/Reference' }
    TakeoverNumber:
      name: number
      in: path
      required: true
      description: The adapter's id of the stored batch
      schema: { type: integer, minimum: 0, maximum: 4294967295 }
    StepId:
      name: id
      in: path
      required: true
      schema: { type: string, pattern: '^[0-9a-f]{32}$' }
    Limit:
      name: limit
      in: query
      required: false
      schema: { type: integer, minimum: 1, maximum: 200, default: 50 }
    Cursor:
      name: cursor
      in: query
      required: false
      description: Opaque; the `next_cursor` of the previous page
      schema: { type: string, pattern: '^[A-Za-z0-9_-]{1,64}$' }
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: The same key with the same body within 24 hours returns the stored response
      schema: { type: string, pattern: '^[A-Za-z0-9:._-]{8,128}$' }
  headers:
    RetryAfter:
      description: Seconds until the client may try again
      schema: { type: integer, minimum: 1 }
  responses:
    BadRequest:
      description: The request is malformed (VALIDATION_FAILED, IDEMPOTENCY_KEY_MISSING, BAD_CURSOR), or a step's signature does not verify (SIGNATURE_INVALID)
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    Unauthenticated:
      description: No signature, or one that fails (SIGNATURE_REQUIRED, SIGNATURE_INVALID, SIGNATURE_EXPIRED, NONCE_REUSED)
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    Forbidden:
      description: The key is not registered on this line for this route (ROLE_NOT_ALLOWED)
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    NotFound:
      description: No such line, pay-in, take-over or step (LINE_NOT_FOUND, NOT_FOUND)
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    Refused:
      description: |
        The service's checks refused (REFUSED, FROZEN, LIMIT_EXCEEDED, SCREENING_FAILED,
        STATE_CONFLICT, IDEMPOTENCY_KEY_REUSED, IDEMPOTENCY_IN_PROGRESS). `reasons` says why.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    ReleaseRefused:
      description: |
        The release step cannot be built now (STATE_CONFLICT, or another code of `Refused`). With `detail.settling: true`
        the pay-in's advance is still settling on chain, and with `detail.changed: true` its release changed while the
        step was built: both carry `detail.retry_after_s` and `Retry-After`, and mean "ask again then, unchanged". Any
        other STATE_CONFLICT means the release lapsed or ends too soon: renew it, then ask again.
      headers:
        Retry-After: { $ref: '#/components/headers/RetryAfter' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    Invalid:
      description: The input is well-formed but not usable (UNKNOWN_ASSET, STALE_PRICE)
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    RefusedByContracts:
      description: The simulation on chain refused (REFUSED_BY_CONTRACTS); `detail.error` holds the contract error
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    StepExpired:
      description: The step's approvals lapsed; start again (STEP_EXPIRED)
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    SubmitFailed:
      description: The transaction was sent and failed or timed out (SUBMIT_FAILED); its hash is in `detail.tx`
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    ChainUnavailable:
      description: The RPC did not answer (CHAIN_UNAVAILABLE)
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    RateLimited:
      description: Too many requests from this address (RATE_LIMITED)
      headers:
        Retry-After: { $ref: '#/components/headers/RetryAfter' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
  schemas:
    Error:
      type: object
      required: [error, request_id]
      properties:
        error:
          type: object
          required: [code, message]
          properties:
            code: { $ref: '#/components/schemas/ErrorCode' }
            message: { type: string, description: One sentence a person can read }
            reasons:
              type: array
              items: { type: string }
              description: Every check that failed, when the service checked
            detail:
              type: object
              additionalProperties: true
            decision_id:
              type: integer
              description: The decision the refusal was recorded as
        request_id: { type: string }
    ErrorCode:
      type: string
      enum:
        - VALIDATION_FAILED
        - BAD_CURSOR
        - IDEMPOTENCY_KEY_MISSING
        - IDEMPOTENCY_KEY_REUSED
        - IDEMPOTENCY_IN_PROGRESS
        - SIGNATURE_REQUIRED
        - SIGNATURE_EXPIRED
        - NONCE_REUSED
        - ROLE_NOT_ALLOWED
        - LINE_NOT_FOUND
        - NOT_FOUND
        - UNKNOWN_ASSET
        - REFUSED
        - FROZEN
        - LIMIT_EXCEEDED
        - SCREENING_FAILED
        - STALE_PRICE
        - STATE_CONFLICT
        - REFUSED_BY_CONTRACTS
        - SIGNATURE_INVALID
        - STEP_EXPIRED
        - SUBMIT_FAILED
        - CHAIN_UNAVAILABLE
        - RATE_LIMITED
        - MAINNET_REFUSED
        - INTERNAL
    LineId:
      type: string
      pattern: '^[a-z0-9][a-z0-9-]{0,31}$'
      examples: [beta, line-2]
    Reference:
      type: string
      pattern: '^[A-Za-z0-9._-]{1,64}$'
    MarketAction:
      type: string
      enum: [set_fee_beneficiary, propose_oracle, execute_oracle_update, cancel_oracle_update, set_collateral_vault, set_delegate_enabled, pause, unpause]
    MarketActionState:
      type: object
      required: [available]
      properties:
        available: { type: boolean }
        why: { type: string, description: Why it cannot run now }
        note: { type: string, description: A caution that applies when it can }
    Market:
      type: object
      description: Rates and IRM fields are 18-decimal fixed point, written as decimals.
      required: [address, ledger, closed_at, admin, paused, delegate_enabled, loan_asset, collateral_asset, fee_beneficiary, collateral_vault, oracle, pending_oracle, oracle_timelock_s, fixed, totals, accrual, actions]
      properties:
        address: { type: string }
        ledger: { type: integer }
        closed_at: { type: integer }
        admin:
          type: object
          required: [address, holds_admin_role, role_holders]
          properties:
            address: { type: string }
            holds_admin_role: { type: boolean }
            role_holders: { type: integer }
        paused: { type: boolean }
        delegate_enabled: { type: boolean }
        loan_asset: { type: string }
        collateral_asset: { type: string }
        fee_beneficiary:
          oneOf:
            - type: object
              required: [address, shares]
              properties:
                address: { type: string }
                shares: { $ref: '#/components/schemas/Amount' }
            - type: 'null'
        collateral_vault:
          oneOf:
            - type: object
              required: [address]
              properties:
                address: { type: string }
                total_assets: { $ref: '#/components/schemas/Amount' }
                total_supply: { $ref: '#/components/schemas/Amount' }
                error: { type: string }
            - type: 'null'
        oracle:
          type: object
          required: [address, collateral_price]
          properties:
            address: { type: string }
            collateral_price:
              oneOf:
                - type: object
                  required: [price, decimals, timestamp]
                  properties:
                    price: { type: string }
                    decimals: { type: integer }
                    timestamp: { type: integer }
                - type: object
                  required: [error]
                  properties:
                    error: { type: string }
        pending_oracle:
          oneOf:
            - type: object
              required: [address, execute_after, executable_now]
              properties:
                address: { type: string }
                execute_after: { type: integer }
                executable_now: { type: boolean }
            - type: 'null'
        oracle_timelock_s: { type: integer }
        fixed:
          type: object
          required: [liquidation_threshold_bps, liquidation_bonus_bps, fee_bps, irm, base_rate_per_s]
          properties:
            liquidation_threshold_bps: { type: [integer, 'null'] }
            liquidation_bonus_bps: { type: integer }
            fee_bps: { type: integer }
            irm:
              oneOf:
                - type: object
                  required: [model]
                  properties:
                    model: { type: string, enum: [fixed, adaptive] }
                  additionalProperties: { type: string }
                - type: 'null'
            base_rate_per_s: { type: string }
        totals:
          type: object
          required: [lp_assets, lp_shares, total_debt, debt_shares, available_liquidity, collateral_held, utilization_bps, borrow_rate_yearly, debt_share_price]
          properties:
            lp_assets: { $ref: '#/components/schemas/Amount' }
            lp_shares: { $ref: '#/components/schemas/Amount' }
            total_debt: { $ref: '#/components/schemas/Amount' }
            debt_shares: { $ref: '#/components/schemas/Amount' }
            available_liquidity: { $ref: '#/components/schemas/Amount' }
            collateral_held: { $ref: '#/components/schemas/Amount' }
            utilization_bps: { type: integer }
            borrow_rate_yearly: { type: string }
            debt_share_price: { $ref: '#/components/schemas/Amount' }
        accrual:
          type: object
          required: [interest_at, fee_at, last_debt_assets, last_total_assets]
          properties:
            interest_at: { type: integer }
            fee_at: { type: integer }
            last_debt_assets: { $ref: '#/components/schemas/Amount' }
            last_total_assets: { $ref: '#/components/schemas/Amount' }
        actions:
          type: object
          required: [set_fee_beneficiary, propose_oracle, execute_oracle_update, cancel_oracle_update, set_collateral_vault, set_delegate_enabled, pause, unpause]
          additionalProperties: { $ref: '#/components/schemas/MarketActionState' }
    Amount:
      type: string
      pattern: '^[0-9]{1,15}(\.[0-9]{1,7})?$'
      description: Whole tokens with at most 7 decimals
      examples: ['1000', '0.5']
    SignedAmount:
      type: string
      pattern: '^-?[0-9]{1,15}(\.[0-9]{1,7})?$'
    TxHash:
      type: string
      pattern: '^[0-9a-f]{64}$'
    AccountAddress:
      type: string
      pattern: '^G[A-Z2-7]{55}$'
      description: A Stellar account (G) address
    Address:
      type: string
      pattern: '^[GC][A-Z2-7]{55}$'
      description: A Stellar account (G) or contract (C) address
    ContractAddress:
      type: string
      pattern: '^C[A-Z2-7]{55}$'
    AssetSymbol:
      type: string
      pattern: '^[A-Z0-9]{1,12}$'
      description: A basket asset of the line, as listed in its basket
      examples: [XLM, USDC]
    Network:
      type: string
      enum: [testnet, mainnet]
    Receiver:
      type: object
      required: [name, address, note, payouts, last_at]
      properties:
        name: { type: [string, 'null'] }
        address: { type: string }
        note: { type: [string, 'null'] }
        payouts: { type: integer, minimum: 0 }
        last_at: { type: [integer, 'null'], description: Unix seconds of the latest payout request }
    Role:
      type: string
      enum: [po, admin]
    PayinStatus:
      type: string
      enum: [registered, pending, unknown, funded, release_proposed, paid, returned, closed, cancelled]
      description: |
        registered: checked, nothing on chain. pending: the service signed an advance whose
        outcome is not known yet. unknown: the network no longer shows what became of a pending
        advance; an operator resolves it. funded: the advance landed and waits in the settlement
        account. release_proposed: a signed release is out. paid: the receiver has the money.
        returned: the owners swept the unreleased advance back to custody. closed: repaid.
        cancelled: withdrawn before any advance.
    Outcome:
      type: string
      enum: [approved, refused, refused by contracts, failed, expired]
    Health:
      type: object
      required: [ok, version, network, lines, request_id]
      properties:
        ok: { type: boolean }
        version: { type: string, description: The service's version }
        network: { $ref: '#/components/schemas/Network' }
        lines: { type: integer, description: How many lines the service serves }
        commit: { type: string, description: 'The git commit the process runs (12 hex, "+dirty" for local changes), so a process left on old code shows' }
        ledger: { type: integer, description: 'The latest ledger the RPC reports, when it answered' }
        ttl:
          description: "The Worker's keep-alive: the lowest time to live left among the ledger entries the lines rely on, from its last look (about daily). Null before its first look; absent from a service without one."
          oneOf:
            - type: 'null'
            - type: object
              required: [lowest, checkedAt, nextCheckAt, entries, missing, extended, ok]
              properties:
                lowest:
                  oneOf:
                    - type: 'null'
                    - type: object
                      required: [ledgers, days, what]
                      properties:
                        ledgers: { type: integer, description: Ledgers left now (about 5 s each), counted from the look }
                        days: { type: number }
                        what: { type: string, description: The entry with the least left }
                checkedAt: { type: string, format: date-time }
                nextCheckAt: { type: string, format: date-time }
                entries: { type: integer, description: Ledger keys looked at }
                missing: { type: integer, description: Keys with no entry on the ledger (not created yet or deleted) }
                extended: { type: integer, description: Entries the last look extended }
                ok: { type: boolean, description: 'The last look finished, every extension landed and nothing has run out' }
        request_id: { type: string }
    LineSummary:
      type: object
      required: [id, name, network, po, contracts, assets, basket, rules]
      properties:
        id: { $ref: '#/components/schemas/LineId' }
        name: { type: string }
        network: { $ref: '#/components/schemas/Network' }
        created_at: { type: string, format: date-time }
        po:
          type: object
          required: [admin, ops]
          description: The PO's keys; a wallet holding one of them is the PO on this line
          properties:
            admin: { $ref: '#/components/schemas/AccountAddress' }
            ops: { $ref: '#/components/schemas/AccountAddress' }
        operator:
          type: object
          description: Untangled's keys on the line; a wallet holding one is the operator
          properties:
            admin: { $ref: '#/components/schemas/AccountAddress' }
            signer: { $ref: '#/components/schemas/AccountAddress' }
            recovery: { $ref: '#/components/schemas/AccountAddress' }
        contracts:
          type: object
          required: [settlement, mint_account, market, pot, gate, adapter, interpreter]
          properties:
            settlement: { $ref: '#/components/schemas/ContractAddress' }
            mint_account: { $ref: '#/components/schemas/ContractAddress' }
            market: { $ref: '#/components/schemas/ContractAddress' }
            pot: { $ref: '#/components/schemas/ContractAddress' }
            tusd: { $ref: '#/components/schemas/ContractAddress' }
            gate: { $ref: '#/components/schemas/ContractAddress' }
            adapter: { $ref: '#/components/schemas/ContractAddress' }
            interpreter: { $ref: '#/components/schemas/ContractAddress' }
            oracle: { $ref: '#/components/schemas/ContractAddress' }
        custody: { $ref: '#/components/schemas/AccountAddress' }
        assets:
          type: object
          description: The borrow asset and the PO's token
          properties:
            borrow: { $ref: '#/components/schemas/TokenInfo' }
            pot: { $ref: '#/components/schemas/TokenInfo' }
        basket:
          type: array
          items: { $ref: '#/components/schemas/TokenInfo' }
        rules:
          type: object
          description: The rule ids installed on the line's accounts, by name
          additionalProperties:
            type: object
            additionalProperties: { type: integer }
        limits:
          type: object
          description: The line's static terms a client checks a step against
          required: [advance_bps]
          properties:
            advance_bps: { type: integer, description: 'The advance, in basis points of the face; the PO tops up the rest' }
        liquidation:
          $ref: '#/components/schemas/Liquidation'
        takeover:
          $ref: '#/components/schemas/TakeoverRules'
    TokenInfo:
      type: object
      required: [symbol, contract]
      properties:
        symbol: { $ref: '#/components/schemas/AssetSymbol' }
        contract: { $ref: '#/components/schemas/ContractAddress' }
        issuer: { $ref: '#/components/schemas/AccountAddress' }
        decimals: { type: integer, minimum: 0, maximum: 18 }
    LineList:
      type: object
      required: [lines, request_id]
      properties:
        lines:
          type: array
          items: { $ref: '#/components/schemas/LineSummary' }
        request_id: { type: string }
    Limits:
      type: object
      description: The line's service limits. Amounts in whole tokens.
      properties:
        per_draw_cap: { $ref: '#/components/schemas/Amount' }
        daily_limit: { $ref: '#/components/schemas/Amount' }
        line_cap: { $ref: '#/components/schemas/Amount' }
        working_float: { $ref: '#/components/schemas/Amount' }
        max_ltv_bps: { type: integer }
        settlement_dust: { $ref: '#/components/schemas/Amount' }
        allowance_floor: { $ref: '#/components/schemas/Amount' }
        overdue_window_seconds: { type: integer }
        corridors:
          type: object
          additionalProperties: { $ref: '#/components/schemas/Amount' }
        blocked_payees:
          type: array
          description: Left out here (this route is public, so the caller is always unsigned)
          items: { $ref: '#/components/schemas/Address' }
    LineView:
      type: object
      required: [line, ledger, debt, suspended, suspended_reasons, basket, freeze, request_id]
      properties:
        line: { $ref: '#/components/schemas/LineSummary' }
        ledger: { type: integer }
        debt: { $ref: '#/components/schemas/Amount' }
        posted: { $ref: '#/components/schemas/Amount', description: POT posted as collateral }
        ltv_bps: { type: integer }
        ltv_breach: { type: boolean }
        pot_price: { $ref: '#/components/schemas/Amount' }
        first_loss: { $ref: '#/components/schemas/SignedAmount' }
        custody_tusd: { $ref: '#/components/schemas/Amount' }
        allowance: { $ref: '#/components/schemas/Amount' }
        allowance_until_ledger: { type: [integer, 'null'] }
        allowance_low: { type: boolean }
        settlement_tusd: { $ref: '#/components/schemas/Amount' }
        settlement_pot: { $ref: '#/components/schemas/Amount' }
        settlement_held: { $ref: '#/components/schemas/Amount' }
        settlement_excess: { type: boolean }
        settlement_reasons: { type: array, items: { type: string } }
        unexpected_mints:
          type: array
          items:
            type: object
            required: [tx, amount, ledger, at]
            properties:
              tx: { $ref: '#/components/schemas/TxHash' }
              amount: { $ref: '#/components/schemas/Amount' }
              ledger: { type: integer }
              at: { type: integer }
        pending:
          type: array
          items:
            type: object
            properties:
              reference: { $ref: '#/components/schemas/Reference' }
              payout_tx: { type: [string, 'null'] }
              until_ledger: { type: [integer, 'null'] }
        open_advances:
          type: array
          items:
            type: object
            properties:
              reference: { $ref: '#/components/schemas/Reference' }
              face: { $ref: '#/components/schemas/Amount', description: 'The payout amount: the POT minted, the loan plus the top-up' }
              loan: { $ref: '#/components/schemas/Amount' }
              corridor: { type: string }
              expected_settlement_at: { type: integer }
              advance_tx: { type: [string, 'null'] }
              status: { $ref: '#/components/schemas/PayinStatus' }
              receiver: { type: string, description: Always masked here (this route is public) }
        unreleased:
          type: array
          items:
            type: object
            properties:
              reference: { $ref: '#/components/schemas/Reference' }
              receiver: { type: string }
              amount: { $ref: '#/components/schemas/Amount' }
              status: { $ref: '#/components/schemas/PayinStatus' }
              advance_tx: { type: [string, 'null'] }
              release_expires_ledger: { type: [integer, 'null'] }
        daily_used: { $ref: '#/components/schemas/Amount' }
        corridor_open:
          type: object
          additionalProperties: { $ref: '#/components/schemas/Amount' }
        overdue: { type: array, items: { $ref: '#/components/schemas/Reference' } }
        suspended: { type: boolean, description: True when the service signs no new advance }
        suspended_reasons: { type: array, items: { type: string } }
        basket: { $ref: '#/components/schemas/BasketView' }
        freeze: { $ref: '#/components/schemas/Freeze' }
        limits: { $ref: '#/components/schemas/Limits' }
        liquidations:
          type: array
          maxItems: 5
          description: >-
            The newest liquidations the book recorded, newest first: the service's own steps and the ones read from
            the chain's events (a liquidation sent straight to the chain shows here once read)
          items: { $ref: '#/components/schemas/LiquidationRecord' }
        request_id: { type: string }
    BasketView:
      type: object
      required: [assets, cover_value, cover_bps, required_bps, maintenance_bps, unhealthy, stale]
      properties:
        assets:
          type: array
          items:
            type: object
            required: [asset, balance, price_usd, price_age_s, max_age_s, haircut_bps]
            properties:
              asset: { $ref: '#/components/schemas/AssetSymbol' }
              contract: { $ref: '#/components/schemas/ContractAddress' }
              balance: { $ref: '#/components/schemas/Amount' }
              price_usd: { type: number }
              price_age_s: { type: integer }
              max_age_s: { type: integer }
              haircut_bps: { type: integer }
        debt: { $ref: '#/components/schemas/Amount' }
        cover_value: { $ref: '#/components/schemas/Amount' }
        cover_bps: { type: [integer, 'null'], description: Null when there is no debt }
        required_bps: { type: integer }
        maintenance_bps: { type: integer }
        max_borrow: { $ref: '#/components/schemas/Amount' }
        unhealthy: { type: boolean }
        stale:
          type: array
          items: { $ref: '#/components/schemas/AssetSymbol' }
          description: Assets whose price is older than its feed allows
        release_pending: { type: boolean }
        request_id: { type: string }
    PayinInput:
      type: object
      additionalProperties: false
      required: [reference, face, corridor, receiver, expected_settlement_at]
      properties:
        reference: { $ref: '#/components/schemas/Reference' }
        face: { $ref: '#/components/schemas/Amount' }
        corridor: { type: string, pattern: '^[A-Z]{2}-[A-Z]{2}$' }
        receiver: { $ref: '#/components/schemas/Address' }
        expected_settlement_at: { type: integer, description: Unix seconds }
    Release:
      type: object
      required: [xdr, amount, receiver, expires_ledger, expired]
      description: The release the PO signs as source and submits; it pays the receiver from the settlement account
      properties:
        xdr: { type: string, description: 'The co-signed invoke operation, base64 XDR' }
        amount: { $ref: '#/components/schemas/Amount' }
        receiver: { $ref: '#/components/schemas/Address' }
        expires_ledger: { type: integer }
        expired: { type: boolean }
    Payin:
      type: object
      required: [reference, status, face, corridor, receiver, created_at]
      properties:
        reference: { $ref: '#/components/schemas/Reference' }
        status: { $ref: '#/components/schemas/PayinStatus' }
        face: { $ref: '#/components/schemas/Amount' }
        corridor: { type: string }
        receiver: { type: string }
        borrow: { oneOf: [{ $ref: '#/components/schemas/Amount' }, { type: 'null' }] }
        top_up: { oneOf: [{ $ref: '#/components/schemas/Amount' }, { type: 'null' }] }
        repaid:
          description: What a partial repayment already paid towards this open advance's loan. Absent when nothing was.
          allOf: [{ $ref: '#/components/schemas/Amount' }]
        created_at: { type: integer }
        funded_at: { type: [integer, 'null'] }
        expected_settlement_at: { type: integer }
        closed_at: { type: [integer, 'null'] }
        advance_tx: { type: [string, 'null'] }
        advance_ledger: { type: [integer, 'null'] }
        release: { oneOf: [{ $ref: '#/components/schemas/Release' }, { type: 'null' }] }
        release_tx: { type: [string, 'null'] }
        release_ledger: { type: [integer, 'null'] }
        return_tx: { type: [string, 'null'] }
        repay_tx: { type: [string, 'null'] }
    PayinResult:
      type: object
      required: [payin, request_id]
      properties:
        payin: { $ref: '#/components/schemas/Payin' }
        decision: { $ref: '#/components/schemas/Decision' }
        ledger: { type: integer }
        request_id: { type: string }
    PayinPage:
      type: object
      required: [items, next_cursor, request_id]
      properties:
        items: { type: array, items: { $ref: '#/components/schemas/Payin' } }
        next_cursor: { type: [string, 'null'] }
        request_id: { type: string }
    TxReport:
      type: object
      additionalProperties: false
      required: [tx_hash]
      properties:
        tx_hash: { $ref: '#/components/schemas/TxHash' }
    Screening:
      type: object
      required: [receiver, ok, reasons, request_id]
      properties:
        receiver: { $ref: '#/components/schemas/Address' }
        ok: { type: boolean }
        reasons: { type: array, items: { type: string } }
        state: { type: object, additionalProperties: true }
        request_id: { type: string }
    Quote:
      type: object
      required: [asset, ok, reasons, max_repay, repay, asset_amount, cover_bps, request_id]
      properties:
        asset: { $ref: '#/components/schemas/AssetSymbol' }
        ok: { type: boolean }
        reasons: { type: array, items: { type: string } }
        max_repay: { $ref: '#/components/schemas/Amount' }
        repay: { $ref: '#/components/schemas/Amount' }
        asset_amount:
          $ref: '#/components/schemas/Amount'
          description: The most the fair price allows for `repay`; a liquidator may ask for less
        cover_bps: { type: [integer, 'null'] }
        adapter:
          $ref: '#/components/schemas/ContractAddress'
          description: The line's gate-free adapter, which the liquidator's transaction calls
        debt:
          $ref: '#/components/schemas/Amount'
          description: The line's debt as the market reads it now, interest included
        margin:
          $ref: '#/components/schemas/Amount'
          description: What the quote leaves below half the debt, about a minute of interest
        fair_asset_amount:
          $ref: '#/components/schemas/Amount'
          description: The liquidation rule's edge, the most of the asset R buys at 105%; `asset_amount` is `slippage_bps` under it
        slippage_bps:
          type: integer
          description: >-
            The quote's slippage: `asset_amount` is quoted this many basis points under the rule's 105% edge (50 by
            default), so a price rise up to about that much before the transaction runs still passes
        ledger: { type: integer }
        request_id: { type: string }
    StepQuote:
      type: object
      description: The quote a liquidation step was built on (a Quote's figures, with no request id of its own)
      required: [asset, ok, reasons, max_repay, repay, asset_amount, cover_bps]
      properties:
        asset: { $ref: '#/components/schemas/AssetSymbol' }
        ok: { type: boolean }
        reasons: { type: array, items: { type: string } }
        max_repay: { $ref: '#/components/schemas/Amount' }
        repay: { $ref: '#/components/schemas/Amount' }
        asset_amount: { $ref: '#/components/schemas/Amount' }
        cover_bps: { type: [integer, 'null'] }
        adapter: { $ref: '#/components/schemas/ContractAddress' }
        debt: { $ref: '#/components/schemas/Amount' }
        margin: { $ref: '#/components/schemas/Amount' }
        fair_asset_amount: { $ref: '#/components/schemas/Amount' }
        slippage_bps: { type: integer }
    Liquidation:
      type: object
      description: >-
        The line's liquidation through its gate-free execution adapter: anyone sends one transaction as its source, and
        no key of the service, the PO or Untangled signs it. `rules` are the rule ids the settlement account's tree
        names; `refused` the addresses the root rule refuses as the liquidator
      required: [adapter, rules, refused]
      properties:
        adapter: { $ref: '#/components/schemas/ContractAddress' }
        rules:
          type: object
          required: [liquidate, market, potcred, tusd, assets]
          properties:
            liquidate: { type: integer }
            market: { type: integer }
            potcred: { type: integer }
            tusd: { type: integer }
            assets: { type: object, additionalProperties: { type: integer }, description: The asset rule of each basket symbol }
        refused:
          type: array
          items: { type: string }
    TakeoverRules:
      type: object
      description: >-
        The line's default take-over rules: `queue` (takeover-t1, on the gated adapter, signed by the service and the
        Untangled admin) and `take` (take-t1, the take judged at run)
      required: [rules]
      properties:
        rules:
          type: object
          required: [queue, take]
          properties:
            queue: { type: integer }
            take: { type: integer }
    LiquidationRecord:
      type: object
      description: A liquidation the book recorded, from its own step or read from the chain's events
      required: [tx, ledger, at, asset, repay, asset_amount, liquidator]
      properties:
        tx: { $ref: '#/components/schemas/TxHash' }
        ledger: { type: [integer, 'null'] }
        at: { type: string, format: date-time }
        asset: { $ref: '#/components/schemas/AssetSymbol' }
        repay: { $ref: '#/components/schemas/Amount' }
        asset_amount: { $ref: '#/components/schemas/Amount' }
        liquidator: { $ref: '#/components/schemas/Address' }
        seen:
          type: string
          enum: [step, chain]
          description: '`step`: the service submitted it; `chain`: read from the chain after it landed'
        allocated:
          type: boolean
          description: >-
            Whether R was allocated to the advances open at its ledger; false when the book could not say which it paid
            (see the `liquidation_unallocated` event with the same tx)
    LiquidationScan:
      type: object
      required: [from_ledger, to_ledger, transactions, recorded, already, unreadable]
      properties:
        from_ledger: { type: integer }
        to_ledger: { type: integer }
        transactions: { type: integer, description: The settlement account's repay transactions in the range }
        recorded: { type: array, items: { $ref: '#/components/schemas/TxHash' }, description: Liquidations and T1′ take-over runs this call recorded }
        already: { type: array, items: { $ref: '#/components/schemas/TxHash' }, description: Liquidations and T1′ take-over runs already in the book }
        unreadable:
          type: array
          description: Repay transactions the node could not show
          items:
            type: object
            required: [tx, ledger, reason]
            properties:
              tx: { $ref: '#/components/schemas/TxHash' }
              ledger: { type: integer }
              reason: { type: string }
    StepKind:
      type: string
      enum: [withdraw, liquidate, takeover-queue, takeover-cancel, takeover-cancel-po, advance, release, repay, market]
    StepStatus:
      type: string
      enum: [awaiting_signature, submitted, confirmed, failed, expired]
    Step:
      type: object
      required: [id, kind, status, signer, preimage, transaction, operation, expires_ledger, summary, created_at]
      properties:
        id: { type: string }
        kind: { $ref: '#/components/schemas/StepKind' }
        status: { $ref: '#/components/schemas/StepStatus' }
        signer:
          $ref: '#/components/schemas/AccountAddress'
          description: The key that must sign the preimage, or the transaction as its source
        preimage:
          type: [string, 'null']
          description: The HashIdPreimage of the authorisation to sign, base64 XDR. Decode it and check it before signing. Null on a transaction step.
        transaction:
          type: [string, 'null']
          description: >-
            For a release, repay or liquidation step, the transaction envelope the
            signer signs as its source account, base64 XDR; null otherwise. Check its operation and source before
            signing.
        operation:
          type: string
          description: >-
            Base64 XDR of the operation the step submits, with every authorisation but the
            signer's. A client checks the preimage against it before signing: a delegated
            signer's approval must stand for the settlement account's batch in it, and a
            liquidator's must authorise exactly its call.
        expires_ledger: { type: integer }
        summary:
          type: object
          additionalProperties: true
          description: What the step does, in amounts and addresses the signer can check against the preimage
        created_at: { type: string, format: date-time }
        tx: { oneOf: [{ $ref: '#/components/schemas/TxHash' }, { type: 'null' }] }
        ledger: { type: [integer, 'null'] }
        error: { type: [string, 'null'] }
    StepResult:
      type: object
      required: [step, request_id]
      properties:
        step: { $ref: '#/components/schemas/Step' }
        quote: { $ref: '#/components/schemas/StepQuote' }
        takeover: { $ref: '#/components/schemas/Takeover' }
        payin: { $ref: '#/components/schemas/Payin' }
        decision: { $ref: '#/components/schemas/Decision' }
        release_problem: { type: string }
        closed:
          type: array
          description: A repay step's advances, each closed or refused
          items:
            type: object
            required: [reference, outcome, reasons]
            properties:
              reference: { type: string }
              outcome: { type: string, enum: [approved, refused] }
              reasons: { type: array, items: { type: string } }
        partial:
          type: object
          description: A partial repayment's advance it paid part of
          required: [reference, paid, remaining_due]
          properties:
            reference: { type: string }
            paid: { $ref: '#/components/schemas/Amount' }
            remaining_due: { $ref: '#/components/schemas/Amount' }
        debt:
          $ref: '#/components/schemas/Amount'
          description: A repayment's debt left on the market, once sent
        request_id: { type: string }
    Takeover:
      type: object
      required: [number, asset, repay, asset_amount, status]
      properties:
        number: { type: integer }
        asset: { $ref: '#/components/schemas/AssetSymbol' }
        repay: { $ref: '#/components/schemas/Amount' }
        asset_amount: { $ref: '#/components/schemas/Amount' }
        queued_ledger: { type: integer }
        runnable_ledger: { type: integer }
        window_ends_ledger: { type: integer }
        status: { type: string, enum: [queued, run, cancelled, lapsed] }
        tx: { type: [string, 'null'] }
        reason: { type: [string, 'null'] }
    TakeoverResult:
      type: object
      required: [takeover, request_id]
      properties:
        takeover: { $ref: '#/components/schemas/Takeover' }
        request_id: { type: string }
    TakeoverPage:
      type: object
      required: [items, next_cursor, request_id]
      properties:
        items: { type: array, items: { $ref: '#/components/schemas/Takeover' } }
        next_cursor: { type: [string, 'null'] }
        request_id: { type: string }
    Freeze:
      type: object
      required: [frozen]
      properties:
        frozen: { type: boolean }
        reason: { type: [string, 'null'] }
        since: { type: [string, 'null'], format: date-time }
    FreezeResult:
      type: object
      required: [freeze, request_id]
      properties:
        freeze: { $ref: '#/components/schemas/Freeze' }
        request_id: { type: string }
    Decision:
      type: object
      required: [id, at, kind, outcome, reasons]
      properties:
        id: { type: integer }
        at: { type: string, format: date-time }
        kind: { type: string, enum: [payin, payout, release, repayment, withdraw, liquidate, takeover, freeze, limits] }
        reference: { type: [string, 'null'] }
        outcome: { $ref: '#/components/schemas/Outcome' }
        reasons: { type: array, items: { type: string } }
        check_ms: { type: number }
        total_ms: { type: number }
        tx: { type: [string, 'null'] }
        ledger: { type: [integer, 'null'] }
        detail: { type: [object, 'null'], additionalProperties: true }
    DecisionPage:
      type: object
      required: [items, next_cursor, request_id]
      properties:
        items: { type: array, items: { $ref: '#/components/schemas/Decision' } }
        next_cursor: { type: [string, 'null'] }
        request_id: { type: string }
    EventType:
      type: string
      description: >-
        `takeover_run` is a T1′ take-over run, whoever sent it (`data.seen`: step or chain; `data.allocated`).
        `liquidation_unallocated` is a liquidation or a run the book could not allocate; a run's carries
        `data.kind: takeover`.
      enum:
        - payin_registered
        - payin_cancelled
        - advance_pending
        - advance_unknown
        - advance_expired
        - funded
        - release_proposed
        - paid
        - returned
        - repaid
        - repaid_part
        - overdue
        - frozen
        - unfrozen
        - withdrawn
        - liquidated
        - takeover_queued
        - takeover_run
        - takeover_cancelled
        - unexpected_mint
        - release_disputed
        - release_blocked
        - liquidation_scan_skipped
        - liquidation_unallocated
        - sim_action
    Event:
      type: object
      required: [id, type, at, line]
      properties:
        id: { type: string, description: Increasing within the line }
        type: { $ref: '#/components/schemas/EventType' }
        at: { type: string, format: date-time }
        line: { $ref: '#/components/schemas/LineId' }
        reference: { type: [string, 'null'], description: 'The pay-in, when the event is about one' }
        tx: { type: [string, 'null'] }
        ledger: { type: [integer, 'null'] }
        data: { type: object, additionalProperties: true }
    EventPage:
      type: object
      required: [items, next_cursor, request_id]
      properties:
        items: { type: array, items: { $ref: '#/components/schemas/Event' } }
        next_cursor: { type: string, description: 'Poll with this next, even when the page is empty' }
        request_id: { type: string }
