openapi: 3.1.0
info:
  title: FlowPayra Lite business API
  version: "1"
  license:
    name: MIT
    identifier: MIT
  description: |
    Server-to-server API for the merchant's business system: create payment orders and subscriptions, read them,
    list payees and plans, read the event feed, and maintain the risk address list. Payers pay on the hosted
    checkout (`checkout_url`); the system confirms payments on chain and reports them as webhooks (signed,
    retried) and through `GET /v1/events`. The integration guide is `docs/developers/integration.md`.

    Authentication: `Authorization: Bearer fpk_…` (an API key from the admin console or
    `flowpayra-lite apikey create`). A missing, malformed, unknown or revoked key answers `401 unauthorized`.
    Each key carries scopes: `orders:write`, `orders:read`, `subscriptions:write`, `subscriptions:read`,
    `events:read`, `risk:read`, `risk:write` (keys made before scopes existed carry `orders`, which grants every
    scope but the risk ones). A key created without naming its scopes gets all but `risk:read` and `risk:write`:
    the risk address list is installation-wide screening configuration, granted on request. Each operation
    names its scope in `security`; a key without it answers `403 insufficient_scope` (checked after the path
    and query parameters are parsed, before the request body and the `Idempotency-Key`).

    Live and test mode (Sandbox): every key belongs to a mode, visible in its prefix — `fpk_live_…` or
    `fpk_test_…` (keys made before modes, `fpk_…`, are live). A key creates and sees only its own mode's orders,
    subscriptions and events; another mode's object answers `404`. Test orders and subscriptions are paid on
    testnets only (Sepolia, Base Sepolia, …), live ones on mainnets only; local devnet chains serve both. Objects
    and events carry `livemode` (`false` in test mode), test events go to the test webhook endpoint signed with
    the test secret, and merchant order numbers are unique per mode. Plans and payees are shared by both modes.
    Amount limits apply to live orders only; test payers are screened against the local lists only (the
    merchant's list, OFAC, URL feeds and named lists; no third-party providers or sanctions oracles). The risk
    address list is shared by both modes: a test key reads all of it but writes only entries scoped to a testnet
    chain (`403 testnet_only`), and its replacements and removals touch only such entries.

    Writes that create (`POST /v1/orders`, `POST /v1/subscriptions`, `POST /v1/subscriptions/{id}/change_plan`,
    `POST /v1/risk/addresses`, `POST /v1/risk/addresses/import`) need an `Idempotency-Key` header (1-255
    characters; missing: `400 invalid_request`). Keys are scoped to the API key. The first answer (2xx or 4xx)
    is stored with a SHA-256 of the raw body: a retry with the same key and the same body bytes returns it again
    (same status and body); the same key with another body answers `422 idempotency_key_reused`, and a retry
    while the first request is still running `409 request_in_progress`. A server error (5xx) is not stored: retry
    with the same key. Stored keys do not expire. The other writes (`cancel`, `pause`, `resume`, `DELETE`) take
    no key.

    Errors: `{"error": {"code": "…", "message": "…", "params": {…}}}` with an HTTP status; `code` is stable,
    `params` (when present) carries the values behind the error — the `field` at fault, limits such as `min` /
    `max`, amounts and currencies — for wording it in your own language; `message` is English, for logs. Every
    operation may also answer `500 internal` (retry later), `408` (the request took over 30 seconds, empty body)
    and, for a path or method that does not exist, `404` / `405` with an empty body.

    Request bodies are JSON (sent with `Content-Type: application/json`), at most 64 KiB (`413
    payload_too_large`; the bulk import takes 4 MiB). Amounts are decimal strings, never JSON numbers. There is
    no rate limit on the business API.
servers:
  - url: https://pay.example.com
    description: Your deployment (`public_url`)
security:
  - apiKey: []
paths:
  /v1/orders:
    post:
      summary: Create an order
      description: |
        Creates an order priced in `currency` and payable with the tokens and chains in its options; the answer
        carries the `checkout_url` to send the payer to. Splits come from `splits`, else `split_rule_id`, else the
        default split rule (with neither and no default rule: `400 invalid_request`). Fixed split amounts are in
        their currency (the rule member's, or `currency` for `splits` given here) and are only paid in tokens
        pegged to that currency: other tokens are not offered. An order nobody could pay is refused (`422`).
        Idempotent (see the introduction). Requires `orders:write`.
      operationId: createOrder
      security:
        - apiKey: ["orders:write"]
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CreateOrder" }
            example:
              merchant_order_no: "SO-10023"
              amount: "100.00"
              currency: "USD"
              tokens: ["USDC", "USDT"]
              customer_email: "payer@example.com"
              return_url: "https://shop.example/orders/SO-10023/done"
              metadata: { description: "Annual plan × 1" }
      responses:
        "201":
          description: Created (or the replayed first answer)
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Order" }
        "400":
          description: |
            `invalid_request`: the body is not JSON, has an unknown field or a wrong type, or a field is invalid —
            `params.field` names it (`merchant_order_no` 1-128 characters; `amount` positive, at most 8 decimals
            and `max` 1000000000000; `currency` 1-16 characters; `prices.<symbol>` not a decimal, not positive or
            `token` not listed; `expires_in` `min` 60 – `max` 604800; `return_url` http(s), `max` 2048 characters;
            `customer_email`; `locale` with `allowed`). Without `params`: missing `Idempotency-Key`, both
            `split_rule_id` and `splits`, an unknown or inactive split payee, a split that is neither `{kind:
            ratio, bps}` nor `{kind: fixed, fixed_amount}`, an unknown `split_rule_id`, no default split rule.
            `invalid_splits`: the members do not form a rule (1-10 members, at least one `ratio` member, `bps`
            summing to 10000, no payee or address twice, no member receiving zero). Split addresses (see
            `SplitInput`): `split_address_not_allowed` (the split whitelist is on), `main_payee_first`,
            `main_payee_not_registered`, and `invalid_request` with `params.field` `splits[i].address`,
            `splits[i].name` or `splits[i]` (both a payee and an address).
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties:
                      error:
                        properties:
                          code:
                            enum:
                              - invalid_request
                              - invalid_splits
                              - split_address_not_allowed
                              - main_payee_first
                              - main_payee_not_registered
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/InsufficientScope" }
        "409":
          description: "`duplicate_order`: `merchant_order_no` exists in this mode already. `request_in_progress`."
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties: { error: { properties: { code: { enum: [duplicate_order, request_in_progress] } } } }
        "413": { $ref: "#/components/responses/PayloadTooLarge" }
        "422":
          description: |
            `split_total_too_small`: the amount does not cover the fixed splits (`params`: `amount`, `currency`,
            `fixed[{payee_id, amount, currency}]`). `split_currency_mismatch`: no accepted token is pegged to a fixed
            split's currency (`params`: `currency`, `fixed[]`). `no_payable_route`: no enabled network and token can
            settle the order otherwise (token filter, prices, payee addresses screened on the chain); when the payees'
            addresses are the reason, `params.reason` is `payee_address`, with `payees[{payee_id, name, problem}]`
            (`problem`: `missing` no address for the network's family, `unscreened` not screened there yet,
            `blocked` refused by screening) and the candidate `chains[{chain_id, name}]`.
            `amount_out_of_range`: a live order priced in the limits' currency outside the configured order limits
            (`params`: `limit` `min` | `max`, `bound`, `currency`, `amount`). `payee_blocked`: a split address failed
            screening on a chain that could pay (`params`: `field`, `address`, `chain_id`, `hits`);
            `no_payable_route` also when no enabled network of a split address's family can pay (`params`: `field`,
            `family`). `idempotency_key_reused`.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties:
                      error:
                        properties:
                          code:
                            enum:
                              - split_total_too_small
                              - split_currency_mismatch
                              - no_payable_route
                              - amount_out_of_range
                              - payee_blocked
                              - idempotency_key_reused
        "503": { $ref: "#/components/responses/ChainUnavailable" }
    get:
      summary: Find an order by your order number
      description: The key's mode's order with this `merchant_order_no` (exact match). Requires `orders:read`.
      operationId: findOrder
      security:
        - apiKey: ["orders:read"]
      parameters:
        - name: merchant_order_no
          in: query
          required: true
          schema: { type: string }
      responses:
        "200":
          description: The order
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Order" }
        "400": { $ref: "#/components/responses/InvalidRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/InsufficientScope" }
        "404": { $ref: "#/components/responses/NotFound" }
  /v1/orders/{id}:
    get:
      summary: Get an order
      description: |
        The order as it stands: the source of truth for fulfilment (webhooks and the return URL only announce
        changes). Requires `orders:read`.
      operationId: getOrder
      security:
        - apiKey: ["orders:read"]
      parameters:
        - $ref: "#/components/parameters/Id"
      responses:
        "200":
          description: The order
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Order" }
        "400": { $ref: "#/components/responses/InvalidRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/InsufficientScope" }
        "404": { $ref: "#/components/responses/NotFound" }
  /v1/payees:
    get:
      summary: List payees
      description: |
        Every payee registered in the admin console (active or not), oldest first, for `splits[].payee_ref` /
        `payee_id`. Recipients named by `address` (the split whitelist off) are not listed. Requires `orders:read`.
      operationId: listPayees
      security:
        - apiKey: ["orders:read"]
      responses:
        "200":
          description: Payees
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/Payee" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/InsufficientScope" }
  /v1/plans:
    get:
      summary: List active subscription plans
      description: |
        Plans are managed in the admin console and shared by both modes; pass one's `id` as `plan_id`. Retired
        plans are left out. Requires `subscriptions:read`.
      operationId: listPlans
      security:
        - apiKey: ["subscriptions:read"]
      responses:
        "200":
          description: Active plans
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/Plan" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/InsufficientScope" }
  /v1/subscriptions:
    post:
      summary: Create a subscription
      description: |
        Opens a subscription on a plan and returns its `checkout_url` (`/pay/sub/{id}`), where the payer picks token
        and network, agrees to the terms and authorizes an allowance capped at the plan's periods. The plan is
        snapshotted: later plan edits do not change it. The status starts `incomplete`; `subscription.activated`
        follows once the payer has subscribed on chain and it is confirmed. Splits come from `splits`, else
        `split_rule_id`, else the plan's default rule, else the default split rule. Idempotent (see the
        introduction). Requires `subscriptions:write`.
      operationId: createSubscription
      security:
        - apiKey: ["subscriptions:write"]
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CreateSubscription" }
            example:
              plan_id: "3d0f4a8e-2b6c-4f7e-9a51-0c8d2e6b1f47"
              customer_ref: "cus_1001"
              customer_email: "payer@example.com"
              return_url: "https://shop.example/account/billing"
      responses:
        "201":
          description: Created (or the replayed first answer)
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Subscription" }
        "400":
          description: |
            `invalid_request`: the body is not JSON or has an unknown field or a wrong type; an unknown or retired
            `plan_id`; `customer_ref` over 128 characters; `trial_seconds` outside the plan's trial (or non-zero on a
            plan without one); `return_url` not http(s) or over 2048 characters; `customer_email` not an address;
            `expires_in` outside 60 – 2592000; split errors as for orders; `locale` (`params`: `field`, `allowed`);
            missing `Idempotency-Key`. Only the `locale` and split address errors carry `params`. `invalid_splits` and
            the split address codes as for orders.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties:
                      error:
                        properties:
                          code:
                            enum:
                              - invalid_request
                              - invalid_splits
                              - split_address_not_allowed
                              - main_payee_first
                              - main_payee_not_registered
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/InsufficientScope" }
        "409": { $ref: "#/components/responses/RequestInProgress" }
        "413": { $ref: "#/components/responses/PayloadTooLarge" }
        "422":
          description: |
            `no_payable_route`: no enabled network with a Subscriptions contract and ERC-20 token can settle the plan
            with these splits (`params.reason` `payee_address` with `payees[]` and `chains[]` when the payees'
            addresses are why, as for orders). `payee_blocked`: a split address failed screening, as for orders.
            `idempotency_key_reused`.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties: { error: { properties: { code: { enum: [no_payable_route, payee_blocked, idempotency_key_reused] } } } }
        "503": { $ref: "#/components/responses/ChainUnavailable" }
  /v1/subscriptions/{id}:
    get:
      summary: Get a subscription
      description: Requires `subscriptions:read`.
      operationId: getSubscription
      security:
        - apiKey: ["subscriptions:read"]
      parameters:
        - $ref: "#/components/parameters/Id"
      responses:
        "200":
          description: The subscription
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Subscription" }
        "400": { $ref: "#/components/responses/InvalidRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/InsufficientScope" }
        "404": { $ref: "#/components/responses/NotFound" }
  /v1/subscriptions/{id}/cancel:
    post:
      summary: Cancel a subscription
      description: |
        Stops charging at once: `canceled` with `cancel_source: merchant` and `subscription.canceled` (none for an
        `incomplete` subscription, which never started); the system then cancels the on-chain subscription
        (`cancelByMerchant`), after which nobody can charge it. A pending plan change of the subscription ends with
        it (`subscription.plan_change_canceled`). Canceling a `canceled` or `completed` subscription changes
        nothing and answers `200` with it. No request body. Requires `subscriptions:write`.
      operationId: cancelSubscription
      security:
        - apiKey: ["subscriptions:write"]
      parameters:
        - $ref: "#/components/parameters/Id"
      responses:
        "200":
          description: The subscription
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Subscription" }
        "400": { $ref: "#/components/responses/InvalidRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/InsufficientScope" }
        "404": { $ref: "#/components/responses/NotFound" }
  /v1/subscriptions/{id}/pause:
    post:
      summary: Pause a subscription
      description: |
        No charges while paused; paused periods are not charged later (`subscription.paused` with
        `previous_status`). Any `trialing`, `active`, `past_due` or `unpaid` subscription can be paused. No request
        body. Requires `subscriptions:write`.
      operationId: pauseSubscription
      security:
        - apiKey: ["subscriptions:write"]
      parameters:
        - $ref: "#/components/parameters/Id"
      responses:
        "200":
          description: The subscription (`paused`)
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Subscription" }
        "400": { $ref: "#/components/responses/InvalidRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/InsufficientScope" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: "`not_pausable`: the subscription is `incomplete`, `paused`, `canceled` or `completed`."
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties: { error: { properties: { code: { enum: [not_pausable] } } } }
  /v1/subscriptions/{id}/resume:
    post:
      summary: Resume a paused subscription
      description: |
        Charging resumes from the next period start (`subscription.resumed`; `trialing` again when the trial has
        not ended and nothing was charged, else `active`). Arrears are not collected: the period running when it
        was paused and those while paused are never charged, and the dunning state (failures, retries,
        `past_due_since`) starts over. A subscription paused by risk screening (`subscription.risk_paused`) is
        resumed from the console only, after the payer is screened again. No request body. Requires
        `subscriptions:write`.
      operationId: resumeSubscription
      security:
        - apiKey: ["subscriptions:write"]
      parameters:
        - $ref: "#/components/parameters/Id"
      responses:
        "200":
          description: The subscription
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Subscription" }
        "400": { $ref: "#/components/responses/InvalidRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/InsufficientScope" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: "`risk_paused`: paused by risk screening (resume it from the console). `not_paused`: not `paused`."
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties: { error: { properties: { code: { enum: [risk_paused, not_paused] } } } }
  /v1/subscriptions/{id}/change_plan:
    post:
      summary: Change a subscription's plan (upgrade or downgrade)
      description: |
        "Cancel the old subscription, create a new one from the next period" (DESIGN.md §6.3.1): on-chain terms
        are immutable, so the payer authorizes the new plan at the returned subscription's `checkout_url`. Its
        first period starts at the old subscription's next period boundary at least 30 minutes ahead
        (`plan_change.effective_at`) and is not charged in the subscribe transaction; the old subscription keeps
        its current period, and nothing is prorated (bill a difference as a one-time order). From the request on,
        the old subscription charges no period from the boundary (`subscription.plan_change_pending` on it). The
        link expires at the latest 15 minutes before the boundary (`expires_in` is capped); unanswered, the change
        expires 10 minutes after the link (`subscription.plan_change_expired`, the new subscription `canceled` with
        `cancel_source: expired`) and the old subscription goes on unchanged. Once the new on-chain subscription is
        confirmed: `subscription.plan_changed` (instead of `subscription.activated`) for the new one, and the old
        one ends (`canceled`, `cancel_source: plan_changed`) as soon as its current period is charged or over, then is
        canceled on chain; its event is `subscription.replaced` (`replaced_by`, `effective_at`), not
        `subscription.canceled`, since the customer's service goes on with the new subscription. A new request supersedes a pending change
        whose payer has not subscribed yet (`subscription.plan_change_canceled`, `reason: superseded`); canceling
        either subscription withdraws it (`reason: subscription_ended` / `canceled`). Only `trialing` / `active`
        subscriptions confirmed on chain change plan (a trial is not granted again: the new plan starts where the
        trial ends). The new subscription carries over the customer, receipt email, locale, metadata and return
        URL (the request's override them); its splits are the request's, else the new plan's default rule, else
        the old subscription's. The payer confirms with the wallet paying the old subscription. Idempotent (see the
        introduction). Requires `subscriptions:write`.
      operationId: changeSubscriptionPlan
      security:
        - apiKey: ["subscriptions:write"]
      parameters:
        - $ref: "#/components/parameters/Id"
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ChangePlan" }
            example:
              plan_id: "8a1c2e40-7d3b-4b8f-a0e6-5f9d3c2b1a07"
      responses:
        "201":
          description: The new subscription (`incomplete`, `replaces` the old one) with `plan_change`
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Subscription" }
        "400":
          description: |
            `invalid_request`: the body is not JSON or has an unknown field or a wrong type; an unknown or retired
            `plan_id`; `expires_in` outside 60 – 2592000; `return_url`; `locale` (`params`: `field`, `allowed`);
            split errors as for orders; missing `Idempotency-Key`. `invalid_splits` and the split address codes as
            for orders.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties:
                      error:
                        properties:
                          code:
                            enum:
                              - invalid_request
                              - invalid_splits
                              - split_address_not_allowed
                              - main_payee_first
                              - main_payee_not_registered
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/InsufficientScope" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: |
            `same_plan`: the subscription is on this plan already. `not_changeable` (`params.status`): not `trialing`
            / `active`, not confirmed on chain yet, no period boundary left before it ends, or its schedule moved
            meanwhile (try again). `switch_in_flight`: a payment-method switch is being confirmed.
            `plan_change_in_flight`: the payer's subscribe of an earlier change is on its way. `request_in_progress`.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties:
                      error:
                        properties:
                          code: { enum: [same_plan, not_changeable, switch_in_flight, plan_change_in_flight, request_in_progress] }
        "413": { $ref: "#/components/responses/PayloadTooLarge" }
        "422":
          description: |
            `no_payable_route`: no enabled network with a Subscriptions contract and ERC-20 token can settle the new
            plan with these splits (`params.reason` `payee_address` with `payees[]` and `chains[]` when the payees'
            addresses are why, as for orders). `payee_blocked`: a split address failed screening, as for orders.
            `idempotency_key_reused`.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties: { error: { properties: { code: { enum: [no_payable_route, payee_blocked, idempotency_key_reused] } } } }
        "503": { $ref: "#/components/responses/ChainUnavailable" }
  /v1/events:
    get:
      summary: Read the event feed
      description: |
        Every webhook event of the key's mode in commit order, whether or not delivery succeeded: the pull
        alternative to webhooks. Pass the previous response's `next_since` to continue (positions are shared by both
        modes, so a mode's feed skips numbers). Positions never change, and no event is ever placed before a
        position already returned: an event is listed once every database transaction that could still commit an
        earlier one has ended (the feed may trail commits by the length of the longest running transaction; it
        never skips). Events are kept: `since=0` replays the whole history. Order events carry `customer_email`
        here as in webhooks. Requires `events:read`.
      operationId: listEvents
      security:
        - apiKey: ["events:read"]
      parameters:
        - name: since
          in: query
          description: Position after which to list (the previous page's `next_since`).
          schema: { type: integer, default: 0 }
        - name: limit
          in: query
          description: Events per page; values outside 1-500 are clamped.
          schema: { type: integer, minimum: 1, maximum: 500, default: 100 }
      responses:
        "200":
          description: Events after `since`, oldest first
          content:
            application/json:
              schema:
                type: object
                required: [data, next_since]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/Event" }
                  next_since:
                    type: integer
                    description: "Position of the last event returned (`since` when none): pass it as `since` next."
        "400": { $ref: "#/components/responses/InvalidRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/InsufficientScope" }
  /v1/risk/addresses:
    get:
      summary: List risk address entries
      description: |
        Entries of every source, newest first: the merchant's list (`manual`), the imported OFAC SDN addresses
        (`ofac`), URL feeds (`feed:<name>`) and named lists (`list:<name>`). Screening merges them: an `allow`
        from any source wins, then `block`, then `review`. Pass the previous page's `next_after` as `after` to
        continue. Test keys read the whole list (it is shared by both modes). Requires `risk:read`.
      operationId: listRiskAddresses
      security:
        - apiKey: ["risk:read"]
      parameters:
        - name: source
          in: query
          description: "Exact source: `manual`, `ofac`, `feed:<name>` or `list:<name>`."
          schema: { type: string }
        - name: address
          in: query
          description: "Entries of this address (any case; `400 invalid_request`, `params.field: address`, if not one)."
          schema: { type: string, pattern: "^0[xX][0-9a-fA-F]{40}$" }
        - name: level
          in: query
          schema: { type: string, enum: [block, review, allow] }
        - name: chain_id
          in: query
          description: Entries scoped to this chain (entries for all chains are left out).
          schema: { type: integer }
        - name: limit
          in: query
          description: Entries per page; values outside 1-500 are clamped.
          schema: { type: integer, minimum: 1, maximum: 500, default: 100 }
        - name: after
          in: query
          description: The `id` of the last entry of the previous page (`next_after`).
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: A page of entries
          content:
            application/json:
              schema:
                type: object
                required: [data, has_more, next_after]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/RiskEntry" }
                  has_more: { type: boolean }
                  next_after:
                    type: [string, "null"]
                    format: uuid
                    description: "`after` for the next page; null on the last one."
        "400": { $ref: "#/components/responses/InvalidRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/InsufficientScope" }
    post:
      summary: Add a risk address entry
      description: |
        Adds an entry to the merchant's list, or to the named list `list` (created on first use), and applies
        at once to quotes, sponsored submissions, bookings and subscription charges (when payer screening is
        on). An entry for the same address and chain scope in the same list is replaced. Audited as
        `api:<key name>`. A test key writes only entries whose `chain_id` is a testnet (`403 testnet_only`).
        Idempotent (see the introduction). Requires `risk:write`.
      operationId: addRiskAddress
      security:
        - apiKey: ["risk:write"]
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RiskEntryInput" }
            example:
              address: "0x098B716B8Aaf21512996dC57EB0615e2383E2f96"
              level: "block"
              category: "hack"
              reason: "Reported by the fraud team"
      responses:
        "201":
          description: The entry (or the replayed first answer)
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RiskEntry" }
        "400":
          description: |
            `invalid_request` with `params.field`: `address` (not an address of any family, or the zero address), `level`,
            `chain_id` (not a chain configured here), `reason` (over 200 characters), `expires_at` (not a date, or
            in the past), `list` (not `manual` or a list name). Without `params`: a body that is not JSON, has an
            unknown field or a wrong type; missing `Idempotency-Key`.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties: { error: { properties: { code: { enum: [invalid_request] } } } }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/RiskForbidden" }
        "409":
          description: "`list_is_feed`: `list` names a URL feed, whose entries come from its URL (`params.list`). `request_in_progress`."
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties: { error: { properties: { code: { enum: [list_is_feed, request_in_progress] } } } }
        "413": { $ref: "#/components/responses/PayloadTooLarge" }
        "422": { $ref: "#/components/responses/IdempotencyKeyReused" }
  /v1/risk/addresses/import:
    post:
      summary: Import risk address entries in bulk
      description: |
        Writes up to 10,000 entries in one transaction to the merchant's list or the named list `list` (created
        on first use): all valid or none (`400 invalid_entries` lists the faulty items by index). `append` adds
        the entries (replacing those already there for the same address and chain scope); `replace` makes the
        list hold exactly these entries, removing the others (a test key's replacement touches only entries on
        testnet chains). An address appearing twice for the same chain scope counts once (`duplicates`). The body
        may be up to 4 MiB. Audited as `api:<key name>`. Idempotent (see the introduction). Requires `risk:write`.
      operationId: importRiskAddresses
      security:
        - apiKey: ["risk:write"]
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RiskImportInput" }
            example:
              list: "crm"
              mode: "replace"
              default_level: "block"
              entries:
                - "0x098B716B8Aaf21512996dC57EB0615e2383E2f96"
                - { address: "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC", level: "review", category: "mixer", chain_id: [1, 8453] }
      responses:
        "200":
          description: What the import changed (or the replayed first answer)
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RiskImport" }
        "400":
          description: |
            `invalid_entries`: nothing was imported (`params`: `invalid`, `errors[{index, message}]` — the first 20,
            `index` 0-based). `invalid_request` with `params.field` for the other fields: `entries` (1-10,000 items,
            `min` / `max`), `mode`, `default_level`, `chain_id`, `list`; without `params` for a body that is not
            JSON, has an unknown field or a wrong type, and a missing `Idempotency-Key`.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties: { error: { properties: { code: { enum: [invalid_request, invalid_entries] } } } }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/RiskForbidden" }
        "409":
          description: "`list_is_feed` (`params.list`); `request_in_progress`."
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties: { error: { properties: { code: { enum: [list_is_feed, request_in_progress] } } } }
        "413": { $ref: "#/components/responses/PayloadTooLarge" }
        "422": { $ref: "#/components/responses/IdempotencyKeyReused" }
  /v1/risk/addresses/{address}:
    delete:
      summary: Remove a risk address
      description: |
        Removes the address's entries from the merchant's list (or the named list `list`): every chain scope, or
        the one `chain_id` names (`all`: the entry for all chains). Imported sources (OFAC, URL feeds) are not
        removable here: their next import refreshes them. A test key removes only entries on testnet chains (a
        `chain_id` other than a testnet answers `403 testnet_only`). Audited as `api:<key name>`. Requires
        `risk:write`.
      operationId: removeRiskAddress
      security:
        - apiKey: ["risk:write"]
      parameters:
        - name: address
          in: path
          required: true
          description: Any case.
          schema: { type: string, pattern: "^0[xX][0-9a-fA-F]{40}$" }
        - name: chain_id
          in: query
          description: A chain id, or `all` for the all-chain entry. Absent — every chain scope.
          schema: { type: string }
        - name: list
          in: query
          description: A named list instead of the merchant's list.
          schema: { type: string }
      responses:
        "200":
          description: The removed entries
          content:
            application/json:
              schema:
                type: object
                required: [deleted, data]
                properties:
                  deleted: { type: integer }
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/RiskEntry" }
        "400":
          description: "`invalid_request` with `params.field`: `address`, `chain_id` (not an id or `all`), `list`."
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties: { error: { properties: { code: { enum: [invalid_request] } } } }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/RiskForbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: |
            `entry_not_removable`: the address is listed only by imported sources (`params.sources`, e.g.
            `["ofac"]`). `list_is_feed` (`params.list`).
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Error"
                  - properties: { error: { properties: { code: { enum: [entry_not_removable, list_is_feed] } } } }
  /v1/openapi.yaml:
    get:
      summary: This description
      description: The OpenAPI document of the deployment's version, without authentication.
      operationId: getOpenApi
      security: []
      responses:
        "200":
          description: OpenAPI 3.1 (YAML)
          content:
            application/yaml:
              schema: { type: string }
webhooks:
  event:
    post:
      summary: Event delivery
      description: |
        POSTed to the endpoint configured in the admin console: live events to the live endpoint, test events
        (`livemode: false`) to the test endpoint, each signed with its own mode's secret (test order return URLs
        use the test secret too). Headers: `Content-Type: application/json`, `User-Agent: FlowPayra-Lite/<version>`
        and `FlowPay-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>` — verify it on the
        raw body bytes (the secret is the whole `whsec_…` string as UTF-8; accept any `v1` that matches) and reject
        stale timestamps (300 seconds is a good tolerance). The timestamp is the attempt's: a retry is signed anew.

        Answer 2xx within 10 seconds to acknowledge; anything else (redirects are not followed) is retried after 10 s,
        30 s, 1 min, 5 min, 15 min, 30 min, 1 h, 2 h, 4 h, 8 h and 8 h (12 attempts, about 24 hours), after which
        the event is marked failed (resendable from the console). Each mode is delivered strictly in order: a
        failing event holds the later ones of its mode back until it is delivered or given up. Every event stays
        readable through `GET /v1/events`, which also gives the commit order. The same event can arrive more than
        once (a lost acknowledgement, a resend): handle events idempotently by `id`, and read the object
        (`GET /v1/orders/{id}`) before acting on an older event.

        `data` is the object as it was when the event was written: an order (`order.*`), a subscription
        (`subscription.*`), a help ticket (`support.ticket_created`) or an alert (`system.*`). New event types may be
        added: acknowledge unknown types with 2xx.
      operationId: eventWebhook
      parameters:
        - name: FlowPay-Signature
          in: header
          required: true
          schema: { type: string, pattern: "^t=[0-9]+(,v1=[0-9a-f]{64})+$" }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/Event" }
      responses:
        "200": { description: Acknowledged (any 2xx) }
        default: { description: Not acknowledged; retried }
  alert:
    post:
      summary: Alert centre notification (webhook channel)
      description: |
        Sent by an alert-centre channel of kind `webhook` (admin console, 告警中心), separately from the business
        events above, to the channel's URL: one request per notification (an alert opening, resolving, or a
        one-off event) routed to the channel. Live alerts only (alerts about test data reach the test endpoint as
        `system.*` events, not alert channels). Headers as for business events, signed with the channel's own
        secret: `FlowPay-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(channel secret, "<t>.<raw body>")>`.
        Non-2xx answers (10-second timeout, no redirects) are retried on the business webhook schedule (about a
        day), then the delivery is marked failed and can be resent from the console. Deliveries are independent:
        no ordering. `id` identifies the delivery and stays the same across retries (deduplicate on it);
        `created_at` is the attempt's time, `data.at` the notification's.
      operationId: alertWebhook
      parameters:
        - name: FlowPay-Signature
          in: header
          required: true
          schema: { type: string, pattern: "^t=[0-9]+(,v1=[0-9a-f]{64})+$" }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AlertNotification" }
      responses:
        "200": { description: Acknowledged (any 2xx) }
        default: { description: Not acknowledged; retried }
components:
  securitySchemes:
    apiKey:
      type: http
      scheme: bearer
      description: |
        `fpk_live_…` or `fpk_test_…` API key (`fpk_…` keys from before modes are live). The names an operation
        lists in `security` are the scopes the key needs.
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: Any unique string per logical request (a UUID); see the introduction.
      schema: { type: string, minLength: 1, maxLength: 255 }
    Id:
      name: id
      in: path
      required: true
      description: "A UUID (`400 invalid_request`, `params.field: id`, otherwise)."
      schema: { type: string, format: uuid }
  responses:
    InvalidRequest:
      description: "`invalid_request`: a malformed path parameter (`params.field`) or query string, or an invalid filter value (`params.field`)."
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/Error"
              - properties: { error: { properties: { code: { enum: [invalid_request] } } } }
    Unauthorized:
      description: "`unauthorized`: no `Authorization: Bearer` header, or an unknown or revoked key."
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/Error"
              - properties: { error: { properties: { code: { enum: [unauthorized] } } } }
    InsufficientScope:
      description: "`insufficient_scope`: the key lacks the operation's scope."
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/Error"
              - properties: { error: { properties: { code: { enum: [insufficient_scope] } } } }
    RiskForbidden:
      description: |
        `insufficient_scope`; `testnet_only`: a test key writing an entry not scoped to a testnet chain
        (`params`: `chain_id`, `testnets`).
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/Error"
              - properties: { error: { properties: { code: { enum: [insufficient_scope, testnet_only] } } } }
    NotFound:
      description: "`not_found` (`params.what`: `order`, `subscription`, `entry`): unknown, or another mode's."
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/Error"
              - properties: { error: { properties: { code: { enum: [not_found] } } } }
    RequestInProgress:
      description: "`request_in_progress`: a request with this `Idempotency-Key` is still running."
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/Error"
              - properties: { error: { properties: { code: { enum: [request_in_progress] } } } }
    IdempotencyKeyReused:
      description: "`idempotency_key_reused`: the `Idempotency-Key` was used with another request body."
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/Error"
              - properties: { error: { properties: { code: { enum: [idempotency_key_reused] } } } }
    ChainUnavailable:
      description: |
        `chain_unavailable`: none of the networks that could pay a split address could be reached to screen it.
        Nothing is recorded (not replayed for the `Idempotency-Key`): retry later.
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/Error"
              - properties: { error: { properties: { code: { enum: [chain_unavailable] } } } }
    PayloadTooLarge:
      description: "`payload_too_large`: the body is over 64 KiB (the bulk import: 4 MiB)."
      content:
        application/json:
          schema:
            allOf:
              - $ref: "#/components/schemas/Error"
              - properties: { error: { properties: { code: { enum: [payload_too_large] } } } }
  schemas:
    Error:
      type: object
      required: [error]
      properties:
        error:
          type: object
          required: [code, message]
          properties:
            code: { type: string, examples: ["invalid_request", "unauthorized", "insufficient_scope", "not_found"] }
            message: { type: string, description: "English, for logs; may change." }
            params:
              type: object
              description: "Values for a localized message, e.g. `{\"field\": \"expires_in\", \"min\": 60, \"max\": 604800}`. Absent when the error has none."
              additionalProperties: true
    Decimal:
      type: string
      pattern: '^\d+(\.\d+)?$'
      description: Decimal amount as a string (no floats).
    BaseUnits:
      type: string
      pattern: '^\d+$'
      description: Token amount in base units (integer string; 1 USDC = "1000000").
    Address:
      type: string
      description: |
        An account address in its chain family's own form: EVM `0x` + 40 hex digits (orders, subscriptions and
        tickets give it in lowercase hex; the risk list EIP-55 checksummed), TRON Base58Check (`T…`, 34
        characters), Solana Base58 (32 bytes, 32-44 characters). Requests accept any of the three.
      anyOf:
        - { pattern: "^0x[0-9a-fA-F]{40}$" }
        - { pattern: "^T[1-9A-HJ-NP-Za-km-z]{33}$" }
        - { pattern: "^[1-9A-HJ-NP-Za-km-z]{32,44}$" }
    Hash:
      type: string
      pattern: "^0x[0-9a-f]{64}$"
      description: 32-byte hash of this system's own (order hash, on-chain subscription id), lowercase hex.
    TxId:
      type: string
      description: |
        A transaction id in its chain family's own form: EVM `0x` + 64 hex digits (lowercase), TRON 64 hex digits
        without `0x`, Solana a Base58 signature (64 bytes, 87-88 characters).
      anyOf:
        - { pattern: "^0x[0-9a-f]{64}$" }
        - { pattern: "^[0-9a-f]{64}$" }
        - { pattern: "^[1-9A-HJ-NP-Za-km-z]{86,88}$" }
    Family:
      type: string
      enum: [evm, tron, solana]
      description: "Chain family: decides the address and transaction id forms, and the wallets that can pay."
    ChainRef:
      type: object
      description: "The chain a record is on: its id (`chain_id` as well, unchanged), CAIP-2 identifier and family."
      required: [id, caip2, family]
      properties:
        id: { type: integer }
        caip2: { type: string, description: "`eip155:<id>`, `tron:0x2b6653dc`, `solana:<genesis hash prefix>`.", examples: ["eip155:8453"] }
        family: { $ref: "#/components/schemas/Family" }
    SplitInput:
      type: object
      additionalProperties: false
      required: [kind]
      description: |
        A split member: `{payee_ref | payee_id, kind: ratio, bps}` or `{payee_ref | payee_id, kind: fixed,
        fixed_amount}`, naming a payee registered in the console (the split whitelist).

        With the split whitelist switched off in the console, a member may name its recipient by `address` (with an
        optional `name`) instead of `payee_id` / `payee_ref`. The address is checked as at registration (checksum,
        not zero, not a system address: `400 invalid_request`, `params.field` `splits[i].address`) and screened on
        every enabled chain of its family that could pay (risk lists, sanctions, token blocklists, account type);
        a hit refuses the request (`422 payee_blocked`). The first member of a list with an address is the main
        payee (`payTo[0]`, which takes the remainder and bears refunds) and must be a ratio member
        (`400 main_payee_first`) naming a registered payee (`400 main_payee_not_registered`). The address appears in
        `splits[]` of the order or subscription as a payee whose `payee_ref` is `<family>:<address>` (e.g.
        `evm:0xab…`). With the whitelist on, `address` answers `400 split_address_not_allowed`.
      properties:
        payee_id: { type: string, format: uuid }
        payee_ref: { type: string, description: "The payee's reference (alternative to payee_id). The payee must be active." }
        address:
          type: string
          description: |
            The recipient's address (the split whitelist off), not with `payee_id` / `payee_ref`: EVM `0x` + 40 hex
            digits (EIP-55 checked when mixed case), TRON `T…` (Base58Check) or a Solana Base58 public key.
          examples: ["0x5B38Da6a701c568545dCfcB03FcB875f56beddC4"]
        name: { type: string, maxLength: 80, description: "With `address`: the recipient's name, shown in the console and statements (default: the address; a later name replaces it)." }
        kind: { type: string, enum: [ratio, fixed] }
        bps: { type: integer, minimum: 0, maximum: 10000, description: "For `ratio`: share of what the fixed members leave, in basis points; the ratio members sum to 10000." }
        fixed_amount:
          $ref: "#/components/schemas/Decimal"
          description: "For `fixed`: an amount in the order's `currency` (the plan's for subscriptions)."
    CreateOrder:
      type: object
      additionalProperties: false
      required: [merchant_order_no, amount, currency]
      properties:
        merchant_order_no: { type: string, minLength: 1, maxLength: 128, description: "Your order number (trimmed); unique per mode." }
        amount:
          $ref: "#/components/schemas/Decimal"
          description: Price in `currency`; positive, at most 8 decimals and 1000000000000.
        currency: { type: string, minLength: 1, maxLength: 16, description: "Pricing currency, any case (stored uppercase), e.g. USD; tokens pegged to it pay 1:1." }
        prices:
          type: object
          additionalProperties: { $ref: "#/components/schemas/Decimal" }
          description: |
            Per-token prices (the amount of that token to pay, at most 18 decimals) by token symbol, overriding the
            conversion of `amount`; tokens not named pay `amount` as usual (pegged tokens only). Symbols in any case
            (`USDE` prices `USDe`; stored in the listing's spelling). A symbol no listed token has is rejected
            (`400 invalid_request`, `params.field` `prices.<key>`, `params.token`).
          examples: [{ "USDC": "99.50" }]
        tokens: { type: array, items: { type: string }, description: "Accepted token symbols, any case (stored uppercase). Default: stablecoins, plus the token whose symbol is `currency`." }
        chains: { type: array, items: { type: integer, minimum: 0 }, description: "Accepted chain ids (default: every enabled chain serving the key's mode)." }
        customer_email: { type: string, format: email, maxLength: 254, description: "Receipt recipient; prefills the checkout (stored encrypted, sent in order events)." }
        split_rule_id: { type: string, format: uuid, description: "An active split rule (not with `splits`)." }
        splits: { type: array, minItems: 1, maxItems: 10, items: { $ref: "#/components/schemas/SplitInput" }, description: "Splits for this order (not with `split_rule_id`)." }
        return_url: { type: string, format: uri, maxLength: 2048, description: "http(s) URL the checkout sends the payer back to, with signed result parameters." }
        expires_in: { type: integer, minimum: 60, maximum: 604800, description: "Seconds until the order expires (default from the configuration, `order_ttl`)." }
        locale: { type: string, enum: [zh-CN, en], description: "Checkout and receipt language; any case (`EN` is stored as `en`). Others answer `400 invalid_request` with `params.allowed`." }
        metadata: { description: "Any JSON value (an object is recommended), returned as given in the order and its events." }
    Order:
      type: object
      description: |
        An order. `GET /v1/orders…` and `POST /v1/orders` add `checkout_url`; order events (`data` of `order.*`) add
        `payments` and `customer_email` instead, and `order.refunded` the `refund`.
      required: [id, livemode, merchant_order_no, order_hash, status, amount, currency, prices, tokens, chains,
        split_rule_id, payment, splits, risk_flag, locale, return_url, metadata, expires_at, created_at]
      properties:
        id: { type: string, format: uuid }
        livemode: { type: boolean, description: "`false` for a test order (created with a test key)." }
        merchant_order_no: { type: string, description: Unique per mode. }
        order_hash: { $ref: "#/components/schemas/Hash", description: "On-chain order id (bytes32)." }
        status:
          type: string
          enum: [pending, paid_unconfirmed, paid, expired, reverted, duplicate_paid, refunded, partially_refunded]
          description: |
            `pending` (awaiting payment) → `paid_unconfirmed` (a payment seen, not yet at its confirmations) →
            `paid` (`order.paid`). `expired`: unpaid at `expires_at` (`order.expired`; a late payment still books it).
            `duplicate_paid`: a second confirmed payment (`order.duplicate_paid`; a refund is opened for it).
            `reverted`: a confirmed payment left the chain (`order.payment_reverted`). `partially_refunded` /
            `refunded`: the booked payment partly, or every payment fully, refunded (`order.refunded`).
        amount: { $ref: "#/components/schemas/Decimal" }
        currency: { type: string }
        prices:
          type: [object, "null"]
          additionalProperties: { $ref: "#/components/schemas/Decimal" }
          description: The per-token prices given at creation, by listed symbol.
        tokens: { type: [array, "null"], items: { type: string }, description: "Accepted symbols as given (uppercase); null: the default." }
        chains: { type: [array, "null"], items: { type: integer } }
        split_rule_id: { type: [string, "null"], format: uuid, description: "The rule the splits were taken from; null for `splits` given with the order." }
        payment:
          type: [object, "null"]
          description: "The payment the order is booked on (the first confirmed one, which a later duplicate never displaces); null until one is seen."
          required: [chain_id, chain, token_id, symbol, decimals, amount, payer, tx_hash, paid_at, confirmed_at]
          properties:
            chain_id: { type: integer }
            chain: { $ref: "#/components/schemas/ChainRef" }
            token_id: { type: [string, "null"], format: uuid, description: "The listed token (see the console's tokens)." }
            symbol: { type: [string, "null"], description: "The token's symbol as listed (e.g. USDC); null if the token was removed since." }
            decimals: { type: [integer, "null"], description: "The token's decimals: `amount` / 10^decimals is the amount in tokens." }
            amount: { type: [string, "null"], pattern: '^\d+$', description: "Token base units." }
            payer: { oneOf: [{ $ref: "#/components/schemas/Address" }, { type: "null" }] }
            tx_hash: { oneOf: [{ $ref: "#/components/schemas/TxId" }, { type: "null" }] }
            paid_at: { type: [string, "null"], format: date-time, description: When the payment was first seen. }
            confirmed_at: { type: [string, "null"], format: date-time, description: When it reached its confirmations. }
        splits:
          type: array
          items:
            type: object
            required: [position, payee_id, payee_ref, kind, bps, fixed_amount, fixed_currency, address, amount]
            properties:
              position: { type: integer, description: "The member's place in the rule or `splits`. On chain the main payee (first ratio member, who takes the rounding remainder) is paid first." }
              payee_id: { type: string, format: uuid }
              payee_ref: { type: string }
              kind: { type: string, enum: [ratio, fixed] }
              bps: { type: [integer, "null"] }
              fixed_amount: { type: [string, "null"], description: "Fixed members: the amount in `fixed_currency`." }
              fixed_currency: { type: [string, "null"], description: "Currency of `fixed_amount` (fixed members)." }
              address: { oneOf: [{ $ref: "#/components/schemas/Address" }, { type: "null" }], description: "Payee address on the paid chain, once paid." }
              amount: { type: [string, "null"], pattern: '^\d+$', description: "Token base units the member received, once paid." }
        risk_flag:
          type: [string, "null"]
          enum: [frozen, review, hit_after_paid, null]
          description: "Set when a payer was listed at booking. `frozen`: a payment came from a blocked address; it is frozen and does not count toward the order (see `order.payment_frozen`). `review`: a review-level entry or over the payer's daily limit; hold fulfilment for review. `hit_after_paid`: orders booked before frozen payments existed (they stay paid)."
        locale: { type: [string, "null"], enum: [zh-CN, en, null] }
        return_url: { type: [string, "null"] }
        metadata: { description: "As given at creation (null when none)." }
        expires_at: { type: string, format: date-time }
        created_at: { type: string, format: date-time }
        checkout_url: { type: string, format: uri, description: "API answers only: the hosted checkout for the payer (`<public_url>/pay/{id}`)." }
        payments:
          type: array
          description: "Order events only: every payment seen (removed ones left out), the booked one first."
          items:
            type: object
            required: [chain_id, chain, tx_hash, block_number, payer, amount, status]
            properties:
              chain_id: { type: integer }
              chain: { $ref: "#/components/schemas/ChainRef" }
              tx_hash: { $ref: "#/components/schemas/TxId" }
              block_number: { type: integer }
              payer: { $ref: "#/components/schemas/Address" }
              amount: { $ref: "#/components/schemas/BaseUnits" }
              status: { type: string, enum: [unconfirmed, confirmed] }
              frozen: { type: boolean, description: "The payer had a block verdict at booking: the payment does not count toward the order and cannot be refunded." }
        customer_email: { type: [string, "null"], description: "Order events only: the receipt address, when one was given." }
        frozen_payment:
          type: object
          description: "`order.payment_frozen` only: the payment just frozen."
          required: [id, chain_id, chain, tx_hash, log_index, block_number, payer, token, amount, frozen_at]
          properties:
            id: { type: string, format: uuid }
            chain_id: { type: integer }
            chain: { $ref: "#/components/schemas/ChainRef" }
            tx_hash: { $ref: "#/components/schemas/TxId" }
            log_index: { type: integer }
            block_number: { type: integer }
            payer: { $ref: "#/components/schemas/Address" }
            token: { $ref: "#/components/schemas/Address" }
            amount: { $ref: "#/components/schemas/BaseUnits" }
            frozen_at: { type: string, format: date-time }
        refund:
          type: object
          description: "`order.refunded` only: the refund just booked."
          required: [id, payment_id, chain_id, chain, token, amount, to, from, tx_hash, reason, method, verification]
          properties:
            id: { type: string, format: uuid }
            payment_id: { type: [string, "null"], format: uuid }
            chain_id: { type: [integer, "null"] }
            chain: { oneOf: [{ $ref: "#/components/schemas/ChainRef" }, { type: "null" }] }
            token: { oneOf: [{ $ref: "#/components/schemas/Address" }, { type: "null" }], description: "Token contract (or mint); the zero address for the chain's native coin." }
            amount: { $ref: "#/components/schemas/BaseUnits" }
            to: { oneOf: [{ $ref: "#/components/schemas/Address" }, { type: "null" }], description: The payer refunded. }
            from: { oneOf: [{ $ref: "#/components/schemas/Address" }, { type: "null" }], description: "The payee address it was sent from." }
            tx_hash: { oneOf: [{ $ref: "#/components/schemas/TxId" }, { type: "null" }] }
            reason: { type: [string, "null"] }
            method: { type: [string, "null"], enum: [wallet, offline, null], description: "`wallet`: sent from the console's wallet connection; `offline`: a transaction id entered." }
            verification:
              type: [string, "null"]
              enum: [transfer, trace, manual, null]
              description: "`transfer` (a token or coin transfer), `trace` (found in the call trace, e.g. sent by a Safe) or `manual` (confirmed by an operator)."
    Payee:
      type: object
      required: [id, ref, name, is_primary, active]
      properties:
        id: { type: string, format: uuid }
        ref: { type: string, description: "Your reference, for `splits[].payee_ref`." }
        name: { type: string }
        is_primary: { type: boolean, description: The primary payee (takes the remainder and sends refunds). }
        active: { type: boolean, description: Only active payees can be split to. }
    Plan:
      type: object
      required: [id, name, description, pricing_mode, amount, currency, prices, accepted_tokens, period_seconds,
        max_periods, start_mode, trial_seconds, require_balance_on_trial, grace_seconds, retry_schedule, on_unpaid,
        default_split_rule_id, payer_can_pause, active, created_at]
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        description: { type: [string, "null"] }
        pricing_mode: { type: string, enum: [unified, per_token] }
        amount:
          type: [string, "null"]
          pattern: '^\d+(\.\d+)?$'
          description: "Per-period price in `currency` (unified pricing; pegged stablecoins pay it 1:1)."
        currency: { type: [string, "null"] }
        prices:
          type: array
          description: "Per-token prices (per_token pricing); `chain_id` null applies to every chain."
          items:
            type: object
            required: [token_symbol, chain_id, amount]
            properties:
              token_symbol: { type: string }
              chain_id: { type: [integer, "null"] }
              amount: { $ref: "#/components/schemas/Decimal" }
        accepted_tokens: { type: [array, "null"], items: { type: string }, description: "null: every token that settles the price." }
        period_seconds: { type: integer }
        max_periods: { type: integer }
        start_mode: { type: string, enum: [immediate, trial], description: "`immediate`: the first period is charged when the payer subscribes." }
        trial_seconds: { type: integer }
        require_balance_on_trial: { type: boolean, description: "Trials check that the payer holds one period's amount." }
        grace_seconds: { type: integer, description: "How long a failed charge is retried before `on_unpaid` applies." }
        retry_schedule: { type: array, items: { type: integer }, description: Seconds after each failed charge. }
        on_unpaid: { type: string, enum: [unpaid, cancel], description: "What the grace period's end does: `unpaid` (kept, no more charges) or `canceled`." }
        default_split_rule_id: { type: [string, "null"], format: uuid }
        payer_can_pause: { type: boolean, description: "Payers may pause from \"my subscriptions\"." }
        active: { type: boolean }
        created_at: { type: string, format: date-time }
    CreateSubscription:
      type: object
      additionalProperties: false
      required: [plan_id]
      properties:
        plan_id: { type: string, format: uuid, description: An active plan. }
        customer_ref: { type: string, maxLength: 128, description: "Your customer identifier (trimmed)." }
        customer_email:
          type: string
          format: email
          description: "For receipts (activation, charges, failures, trial end, end) and the \"my subscriptions\" sign-in by email."
        trial_seconds: { type: integer, minimum: 0, description: "A shorter trial than the plan's (trial plans only; `0` on other plans)." }
        split_rule_id: { type: string, format: uuid }
        splits: { type: array, minItems: 1, maxItems: 10, items: { $ref: "#/components/schemas/SplitInput" } }
        tokens: { type: array, items: { type: string }, description: "Accepted token symbols (default: the plan's). Stored uppercase." }
        chains: { type: array, items: { type: integer, minimum: 0 } }
        return_url: { type: string, format: uri, maxLength: 2048, description: "Where the checkout sends the payer once subscribed (unsigned `subscription_id` and `status` appended)." }
        locale: { type: string, enum: [zh-CN, en], description: "Checkout and receipt language, any case (as for orders)." }
        metadata: { description: "Any JSON value, returned in the subscription and its events." }
        expires_in: { type: integer, minimum: 60, maximum: 2592000, default: 604800, description: Seconds the checkout link stays usable. }
    ChangePlan:
      type: object
      additionalProperties: false
      required: [plan_id]
      properties:
        plan_id: { type: string, format: uuid, description: An active plan other than the current one. }
        split_rule_id: { type: string, format: uuid }
        splits: { type: array, minItems: 1, maxItems: 10, items: { $ref: "#/components/schemas/SplitInput" } }
        tokens: { type: array, items: { type: string }, description: "Accepted token symbols (default: the new plan's)." }
        chains: { type: array, items: { type: integer, minimum: 0 } }
        return_url: { type: string, format: uri, maxLength: 2048, description: "Default: the old subscription's." }
        locale: { type: string, enum: [zh-CN, en], description: "Default: the old subscription's." }
        metadata: { description: "Default: the old subscription's." }
        expires_in: { type: integer, minimum: 60, maximum: 2592000, default: 604800, description: "Seconds the link stays usable; never past 15 minutes before `effective_at`." }
    PlanChange:
      type: object
      required: [id, subscription_id, new_subscription_id, plan_id, plan_name, status, effective_at, expires_at, source,
        reason, created_at, ended_at]
      properties:
        id: { type: string, format: uuid }
        subscription_id: { type: string, format: uuid, description: The subscription being replaced. }
        new_subscription_id: { type: string, format: uuid }
        plan_id: { type: string, format: uuid }
        plan_name: { type: string }
        status: { type: string, enum: [pending, applied, expired, canceled] }
        effective_at: { type: string, format: date-time, description: "The new subscription's first period starts (the old one's next period boundary)." }
        expires_at: { type: [string, "null"], format: date-time, description: The new subscription's link stays usable until then. }
        source: { type: string, enum: [api, console] }
        reason: { type: [string, "null"], enum: [superseded, canceled, subscription_ended, null], description: "Why it was canceled: a newer change, the new subscription canceled, the old one ended." }
        created_at: { type: string, format: date-time }
        ended_at: { type: [string, "null"], format: date-time }
        checkout_url: { type: string, format: uri, description: "Only in `pending_plan_change` of `GET /v1/subscriptions/{id}`: where the payer confirms (the new subscription's link)." }
    Subscription:
      type: object
      description: |
        A subscription. API answers add `checkout_url` (and the `change_plan` answer `plan_change`); subscription
        events (`data` of `subscription.*`) add the fields their type describes (see the properties marked
        "Events:").
      required: [id, livemode, plan_id, plan_name, customer_ref, status, chain_id, chain, token, payer, sub_id,
        amount_per_period, period_seconds, max_periods, trial_seconds, start_at, trial_end_at, next_charge_at,
        charges_made, last_charged_index, past_due_since, last_error, cancel_source, splits, locale, return_url,
        metadata, created_at, canceled_at, replaces, replaced_by, pending_plan_change]
      properties:
        id: { type: string, format: uuid }
        livemode: { type: boolean, description: "`false` for a test subscription (created with a test key)." }
        plan_id: { type: string, format: uuid }
        plan_name: { type: string }
        customer_ref: { type: [string, "null"] }
        status:
          type: string
          enum: [incomplete, trialing, active, past_due, unpaid, paused, canceled, completed]
          description: |
            `incomplete` (link sent, nothing on chain) → `trialing` | `active` once the on-chain subscription is
            confirmed → `past_due` after a failed charge (retried) → `unpaid` or `canceled` when the grace period runs
            out; `paused`; `canceled`; `completed` after the last period.
        checkout_url: { type: string, format: uri, description: "API answers only: the subscription link (`<public_url>/pay/sub/{id}`)." }
        chain_id: { type: [integer, "null"], description: "The network paid on (null while `incomplete`)." }
        chain: { oneOf: [{ $ref: "#/components/schemas/ChainRef" }, { type: "null" }], description: "The network paid on, with its CAIP-2 id and family (null while `incomplete`)." }
        token: { type: [string, "null"], description: Token symbol. }
        payer: { oneOf: [{ $ref: "#/components/schemas/Address" }, { type: "null" }] }
        sub_id: { oneOf: [{ $ref: "#/components/schemas/Hash" }, { type: "null" }], description: "On-chain subscription id (the signed terms digest)." }
        amount_per_period: { type: [string, "null"], pattern: '^\d+$', description: Token base units. }
        period_seconds: { type: integer }
        max_periods: { type: integer }
        trial_seconds: { type: integer }
        start_at: { type: [string, "null"], format: date-time, description: "Start of period 0 (after the trial)." }
        trial_end_at: { type: [string, "null"], format: date-time }
        next_charge_at: { type: [string, "null"], format: date-time }
        charges_made: { type: integer }
        last_charged_index: { type: [integer, "null"], description: "0-based index of the last period charged." }
        past_due_since: { type: [string, "null"], format: date-time }
        last_error: { type: [string, "null"], description: "Of the last failed charge: `balance`, `allowance`, or the revert reason." }
        cancel_source:
          type: [string, "null"]
          enum: [payer, merchant, chain, unpaid, plan_changed, expired, null]
          description: |
            `payer` ("my subscriptions", an on-chain cancel by the payer, or a revoked allowance), `merchant` (this API
            or the console), `chain` (canceled on chain by someone else), `unpaid` (the grace period ran out on a
            `cancel` plan), `plan_changed` (the old subscription of an applied plan change), `expired` (the new
            subscription of a change the payer did not confirm in time).
        splits:
          type: array
          description: "Resolved on the paid chain once the payer subscribes (empty while `incomplete`)."
          items:
            type: object
            required: [position, payee_id, payee_ref, address, kind, bps, amount_per_period]
            properties:
              position: { type: integer }
              payee_id: { type: string, format: uuid }
              payee_ref: { type: string }
              address: { $ref: "#/components/schemas/Address" }
              kind: { type: string, enum: [ratio, fixed] }
              bps: { type: [integer, "null"] }
              amount_per_period: { $ref: "#/components/schemas/BaseUnits" }
        locale: { type: [string, "null"] }
        return_url: { type: [string, "null"] }
        metadata: { description: "As given (null when none)." }
        created_at: { type: string, format: date-time }
        canceled_at: { type: [string, "null"], format: date-time }
        replaces: { type: [string, "null"], format: uuid, description: "The subscription this one replaces (a plan change's new subscription)." }
        replaced_by: { type: [string, "null"], format: uuid, description: "The subscription an applied plan change moved this one to (event `subscription.replaced`)." }
        pending_plan_change:
          description: "The plan change waiting for the payer (on the old subscription); null when none. `checkout_url` in API answers only."
          oneOf:
            - $ref: "#/components/schemas/PlanChange"
            - type: "null"
        plan_change:
          $ref: "#/components/schemas/PlanChange"
          description: "The `change_plan` answer, and events `subscription.plan_change_pending` / `_expired` / `_canceled` (on the old subscription): the change."
        charge:
          type: object
          description: |
            Events: `subscription.charged` and `subscription.charged_after_cancel` — `{id, period_index, amount,
            tx_hash}`; `subscription.charge_failed`, `subscription.unpaid` and a `subscription.canceled` caused by
            the grace period — `{id, period_index, error}`.
          required: [id, period_index]
          properties:
            id: { type: string, format: uuid }
            period_index: { type: integer }
            amount: { $ref: "#/components/schemas/BaseUnits" }
            tx_hash: { $ref: "#/components/schemas/TxId", description: "In the subscription's chain family's form (`data.chain`)." }
            error: { type: string, description: "`balance`, `allowance`, or the revert reason." }
        retry_at: { type: [string, "null"], format: date-time, description: "Events with a failed `charge`: the next attempt (null: none)." }
        previous_status: { type: string, description: "Event `subscription.paused`: the status before." }
        previous:
          type: object
          description: |
            Events: `subscription.plan_changed` — the replaced subscription `{id, plan_id, plan_name}`;
            `subscription.payment_method_changed` — the previous method `{chain_id, token, payer}`.
          properties:
            id: { type: string, format: uuid }
            plan_id: { type: string, format: uuid }
            plan_name: { type: string }
            chain_id: { type: [integer, "null"] }
            token: { type: [string, "null"] }
            payer: { oneOf: [{ $ref: "#/components/schemas/Address" }, { type: "null" }] }
        switch:
          type: object
          description: "Event `subscription.payment_method_changed`: the new method (`token` and `chain_id` are also the subscription's own)."
          required: [chain_id, payer]
          properties:
            chain_id: { type: integer }
            payer: { $ref: "#/components/schemas/Address" }
        migration:
          type: object
          description: |
            Event `subscription.migration_requested`: the merchant replaced its quote signer key and asks the payer to
            move the subscription to the new payment contract through "my subscriptions" (charges continue on the
            old contract until then; tell the customer).
          required: [reason, action]
          properties:
            reason: { type: string, enum: [signer_rotated, signer_compromised] }
            action: { type: string, enum: [switch_payment_method] }
        effective_at: { type: string, format: date-time, description: "Events `subscription.plan_changed` and `subscription.replaced`: the boundary the new plan starts at." }
        reason:
          type: string
          enum: [subscription_ended]
          description: |
            Event `subscription.canceled`: `subscription_ended` (a plan change's new subscription whose old one ended
            first, with `before_activation`).
        before_activation:
          type: boolean
          description: "Event `subscription.canceled`: the subscription was canceled before its on-chain subscription was confirmed (it never got `subscription.activated`)."
        canceled_by: { $ref: "#/components/schemas/Address", description: "Event `subscription.canceled` after an on-chain cancel: who sent it." }
        allowance: { $ref: "#/components/schemas/BaseUnits", description: "Event `subscription.allowance_low`: what the allowance leaves after the pending charge." }
        needed: { $ref: "#/components/schemas/BaseUnits", description: "Event `subscription.allowance_low`: what the remaining periods need." }
    RiskEntry:
      type: object
      required: [id, address, chain_id, source, category, level, reason, expires_at, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        address: { $ref: "#/components/schemas/Address", description: "In the entry's chain family's form (EVM: EIP-55 checksummed; an all-chain entry by its length: 20 bytes EIP-55, 32 bytes Base58)." }
        chain_id: { type: [integer, "null"], description: "The chain it applies to; null for all chains." }
        source:
          type: string
          description: "`manual` (the merchant's list), `ofac`, `feed:<name>` (a URL feed), `list:<name>` (a named list)."
          examples: ["manual", "ofac", "feed:partner", "list:crm"]
        category: { type: [string, "null"], enum: [sanctions, scam, hack, mixer, false_positive, other, null] }
        level:
          type: string
          enum: [block, review, allow]
          description: "`block` refuses the quote; `review` lets the payment through and flags the order; `allow` overrides every other source."
        reason: { type: [string, "null"], description: "Internal note (at most 200 characters); never shown to payers." }
        expires_at: { type: [string, "null"], format: date-time }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
    RiskEntryInput:
      type: object
      additionalProperties: false
      required: [address]
      properties:
        address: { type: string, pattern: "^0[xX][0-9a-fA-F]{40}$", description: "Any case; not the zero address." }
        level: { type: string, enum: [block, review, allow], default: block, description: Any case. }
        category:
          type: string
          description: |
            `sanctions`, `scam`, `hack`, `mixer`, `false_positive` or `other`; other names are mapped to the closest
            (`fraud` → `scam`, `Tornado mixer` → `mixer`, …) or `other`.
        chain_id: { type: integer, description: "A chain configured in the console; absent: all chains (a test key must name a testnet)." }
        reason: { type: string, maxLength: 200 }
        expires_at: { type: string, description: "RFC 3339 or `YYYY-MM-DD`, in the future." }
        list:
          type: string
          pattern: "^[a-z0-9][a-z0-9_-]{0,39}$"
          description: "A named list (`list:<name>`, created on first use) instead of the merchant's list (`manual` or absent); not `ofac`, not a URL feed."
    RiskImportInput:
      type: object
      additionalProperties: false
      required: [entries]
      properties:
        entries:
          type: array
          minItems: 1
          maxItems: 10000
          description: |
            Address strings, or objects with `address` and optional `level`, `category`, `chain_id` (an id, a list
            of ids — one entry each — or `all`), `reason` (or `labels`, joined) and `expires_at`. Field aliases are
            accepted (`wallet`, `action`, `type`, `chain`/`chains`, `note`/`description`, `expires`/`expiry`);
            other fields are ignored.
          items:
            oneOf:
              - { type: string }
              - type: object
                required: [address]
                properties:
                  address: { type: string }
                  level: { type: string, enum: [block, review, allow] }
                  category: { type: string }
                  chain_id:
                    oneOf:
                      - { type: integer }
                      - { type: array, items: { type: integer } }
                      - { type: string }
                  reason: { type: string }
                  labels: { type: array, items: { type: string } }
                  expires_at: { type: string }
        list: { type: string, description: "A named list; default the merchant's list." }
        mode: { type: string, enum: [append, replace], default: append }
        default_level: { type: string, enum: [block, review, allow], default: block }
        default_category: { type: string }
        chain_id: { type: integer, description: "Chain of the entries that name none; default all chains." }
    RiskImport:
      type: object
      required: [list, source, mode, total, added, removed, duplicates]
      properties:
        list: { type: string, description: "`manual` or the named list." }
        source: { type: string, examples: ["manual", "list:crm"] }
        mode: { type: string, enum: [append, replace] }
        total: { type: integer, description: "Entries written (duplicates once)." }
        added: { type: integer, description: "Entries new to the list." }
        removed: { type: integer, description: "Entries a replacement removed." }
        duplicates: { type: integer, description: "Items repeating an earlier address and chain scope." }
    AlertNotification:
      type: object
      required: [id, type, created_at, data]
      properties:
        id: { type: string, format: uuid, description: "The delivery (the same across retries)." }
        type: { type: string, enum: [alert.open, alert.resolved, alert.event] }
        created_at: { type: string, format: date-time, description: The attempt's time. }
        data:
          type: object
          required: [alert_id, kind, title, status, subject, details, at, console_url]
          properties:
            alert_id: { type: string, format: uuid }
            kind: { type: string, examples: ["rpc_down", "payer_risk_blocked", "keeper_stalled"], description: "The alert kind (the `system.<kind>` events list them)." }
            title: { type: string, description: "Human-readable title in the merchant's language; generic for unknown kinds." }
            status: { type: string, enum: [open, resolved, event] }
            subject: { type: string, description: "Which instance (a chain id, an order id…); may be empty." }
            details: { type: object, description: "The alert's details as recorded." }
            at: { type: string, format: date-time, description: "When the alert opened, resolved or happened." }
            console_url: { type: string, description: "The admin console (`<admin url>/admin/`)." }
    Event:
      description: |
        A webhook event, also listed by `GET /v1/events`: `{id, type, created_at, livemode, data}`. The type decides
        `data`: an order, a subscription, a help ticket, or an alert (exactly one of the shapes below, by `type`).
      anyOf:
        - $ref: "#/components/schemas/OrderEvent"
        - $ref: "#/components/schemas/SubscriptionEvent"
        - $ref: "#/components/schemas/SupportTicketEvent"
        - $ref: "#/components/schemas/SystemEvent"
    OrderEvent:
      type: object
      required: [id, type, created_at, data]
      properties:
        id: { type: string, format: uuid, description: "The event; deduplicate on it." }
        type:
          type: string
          enum: [order.paid, order.duplicate_paid, order.payment_frozen, order.payment_reverted, order.expired, order.refunded]
          description: |
            `order.paid`: the first payment reached its confirmations (`paid`; again after a reverted order is paid
            anew). `order.payment_frozen`: a payment arrived from an address that fails risk screening (a block-level
            entry, or a built-in list such as the FBI's); it is frozen and does not count: the order stays unpaid. Do
            not fulfil the order, do not refund the payer, and handle the funds (already in the payee wallets) per
            your compliance process (`frozen_payment` gives it). `order.duplicate_paid`: a second confirmed payment (`duplicate_paid`; refund it — a refund is
            opened). `order.payment_reverted`: a confirmed payment left the chain (`reverted`; stop fulfilment).
            `order.expired`: unpaid at `expires_at`. `order.refunded`: a refund was confirmed on chain (`refund`
            gives it; status `partially_refunded`, `refunded`, or `paid` again after a duplicate's refund).
        created_at: { type: string, format: date-time }
        livemode: { type: boolean, description: "`false` for test mode events; absent on events from before modes (live)." }
        data:
          allOf:
            - $ref: "#/components/schemas/Order"
            - { required: [payments, customer_email], properties: { payments: {}, customer_email: {} } }
      allOf:
        - if: { required: [type], properties: { type: { const: order.refunded } } }
          then: { properties: { data: { required: [refund], properties: { refund: {} } } } }
        - if: { required: [type], properties: { type: { const: order.payment_frozen } } }
          then: { properties: { data: { required: [frozen_payment], properties: { frozen_payment: {} } } } }
    SubscriptionEvent:
      type: object
      required: [id, type, created_at, data]
      properties:
        id: { type: string, format: uuid }
        type:
          type: string
          enum:
            - subscription.activated
            - subscription.trial_will_end
            - subscription.charged
            - subscription.charge_failed
            - subscription.unpaid
            - subscription.paused
            - subscription.risk_paused
            - subscription.resumed
            - subscription.canceled
            - subscription.charged_after_cancel
            - subscription.completed
            - subscription.allowance_low
            - subscription.payment_method_changed
            - subscription.migration_requested
            - subscription.plan_change_pending
            - subscription.plan_changed
            - subscription.replaced
            - subscription.plan_change_expired
            - subscription.plan_change_canceled
          description: |
            `activated` (the on-chain subscription is confirmed: `trialing` or `active`; with an immediate start
            `charged` follows for period 0), `trial_will_end` (the trial ends within the configured days), `charged`
            (`charge`), `charge_failed` (`past_due`, `charge`, `retry_at`), `unpaid` (the grace period ran out:
            `unpaid`, no more charges), `paused` (`previous_status`), `risk_paused` (risk screening refused the
            payer before a charge; resumed from the console only), `resumed`, `canceled` (also once the on-chain
            subscription of a subscription canceled before the payer subscribed lands: `before_activation: true`;
            such a subscription never gets `activated`; `canceled_by` after an on-chain cancel),
            `charged_after_cancel` (a charge that landed on chain after the subscription was canceled here: refund
            it; no receipt), `completed` (every period passed),
            `allowance_low` (the allowance no longer covers the remaining periods: `allowance`, `needed`; once),
            `payment_method_changed` (the payer moved to another wallet, token or network: `previous`, `switch`),
            `migration_requested` (`migration`), `plan_change_pending` / `plan_change_expired` /
            `plan_change_canceled` (on the old subscription, with `plan_change`), `plan_changed` (on the new
            subscription once its on-chain subscription is confirmed, instead of `activated`: `previous` and
            `effective_at`), `replaced` (the old subscription of an applied plan change ended, `canceled` with
            `cancel_source: plan_changed`, usually together with `plan_changed`: `replaced_by` and `effective_at`; not a
            cancellation, the service goes on with the new subscription).
        created_at: { type: string, format: date-time }
        livemode: { type: boolean }
        data: { $ref: "#/components/schemas/Subscription" }
      allOf:
        # Per-type `data` (the fields the type adds; listed with empty schemas, defined in Subscription).
        - if: { required: [type], properties: { type: { enum: [subscription.charged, subscription.charged_after_cancel] } } }
          then:
            properties:
              data:
                required: [charge]
                properties: { charge: { required: [amount, tx_hash], properties: { amount: {}, tx_hash: {} } } }
        - if: { required: [type], properties: { type: { enum: [subscription.charge_failed, subscription.unpaid] } } }
          then:
            properties:
              data:
                required: [charge, retry_at]
                properties: { charge: { required: [error], properties: { error: {} } }, retry_at: {} }
        - if: { required: [type], properties: { type: { const: subscription.paused } } }
          then: { properties: { data: { required: [previous_status], properties: { previous_status: {} } } } }
        - if: { required: [type], properties: { type: { const: subscription.allowance_low } } }
          then: { properties: { data: { required: [allowance, needed], properties: { allowance: {}, needed: {} } } } }
        - if: { required: [type], properties: { type: { const: subscription.payment_method_changed } } }
          then:
            properties:
              data:
                required: [previous, switch]
                properties:
                  previous: { required: [chain_id, token, payer], properties: { chain_id: {}, token: {}, payer: {} } }
                  switch: {}
        - if: { required: [type], properties: { type: { const: subscription.migration_requested } } }
          then: { properties: { data: { required: [migration], properties: { migration: {} } } } }
        - if:
            required: [type]
            properties: { type: { enum: [subscription.plan_change_pending, subscription.plan_change_expired, subscription.plan_change_canceled] } }
          then: { properties: { data: { required: [plan_change], properties: { plan_change: {} } } } }
        - if: { required: [type], properties: { type: { const: subscription.plan_changed } } }
          then:
            properties:
              data:
                required: [previous, effective_at]
                properties:
                  previous: { required: [id, plan_id, plan_name], properties: { id: {}, plan_id: {}, plan_name: {} } }
                  effective_at: {}
        - if: { required: [type], properties: { type: { const: subscription.replaced } } }
          then: { properties: { data: { required: [replaced_by, effective_at], properties: { replaced_by: {}, effective_at: {} } } } }
    SupportTicketEvent:
      type: object
      required: [id, type, created_at, data]
      properties:
        id: { type: string, format: uuid }
        type: { type: string, enum: [support.ticket_created], description: "A payer sent the checkout's help form." }
        created_at: { type: string, format: date-time }
        livemode: { type: boolean, description: "Follows the ticket's order (live without one)." }
        data:
          type: object
          required: [id, ticket_no, livemode, order_id, merchant_order_no, kind, tx_hash, payer, customer_email, attachments]
          properties:
            id: { type: string, format: uuid }
            ticket_no: { type: string }
            livemode: { type: boolean }
            order_id: { type: [string, "null"], format: uuid }
            merchant_order_no: { type: [string, "null"] }
            kind: { type: string, description: "The issue type chosen in the form (e.g. `not_credited`, `other`)." }
            tx_hash: { oneOf: [{ $ref: "#/components/schemas/TxId" }, { type: "null" }], description: "As typed by the payer, in any family's form." }
            payer: { oneOf: [{ $ref: "#/components/schemas/Address" }, { type: "null" }] }
            customer_email: { type: string, description: The payer's reply address. }
            attachments: { type: integer, description: Screenshots attached (viewable in the console). }
    SystemEvent:
      type: object
      required: [id, type, created_at, data]
      properties:
        id: { type: string, format: uuid }
        type:
          type: string
          pattern: '^system\.[a-z0-9_]+$'
          description: |
            `system.<kind>`, one per alert-centre notification (an alert opening, resolving, or a one-off event).
            Kinds: `rpc_down` (every RPC endpoint of a chain down; `subject` the chain id), `relayer_low_balance` (the
            sponsoring hot wallet below its minimum), `walletconnect_down`, `keeper_idle` (live charges have been due
            for 15 minutes while the keeper has not run for 5: stopped, or no instance has a hot wallet configured),
            `keeper_stalled` (subscription charges or on-chain cancellations cannot be sent on a chain: hot-wallet
            balance, gas price cap or RPC), `charge_failure_rate` (subscription charge failures above the configured
            share), `reconcile_recovered` (reconciliation booked events the indexer had missed), `split_mismatch` (a
            payment's on-chain split transfers match no quote of its order), `unquoted_payment` (a payment on a
            replaced key's contract that matches no quote issued here: not booked), `payment_unquoted_chain` (a
            payment on a chain where its order has no quote for that token and amount, or whose network does not
            serve the order's mode: not booked; `details.reason` is `no_quote_on_chain` or
            `network_does_not_serve_mode`), `sub_event_wrong_network` (a subscription event on a chain whose network
            does not serve the subscription's mode: not booked), `sub_foreign_payer` (Solana: another payer opened an
            on-chain subscription with the terms quoted for a subscription; it is canceled on chain and its charges
            are recorded for refund), `payee_ata_recreated` (an event: a payee token account the Solana hot wallet had
            created was closed and is needed again; `details.action` tells whether the payer paid instead, the keeper
            funded it again or the charge was refused past the limit), `token_paused`, `token_depeg`,
            `price_feed_stale`, `token_impl_changed` (an upgradeable token changed its implementation: paused until
            reviewed), `sub_charge_after_cancel` and `sub_charge_retired_method` (a charge landed on chain after the
            subscription was canceled, or on a replaced payment method: refund it), `sub_duplicate_charge` (a second
            on-chain charge of a period already charged: refund it), `sub_duplicate_subscribe` (the payer subscribed
            twice with terms a re-quote replaced: the second on-chain subscription is canceled on chain),
            `sub_onchain_cancel_failed`, `sub_subscribe_front_run` (a sponsored `subscribeWithSig` was front-run
            without its permit; the permit was submitted on its own), `sub_funding_missing` (a subscription opened on
            chain without the allowance for its cap and the permit could not be resubmitted: the payer approves),
            `payer_risk_blocked` (risk screening refused a payer at the quote or the sponsored submission; at most
            once a day per payer and chain), `risk_provider_down` (a third-party screening provider cannot answer;
            `subject` is the provider), `ofac_import_failed`, `risk_list_import_failed` (a URL feed could not be
            imported and keeps its previous entries; `subject` is the feed's name), `email_suppressed` (an address no
            longer mailed after repeated bounces), `signer_rotated` (a new quote signer key is active; `emergency`
            when the replaced one is treated as leaked), `signer_mismatch` (a payment contract embeds another quote
            signer than recorded), `signer_unavailable` (a quote signer key kept in a KMS cannot sign: quotes answer
            `503 signer_unavailable` until it recovers; `subject` is the key's address), and `payee_blocked` (a payee
            address was blocked by screening; its own `data` shape, below). Alert kinds added later arrive as
            `system.<kind>` too: handle unknown kinds generically. Duplicate payments (`order.duplicate_paid`),
            risky bookings (the order events' `risk_flag`), keeper risk pauses (`subscription.risk_paused`) and
            dual-control approval requests reach the alert centre without a `system.*` event of their own.
        created_at: { type: string, format: date-time }
        livemode: { type: boolean, description: "`false` for alerts about test data (also `data.details.livemode: false`)." }
        data:
          anyOf:
            - $ref: "#/components/schemas/SystemAlert"
            - $ref: "#/components/schemas/PayeeBlocked"
      allOf:
        - if: { required: [type], properties: { type: { const: system.payee_blocked } } }
          then: { properties: { data: { $ref: "#/components/schemas/PayeeBlocked" } } }
          else: { properties: { data: { $ref: "#/components/schemas/SystemAlert" } } }
    SystemAlert:
      type: object
      required: [alert_id, status, subject, details]
      properties:
        alert_id: { type: string, format: uuid, description: "The alert (an opening and its resolution share it)." }
        status: { type: string, enum: [open, resolved, event], description: "`open` / `resolved` for conditions that clear; `event` for one-off notices." }
        subject: { type: string, description: "Which instance (a chain id, an order id, a provider…); may be empty." }
        details: { type: object, description: "The alert's details as recorded (kind-specific, flat); `livemode: false` for test data." }
    PayeeBlocked:
      type: object
      description: "`system.payee_blocked` only."
      required: [payee, address, chain_id, hits]
      properties:
        payee:
          type: object
          required: [ref, name]
          properties:
            ref: { type: string }
            name: { type: string }
        address: { $ref: "#/components/schemas/Address", description: EIP-55 checksummed. }
        chain_id: { type: integer }
        hits: { type: array, items: { type: object }, description: "The screening results that blocked it (source, category, …)." }
