openapi: 3.1.0

info:
  title: nrg.market API
  version: "1.0.0"
  summary: TRON energy for USDT transfers, on demand
  description: |
    nrg.market delivers TRON energy to the sending wallet right before a
    USDT (TRC-20) transfer, so the transaction does not burn TRX.

    ## Quick start
    1. Top up your balance **in TRX** at the address from `GET /deposit-address`.
    2. (Optional) Estimate the cost: `POST /estimate`.
    3. Create an order: `POST /orders` with an `Idempotency-Key` header.
    4. Wait for the `ready` status (webhook `order.ready` or polling).
    5. **Send the USDT transaction before `send_before`.**

    The same five steps work in the sandbox at
    `https://sandbox.nrg.market/v1`, where step 1 is a grant of test money
    and `POST /sandbox/deposit` rather than a transfer on chain. See
    "Sandbox" below.

    ## Modes
    - **Mode A (primary).** You send the transaction yourself. We deliver
      the energy and return a `send_before` deadline — the lease you bought
      less a 3-second margin, so 297 seconds on the five-minute product.
      Send on the signal, not near the deadline: that margin only makes the
      window end before the lease does, it is not slack for your side. Miss
      the deadline and the energy is wasted; the charge is not refunded.

    - **Mode B.** You submit an already signed transaction (`signed_tx`);
      we deliver the energy and broadcast it ourselves. Your private key
      is never transmitted — we do not need it.
    ## Lease durations
    An order names how long the energy is leased for: `duration_s`, five
    minutes by default. Which durations are on sale is answered by
    `GET /tariff` in `products[].duration_s` — read it rather than hard-coding
    a list, since a product goes on and off sale without a change to this
    document. The lease decides both the price and the length of the
    `send_before` window.

    ## One price per product (since 2026-10-26)
    Each lease on sale has one current price, recomputed against the market;
    there are no time-of-day zones and no schedule of future prices. On
    2026-10-26 the zone fields were removed from this contract, without a
    deprecation period: from `GET /tariff`, at the top level and in
    `products[]`, the name of the running zone, the moment it ends and the
    schedule of zone segments with their averages; the zone of every point
    of `GET /tariff/history` and of `ours` in `GET /market`; and the `zone`
    of `POST /estimate` and of an order. Nothing else in those responses
    changed, and the price fields mean exactly what they meant. Webhooks
    never carried zones.

    ## Energy maintenance (Auto-refill)
    `/auto-refill-rules` are "keep energy on this wallet" rules: energy is
    replenished after every spend, so no separate order per transfer is
    needed. A rule is described by an address and a mandatory daily budget —
    a spending cap per UTC day. The price of a single top-up is in
    `GET /tariff`; `maintenance.*` events report top-ups and stops.

    The resource originally shipped as `/maintenance-rules`. That path
    remains an **alias until 2026-12-01**: same responses plus
    `Deprecation: true` and `Sunset` headers. Event names (`maintenance.*`),
    the `maintenance_price_trx` tariff field and the
    `maintenance_rule_conflict` error code are not renamed: a path can
    have an alias, an event name cannot.

    ## Queue mode
    `/queue-sessions` is a session on one sender wallet for a run of USDT
    transfers you are about to send: a target level of free energy, Start,
    Stop and the ordered list of the payments. From Start the session keeps
    the wallet at the target with the cheapest five-minute energy, bought
    packet by packet and sized to the next transfers in the queue; it pauses
    by itself when the wallet's USDT does not cover the next payment and
    resumes when it does; it completes when the queue is exhausted. You pay
    only for packets whose delivery is seen on-chain, one
    `queue.packet_delivered` event per packet. The mode is on for every
    account by default; on an account it has been switched off for, every
    `/queue-sessions` path answers `404`.

    ## Amounts and time
    All amounts are in TRX, as strings with 6 decimal places (`"2.080000"`).
    All timestamps are UTC, ISO 8601.

    ## Order price
    An order is priced when it is created: every position at `energy_units`
    × the product's current per-unit price (a volume position
    can be priced higher, see `energy_units` on `POST /orders`), and the hold
    is placed for the total. That total is the order's `quoted_total_trx`,
    and it never changes.

    **The price can be raised while the order is being filled, and never
    falls below that total.** Right before a position is bought, its price
    is compared with what the cheapest vendor available for it at that
    moment may charge us. If that cost leaves less than our minimum margin
    under the position's price, the position's per-unit price is raised to
    the lowest whole-sun price that covers the cost with that margin —
    capped at a fixed multiple of the per-unit price the order was
    created at. The difference is held from your available balance at once:
    `total_trx` and the position's `price_trx` grow by it, `GET /ledger`
    shows a `hold` entry for it with the order's id, the `order.repriced`
    event is sent, and only then is the energy bought. A market that leaves
    our margin under the price leaves the price as it is. A position can be
    raised more than once — for instance when the vendor it was raised for
    refuses and the next one costs more still.

    **A raise is never made on credit.** If your available balance is short
    of the difference, or the price would have to go above the cap, there is
    no raise, and the position is filled as it would have been without one.
    A transfer position (one with a `kind`) is not bought: it ends `failed`
    with `purchase_failed`, its hold comes back in full and nothing is
    charged for it — exactly as when no vendor sells at all. A volume
    position is refused that way only while nothing has been bought for it
    and `allow_partial` is off; otherwise its fill goes on at the price it
    stands at and ends short — the units delivered are charged, the rest of
    the hold comes back, and the order ends `partially_completed` (or
    `failed`, if nothing at all could be bought). Keep your available
    balance above what you order if you would rather pay a dearer market
    than have a position refused or filled short. A transfer position that
    fails after it was raised (the vendor refused and nobody else sold) is
    refunded whole as well, the raise included; `total_trx` keeps the raised
    figure, and `charged_trx` says what was actually charged.

    **A volume position (`kind: bulk`) can be raised before its first piece
    is bought and between pieces.** It has one per-unit price, so a raise
    between pieces prices the units already delivered too. If the fill then
    ends short without buying anything after the raise, the raise is taken
    back: the position returns to the per-unit price its last delivered
    piece was bought at, the hold is lowered by the difference (a
    `hold_release` entry in `GET /ledger`), and another `order.repriced`
    reports `total_trx` going down.

    What you are finally charged is `charged_trx`, counted at the price each
    position stands at when the order settles. `POST /estimate` quotes the
    price an order would be **created** with at that moment — not a final
    price. Queue-mode packets are priced against the market packet by packet
    (see `queue.packet_delivered`).

    ## Idempotency
    `POST /orders` requires an `Idempotency-Key` header. A retry with the
    same key returns the original order and does not create a new one. The
    same key with a different request body → `409 idempotency_conflict`.
    `POST /queue-sessions` and `POST /queue-sessions/{session_id}/items`
    require the header with the same semantics.

    Any endpoint, including one that lists no `503`, may answer a retryable
    `503 capacity_unavailable` when the service is momentarily overloaded or
    waiting on database maintenance. Nothing is reserved or charged by such
    an answer: retry later, and retry an order under the same
    `Idempotency-Key`.

    ## Rate limits
    Four independent buckets, counted per API key: orders (120/min),
    reference requests (600/min), address checks
    (`GET /address-check`, 60/min — every miss of its cache is a
    question to the chain) and the webhook probe
    (`POST /webhooks/{webhook_id}/test`, 10/min — it opens a connection to an
    address you chose and tells you why it failed, and the honest use of it is
    a person pressing a button). On overflow — `429 rate_limited` with a
    `Retry-After` header. For the public endpoints without a key
    (`GET /tariff`, `GET /tariff/history`, `GET /contract.yaml`) the reference
    limit is counted per IP instead.

    `POST /estimate` pays for the addresses it asks about, not only for the
    call: one token for the call, plus one for each unique address in the body
    (`to` and `from` together) that our short-lived address cache does not
    hold. A cached address is free, so repeating an estimate costs one token.
    The charge is capped at what the bucket can hold: a body larger than the
    bucket (500 pairs with distinct `from` are 1000 uncached addresses) costs
    the whole bucket and passes on a full one. A body the bucket cannot pay for
    right now is refused with `429 rate_limited` before anything is asked of
    the chain, and its `Retry-After` is the time until the bucket is full again
    (the same as `RateLimit-Reset`). After it the same body passes, provided
    the key spends nothing else from the same bucket meanwhile: the other
    reference endpoints (`GET /balance`, `GET /ledger` and the rest) are
    paid from it too.
    `GET /address-book` with `include=chain` pays for the addresses of its
    page the same way: one token for the call, plus one for each address
    the cache does not hold.
    `GET /address-check` costs one token of its own bucket, as before — it
    asks about one address.

    `POST /orders`, `POST /queue-sessions` and `POST /queue-sessions/{session_id}/items`
    also spend a **node budget**: 1000 transfers per minute per **account**
    (not per key — every key of the account and the cabinet share it). An
    order costs one per transfer of the body, a queue session's creation one
    per item plus one for the sender, an append one per item; the request's own
    token still comes from the orders bucket. The charge is made before
    anything is asked of the chain and is capped at what the budget holds, so
    the largest body (500 transfers) always passes on a full budget. A body the
    budget cannot pay for right now is `429 rate_limited` with nothing asked of
    the chain; its `Retry-After` is the time after which the same body fits,
    and its `RateLimit-*` describe the node budget (transfers per minute), not
    the orders bucket. Successful answers keep carrying the orders bucket's
    state.

    Two endpoints answer without those headers, and neither absence is the
    outage signal described below: `GET /health` has no limiter of any kind,
    and `GET /contract.yaml` is counted but does not yet report the count.

    Every rate-limited answer — the successful ones too — carries the state
    of your bucket, so you can slow down before the refusal instead of after
    it:

    - `RateLimit-Limit` — how many tokens this bucket holds in its own
      window; a call is one token, and `POST /estimate` spends one more per
      uncached address (above). Per minute everywhere except the sandbox's
      `POST /sandbox/deposit`, whose window is the UTC day (below);
    - `RateLimit-Remaining` — how many are left right now;
    - `RateLimit-Reset` — seconds until the bucket is full again.

    The sandbox adds one allowance more, on its own endpoint and counted per
    day rather than per minute: `POST /sandbox/deposit` takes ten calls per
    client per UTC day. It refuses with the same `429 rate_limited` and the
    same `Retry-After`.

    ## Repeated authorization failures
    Failed authorizations are counted apart from the rate limits above, and
    they answer with their own code: `429 too_many_auth_failures`, also with
    `Retry-After`. Branch on the code, never on `message`:

    - `rate_limited` — the key is fine, the pace is not. Wait and retry.
    - `too_many_auth_failures` — waiting will not fix it. The credential is
      being refused; check the key, and check that your address is on that
      key's allowlist.

    The counter is keyed on the presented key **together with** your address,
    so a forgotten machine holding a revoked key cannot lock out the working
    integrations that share an office NAT with it. Credentials that resolve
    to no key at all are counted per address — there is nothing else to count
    them by. A request presenting a valid, active key is never refused by
    this counter.

    While an address is inside such a window, **every** refusal it gets is
    `too_many_auth_failures` — including one whose credential is a real key
    that failed for another reason, an address outside its allowlist among
    them. That is deliberate: telling those two refusals apart would tell
    whoever is guessing which of the strings they are trying are live keys.
    A key that works keeps working and still answers `200`.

    This counter is not a bucket — it has a budget and a window that grows,
    and nothing that refills — so `too_many_auth_failures` carries
    `Retry-After` and no `RateLimit-*`. There is no bucket state to report,
    and reporting one would be inventing it.

    ## Browsers are not supported
    This API is called from your server, not from a page. Authenticated
    endpoints answer no CORS headers at all and allow no browser origin:
    reaching them from client-side code would mean shipping `nrg_live_…` to
    everyone who loads the page, and a key shipped to everyone is a leaked
    key. A preflight request to one of them gets `405` in the usual error
    envelope and nothing that looks like permission. The keyless reference
    endpoints (`GET /tariff`, `GET /tariff/history`, `GET /health` and
    `GET /contract.yaml`) do answer browsers — `GET` only, from our own
    origins.

    ## Fireblocks Network Link is a different contract
    A Fireblocks workspace connects to nrg.market over the Fireblocks
    Provider Connectivity API v2, served at `/link/v2` — signed requests, no
    bearer token, and deposits only. **This document does not describe it**:
    that plane implements the vendor's own specification, answers in the
    vendor's error schemas, and accepts none of the keys described here. What
    we expose there and how a signing key is issued is written up in
    `docs/api-spec.md` §11.

    ## Send your own User-Agent
    Not a requirement: this API answers a default `Python-urllib/3.x` agent
    exactly like any other, and no client signature is refused here. Send an
    agent naming your integration anyway — it is what lets us find your
    requests in a log when you ask us about them.

    One host does refuse it, and it is not this one. The documentation site
    is served separately from the API, and its edge answers some
    programmatic clients — `Python-urllib` among them — with a `403` in
    `text/plain` carrying `error code: 1010`: no `{"error": {…}}` envelope
    and no error code of ours, because the request never reached us. That
    rule is not ours to lift on that host and we are not promising it will
    change. If you want this document from a program, take it from the API
    instead — `GET /contract.yaml` serves it byte for byte from this host,
    with nothing of the sort in front of it.

    ## Sandbox
    There are two `servers` entries. Production is the live service, on TRON
    mainnet, against your real balance. The sandbox at
    `https://sandbox.nrg.market` is the same `/v1` surface and the same code,
    running over test money, a simulated chain and simulated energy
    providers. Build against the sandbox; when the integration works, change
    the base URL and the key.

    ### A key belongs to one host or the other
    The cabinet that issues a key decides its kind: `app.nrg.market` issues
    `nrg_live_…` keys for `https://api.nrg.market/v1`, and
    `sandbox-app.nrg.market` issues `nrg_test_…` keys for
    `https://sandbox.nrg.market/v1`, where registration is self-serve.
    Neither host accepts the other's keys, and the two accounts share
    nothing — separate databases, separate balances, separate webhook
    endpoints and secrets.

    A key presented to the wrong host is refused with `401` and the ordinary
    `unauthorized` code — the same code as any key we do not accept, because
    the code is what you branch on and this is not a branch of its own. Only
    the `message` differs: it names the base URL that key does belong to, so
    a deployment pointed at the wrong host says so in one line of your log
    instead of looking like a revoked key. Read that as a message to a human,
    not as an instruction to a program: the host your client talks to is
    configuration, never something to discover at runtime and switch to.

    ### What the sandbox proves, and what it does not
    It is the same code over test money, so the money rules are the ones you
    will meet in production: orders in all three modes, holds and their
    release, the status machine, `send_before` and expiry, partial batches,
    charging, the ledger and idempotency all behave there as they behave
    here. Webhooks are real deliveries and not a mock — your URL, your
    secret, a real `X-NRG-Signature` over the bytes we send, the same retry
    ladder and the same delivery log — so a receiver verified against the
    sandbox is a verified receiver.

    The prices are the live ones: the sandbox's tariff mirrors production's
    within a few minutes (about two as a rule, three at the worst), so an
    estimate rehearsed there is the live price of that moment — not a
    promise of tomorrow's.

    What it cannot prove is the part the chain does: **energy never actually
    arrives anywhere.** The chain underneath is simulated, so a delegation
    "confirmed" there is a fact about our simulator and not about TRON.
    Whether real energy lands on a real wallet, and whether your transfer
    goes through without burning TRX, is learned in production and nowhere
    else.

    **The energy keeper does not run on the sandbox, and this is the one
    place it is said.** `/v1/maintenance-rules` is mounted there and behaves
    normally — a rule is created, listed, edited and deleted, and the
    validation of every field is the production validation. What does not
    happen is the work: the loop that watches an address and tops it up is
    not among the stand's background tasks, so a rule accepted there is never
    executed. Nothing marks it as inert — the rule reads back exactly as it
    would on production.

    In consequence none of `maintenance.topup`, `maintenance.paused` and
    `maintenance.budget_exhausted` will ever reach your endpoint from the
    sandbox, however long you wait or however you configure the rule. You can
    subscribe to them, and the subscription is real; the deliveries are not
    coming. Build the CRUD half of a keeper integration against the stand and
    treat the three events as unexercised code, the way the list below asks
    you to treat the branches that depend on the chain. `balance.low` is not
    in that group — it does fire on the sandbox, off `POST /sandbox/deposit`.

    ### Test money
    Activating a new sandbox account — confirming the e-mail, or the first
    Google sign-in — grants **10,000 TRX** of test balance; it arrives as an
    `adjustment_credit` row in `GET /ledger`.
    For more, `POST /sandbox/deposit` credits what you ask for — up to
    100,000 TRX per call, ten calls per client per UTC day — down the same
    path the deposit watcher uses in production: a `deposit` entry with a
    `sandbox-<uuid>` txid, and a real `deposit.credited` event — for
    1 TRX and more, as in production; a smaller amount is credited
    without it.

    ### Scenario addresses
    Some addresses in the sandbox are wired to behave in a fixed way, the
    way test card numbers are. They are ordinary base58check TRON addresses
    and nothing more: no private key exists for any of them, here or
    anywhere, which is why they can be printed in a public document.

    The recipient decides how much energy the transfer needs and what
    happens to the item after `ready` — the `to` of a transfer in mode `a`,
    the address parsed out of `signed_tx` in mode `b`:

    | Recipient | What the sandbox does with it |
    | --- | --- |
    | `TDRCjoKpcCqP87TVpxcwXmknadMcPom8cc` | An activated USDT holder, so `kind: single`. Delegation confirms in 2–8 s, and about 45 s after `ready` a synthetic transfer to it appears — the item ends `sent`. |
    | `TLLmUhBYgU125KkPpeTdP1vz1zqhoZwn9v` | Empty, so `kind: double` — twice the energy and twice the price — and not activated. **It stays that way.** The sandbox classifies this address by its name, not by its history, so it is empty for ever: every order to it prices as `double`, however many transfers have already landed. |
    | `TDUvBqzR3cYY6zYopYdJ9jWrxQRs9QmvQM` | Delegation confirms and no transfer ever appears. The item stands at `ready` until `send_before` and becomes `expired` — and is charged, exactly as in production: the energy was delivered whether or not you used it. |
    | `TKLeQhXSUba1GG1wdznyMc49oqModZ8Fbm` | On the USDT blacklist. The order is refused under the production rule — `422 blacklisted_recipient`, with `details.index` and `details.address`. |
    | any other valid address | Behaves like the holder in the first row. |

    The sender decides how the purchase and the delegation go — the `from`
    of a transfer in modes `a` and `b`, and in mode `c` the wallet you are
    energising, which is your own:

    | Sender | What the sandbox does with it |
    | --- | --- |
    | `TQ6ey8qT87bnzBJXj7gVTGCkrU4wUJ1EWQ` | The purchase fails at every provider. The item ends `failed` with `error: purchase_failed`, the hold is released and nothing is charged. |
    | `TYWZsWdM9u8QKJTi6XEmenpvCPwg1xmPCC` | The first provider is unavailable and the failover succeeds. Nothing in the response says so, which is the point: the order proceeds normally. |
    | `TNhq25t5XTEuk3mC9cTcAGB5rr3xuCkGyr` | Delegation confirms after about 25 s — the slow path, for the code that waits. |
    | any other valid address | Delegation confirms in 2–8 s. |

    The two tables describe two different things about one transfer, so they
    combine: the timing of the delegation comes from the sender, the energy
    kind and everything after `ready` from the recipient. Mixing the
    scenario addresses in one batch is how you get `partially_completed` —
    one transfer from the failing sender among ordinary ones, and the status
    falls out of the mix of item outcomes with nothing special asked for.

    **Neither table's address changes what it is.** The sandbox recognises
    them by name, so `kind: double` above stays `double` and the slow sender
    stays slow, order after order. Nothing here ever "becomes activated" or
    otherwise carries a history the way a real address does — an address's
    past on TRON is a production fact and the stand does not have one.

    **The sender addresses are shared by every client of the stand**, and so
    is the energy delegated to them. Two orders live at once on the same
    sender draw on one pool: the second may find energy already sitting there
    and confirm its delivery sooner than the table says, and yours is not the
    only integration that can put it there. The stated timings — the 25 s of
    the slow sender, the 2–8 s of the rest — hold exactly on an idle address.
    When the timing is what you are rehearsing, use a fresh sender address of
    your own instead: any valid address the sandbox does not recognise takes
    the ordinary 2–8 s path, and its delegations are private to it.

    ### Mode B in the sandbox
    Sign the transaction with any throwaway key: the simulated chain does
    not verify signatures, so a key generated on the spot and holding
    nothing is enough to exercise the mode end to end. Everything around the
    signature is real — the transaction is parsed and validated as
    production parses it, a malformed one is refused the same way, the item
    walks `broadcasting` → `broadcasted` → `confirmed`, and the broadcast
    confirms in about 3 s instead of the roughly one minute solidification
    takes on mainnet.

    ## Rehearsing against production
    An integration should be built against the sandbox. This list is about
    production itself — what the live service costs to exercise, for the
    parts you decide to try here anyway:

    - **Free to exercise, as often as your rate limits allow.**
      `GET /tariff`, `GET /tariff/history`, `GET /health`, `POST /estimate`,
      `GET /address-check`, `GET /balance`, `GET /ledger`,
      `GET /deposit-address`, `GET /settings`, `GET /stats/savings` and the
      `/webhooks` collection reserve nothing and charge nothing. An estimate
      takes up to 500 recipients and returns the same `kind`, `energy_units`
      and `warnings` an order would compute, so most of a batch integration
      can be built against `POST /estimate` alone.
    - **Your webhook receiver has a real rehearsal.**
      `POST /webhooks/{webhook_id}/test` sends it a real signed
      `webhook.test` delivery down the actual delivery path — same secret,
      same signature, same headers — and answers with what your endpoint
      replied; `GET /webhooks/{webhook_id}/deliveries` then shows every
      attempt we have made against it. No order, no charge. It is the one
      part of the order flow you can verify end to end without spending
      anything.
    - **Failure branches you can reproduce deliberately, at no cost.** `400`
      on a malformed body, `401` on an unknown key or one used from outside
      its IP allowlist, `404` on an unknown `order_id`, and
      `402 insufficient_balance` — the balance check runs before any money
      moves, so an order larger than `available_trx` is refused without
      charging you. `429` is yours to trigger too: the buckets above are
      counted per API key, so exhausting your own on a reference endpoint
      gives you the response and the `Retry-After` header without touching
      any other client's quota.
    - **Costs real TRX.** `POST /orders`, in every mode. Mode A cannot be
      rehearsed for free even once: we deliver the energy and the charge
      stands whether or not you send the transaction before `send_before`.
      `409 idempotency_conflict` also has a price — it needs an order that
      really was created under that key first.
    - **Cannot be reproduced on either host by any request you can send.**
      `503 capacity_unavailable` and the item errors `broadcast_failed`,
      `transaction_reverted` and `broadcast_window_missed`. All of them
      depend on energy supply, on the chain, or on the service being paused
      by us. Write that handling from the schema and the webhook payloads
      and review it as unexercised code: you will meet these branches for
      the first time in production, and saying so in advance is the point of
      this list.

      Two things that stood in this list no longer belong to it:
      `purchase_failed` and `partially_completed` are reproducible on demand
      in the sandbox, from the scenario addresses above.
    - **Reproducible on production only — the keeper does not run on the
      sandbox.** `maintenance.topup`, `maintenance.paused` and
      `maintenance.budget_exhausted` have their only source in the loop that
      maintains an address's energy, and that loop is not among the sandbox's
      background tasks. Rules are accepted there and never executed, so the
      three events never fire on that stand and nothing says so at the time.
      The CRUD of `/v1/maintenance-rules` rehearses fully; the events do not
      rehearse at all.
    - **Reproducible on production only — the sandbox has no contracts.**
      `kind: custom` and the `contract_recipient` warning both hang off a
      recipient being a smart contract, and the simulated chain marks no
      address as one: the dry-run that prices a contract transfer is a branch
      the stand cannot enter, so a sandbox `POST /estimate` or
      `GET /address-check` never returns either. On production they cost
      nothing to see — both endpoints are in the free list above, and any
      contract address will do. Exercise them there, and treat the
      `energy_units` of a `custom` position as a number you have not seen your
      code handle until you have.
  contact:
    name: nrg.market support
    url: https://nrg.market
  x-logo:
    altText: nrg.market

servers:
  - url: https://api.nrg.market/v1
    description: |
      Production — the live service, on TRON mainnet, against your real
      balance. Accepts `nrg_live_…` keys only, the ones issued in the
      cabinet at `app.nrg.market`. A `nrg_test_…` key here is refused with
      `401 unauthorized` naming the sandbox base URL.
  - url: https://sandbox.nrg.market/v1
    description: |
      Sandbox — the same code and the same `/v1` surface over test money, a
      simulated chain and simulated energy providers. Accepts `nrg_test_…`
      keys only, issued in the cabinet at `sandbox-app.nrg.market`, where
      registration is self-serve. See "Sandbox" above for what it proves and
      what it cannot.

security:
  - bearerAuth: []

tags:
  - name: Tariff
    description: Current prices. The time-of-day schedule is for reference; the commitment is the price of an order (see "Order price" above).
  - name: Market
    description: What energy costs at the vendors we measure. Reference about somebody else's prices, not an offer.
  - name: Orders
    description: Cost estimates and energy orders
  - name: Billing
    description: Balance, deposits, account ledger
  - name: Account
    description: Settings, statistics, webhooks
  - name: Maintenance
    description: Keeping wallets topped up with energy — auto-refill rules
  - name: Queue
    description: Queue sessions — a wallet kept at a level of energy for a run of transfers, paid per delivered packet
  - name: Address book
    description: Names, notes and tags for the addresses you use, with what this account did with each
  - name: Utility
    description: Address checks and service status
  - name: Sandbox
    description: Endpoints that exist only on https://sandbox.nrg.market. On production the same path is a 404.

paths:

  /tariff:
    get:
      tags: [Tariff]
      summary: Current tariff
      description: |
        The current price of every lease on sale. Public endpoint, no
        authorization required; rate limited by IP, since a public request
        carries no key.

        **A key is optional.** Send `Authorization: Bearer …` and the answer
        is about your account: if prices were agreed for it, they are the
        ones in this response, and `custom` says so — at the top level for
        the five-minute product, and on each entry of `products` for that
        lease. Without agreed prices a keyed answer is the
        public tariff with `custom: false`. A keyed request is rate limited by
        the key rather than the IP, and its answer is never cacheable:
        `Cache-Control: private, no-store` with `Vary: Authorization`. An
        invalid key is `401` — never a silent fall-back to the public tariff,
        so a broken key is visible as one.

        **One price per product.** The current price is recomputed against
        the market at a fixed interval of a few minutes; there is no schedule
        of future prices. Our only commitment to you is the price of a specific
        order: set when it is created, and raised at fulfillment only by the
        rule in "Order price" above. How the price has moved is
        `GET /tariff/history`.

        The public response is cacheable for what is left of the window in
        which our servers hold the current price (`Cache-Control: public,
        max-age=N`). The time of day plays no part in `N`.

        **The top-level fields are the five-minute product**, and they stay
        that way: `current_price_sun`, `custom` and
        `typical_price_trx` describe the 300-second lease exactly as they did
        before longer ones went on sale. Everything we sell is in `products`,
        one entry per lease on sale, ascending by `duration_s` — including
        the five-minute one, so the array reads on its own. A client that
        offers a choice of lease reads `products`; a client that only ever
        buys five minutes can keep reading the top level and change nothing.

        `products` is the list `POST /orders` and `POST /estimate` accept as
        `duration_s`. It is data rather than schema: a product goes on or off
        sale without a release, so the array is the answer to "what can I
        buy right now", and an enumeration copied into your code is the same
        question answered on the day you copied it.
      security:
        - {}
        - bearerAuth: []
      operationId: getTariff
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required:
                  [
                    current_price_sun,
                    custom,
                    typical_price_trx,
                    maintenance_price_trx,
                    products,
                  ]
                properties:
                  current_price_sun:
                    type: integer
                    description: |
                      Price per unit of energy, in sun, for the five-minute
                      lease. The same number as the 300-second entry of
                      `products`; per-product prices live there.
                    examples: [32]
                  custom:
                    type: boolean
                    description: |
                      `true` — for this product your agreed price is in force
                      now; `false` — the public price. About the five-minute
                      product, like every top-level field; each entry of
                      `products` carries its own. Only a request with a key
                      can see `true`. The terms of the agreement are not in
                      this response or anywhere else in the API — only the
                      prices they produce.
                    examples: [false]
                  typical_price_trx:
                    type: object
                    description: Approximate price of a single transfer at the current price
                    required: [single, double]
                    properties:
                      single: { $ref: "#/components/schemas/TRX" }
                      double: { $ref: "#/components/schemas/TRX" }
                  maintenance_price_trx:
                    type: object
                    required: [single, double]
                    description: |
                      The two rates of a single top-up under an energy
                      maintenance rule (`/auto-refill-rules`). Every top-up
                      delivers the full ~131,000 energy to the wallet, and
                      the rate is chosen by the spend of the **previous**
                      transfer: ~65,000 spent — `single`, ~131,000 spent —
                      `double`. The very first top-up of a rule is always
                      `double`.

                      It is not the price of a lease: a top-up is a
                      different product than an order and has a price of its
                      own. The price is
                      dynamic — we keep it below retail prices for comparable
                      products — so read it here rather than memorizing it.
                      You are charged the price in effect **at the moment the
                      top-up is recognized**.
                    properties:
                      single: { $ref: "#/components/schemas/TRX" }
                      double: { $ref: "#/components/schemas/TRX" }
                  trx_usd:
                    anyOf:
                      - $ref: "#/components/schemas/USD"
                      - type: "null"
                    description: |
                      Market price of one TRX in USD — **reference only**.
                      Nothing in this response, and nothing we charge, is
                      derived from it: every amount here is in TRX and every
                      charge is made in TRX.

                      `null` means we do not know the rate at this moment;
                      the rest of the tariff is unaffected. Do not use it to
                      settle anything — it is a convenience for showing a
                      price in dollars, refreshed a few times an hour.
                    examples: ["0.337700"]
                  products:
                    type: array
                    description: |
                      The leases on sale right now, ascending by
                      `duration_s`, one entry each. Never empty and never
                      without the 300-second product: the default of every
                      request that omits a duration has to be buyable.

                      A duration missing from this array is a duration
                      `POST /orders` and `POST /estimate` refuse with
                      `400 invalid_request`. `GET /tariff/history` is the
                      exception — it charts a product whether or not it is
                      on sale today, because history is about what was, not
                      about what you can buy.

                      `maintenance_price_trx` and `trx_usd` stay top-level:
                      a maintenance top-up is a different product than an
                      order and has no lease, and the exchange rate is about
                      TRX rather than about anything we sell.
                    items: { $ref: "#/components/schemas/ProductTariff" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /tariff/history:
    get:
      tags: [Tariff]
      summary: Tariff history
      description: |
        Hourly history of the selling tariff — for charts. Public endpoint,
        no authorization required; the public response is cacheable
        (`Cache-Control: public, max-age=300`).

        **A key is optional**, as on `GET /tariff`. With one, the history is
        your account's: an hour sold to you at prices agreed for your account
        carries those prices and `custom: true`; every other hour — before
        the agreement, after it ended, while autopricing was off — carries
        the public price and `custom: false`, which is what you were charged
        then. A keyed request is rate limited by the key, its answer is
        `Cache-Control: private, no-store` with `Vary: Authorization`, and an
        invalid key is `401`.

        The history is **for reference**: our only commitment to you is the
        price of a specific order (see "Order price" above). There is no
        forecast here — only what the
        service actually sold at; hours older than the recorded history
        show the earliest recorded price.

        **The response is not paginated, and its size is fixed by `range`
        alone.** You get exactly one point per hour of the range and never a
        partial answer: 24 points for `24h`, 168 for `7d`, 720 for `30d`.
        That is the whole of it — there is no cursor, no `limit`, and no
        continuation to follow. The count does not depend on how much history
        we have recorded and does not grow over time: a young database fills
        the hours it has no record for from the earliest recorded price
        rather than dropping them, and an old one still answers with 720 for
        `30d`. Size your buffers for 720 points and you are sized for good;
        `range` is a closed enum, so a fourth depth could only arrive as a
        change to this contract.

        **One product per request** — `duration_s`, the five-minute lease by
        default. Each product has its own price series, and mixing two of
        them into one chart would draw a step at every switch that no price
        ever made. Unlike `/estimate` and `/orders`, this accepts any of the
        three durations whether or not it is on sale: a product taken off
        sale still has a past, and a chart that goes blank the moment it
        does would hide exactly the period worth looking at.
      security:
        - {}
        - bearerAuth: []
      operationId: getTariffHistory
      parameters:
        - name: range
          in: query
          description: |
            History depth, and the only thing that decides the size of the
            answer: `24h` → 24 points, `7d` → 168, `30d` → 720.
          schema: { type: string, enum: [24h, 7d, 30d], default: 7d }
        - name: duration_s
          in: query
          description: |
            Which product's history to chart, in seconds. One of `300`
            (default), `3600` or `86400` — all three, on sale or not.
            Anything else is
            `400 invalid_request` whose `details` carries both the refused
            `duration_s` and `allowed`, the accepted values.

            Written as a plain integer rather than an enum for one reason
            only: it is the same field as on `/orders` and `/estimate`, and
            a client that has it typed one way there should not have to type
            it another way here. The set of values it takes is wider,
            though — that difference is the sentence above, not the schema.
          schema: { type: integer, default: 300, examples: [3600] }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [range, duration_s, points]
                properties:
                  range:
                    type: string
                    examples: [7d]
                  duration_s:
                    type: integer
                    examples: [300]
                    description: |
                      The product these points belong to — the `duration_s`
                      you asked for, or `300` if you asked for none. Echoed
                      so a chart can label a series without remembering
                      which request produced it.
                  points:
                    type: array
                    description: |
                      Hourly points, UTC, ascending by time; the last one is
                      the start of the current hour. Values are as of `t`.
                      Exactly one point per hour of `range`, with no gaps and
                      no pagination — 24, 168 or 720 of them.
                    items:
                      type: object
                      required: [t, price_sun, maintenance_price_trx, custom]
                      properties:
                        t: { type: string, format: date-time }
                        price_sun:
                          type: integer
                          description: |
                            Price per unit of energy during that hour, in
                            sun, on the product named by `duration_s` — for
                            the whole lease, as everywhere else in this
                            contract.
                          examples: [32]
                        maintenance_price_trx:
                          type: object
                          required: [single, double]
                          description: |
                            Energy-maintenance top-up rates in effect during
                            that hour (see the field of the same name in
                            `GET /tariff`). The same two numbers whatever
                            `duration_s` was asked for: a top-up has no
                            lease, so it has no per-product history either.
                          properties:
                            single: { $ref: "#/components/schemas/TRX" }
                            double: { $ref: "#/components/schemas/TRX" }
                        custom:
                          type: boolean
                          description: |
                            `true` marks an hour sold to the asking account at
                            its agreed price, so only a request with a key can
                            see it; `false` — the public price, and every hour
                            of the public history is `false`.
                          examples: [false]
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /market:
    get:
      tags: [Market]
      summary: TRON energy market
      description: |
        What energy costs at the vendors we measure, beside what it costs
        here. Public endpoint, no authorization required; rate limited by IP,
        since a public request carries no key.

        The response is cacheable for at most a minute — the cadence the
        measurement itself runs at — and never longer than what is left of
        the window in which our servers hold the current price: `ours` here
        is `GET /tariff`'s price.

        Every figure is an observation, never a quote we arranged: each
        vendor's own published rate for its own product, read at the moment
        in `observed_at` and fee-inclusive for one order of that size. A
        field we did not measure is `null`, never a plausible number —
        `sun_131k` is `null` where the vendor will not serve that size, not
        the price of the nearest size it will.

        **This is reference, and about somebody else's prices.** Only `ours`
        is ours, and only your order's price is a commitment: it is set when
        the order is created and can be raised at fulfillment only to the
        cheapest available vendor price plus our minimum margin, capped (see
        `GET /tariff`). A vendor listed here is not a
        supplier of ours and not a recommendation; we do not link to any of
        them, and their availability, terms and honesty are their own.

        The list is not the whole market: it is the vendors that publish a
        price we can read, that answered within the last 24 hours, that we
        are free to name, and whose rates are above `ours`. A vendor is not
        listed while either of its printed rates — `sun_65k` or `sun_131k` —
        is at or below our own current price, and it comes back by itself
        when our price moves under both. A vendor that publishes no
        `sun_65k` we can read is not listed at all, whatever its `sun_131k`
        says: with no price at the size this answer is ordered by there is
        nothing to compare against `ours` and nothing to show. An empty
        `vendors` with a `null` `observed_at` is a valid answer and means the
        measurement is empty, not that the service is unwell.

        `duration_s` asks the same question about one lease. With it, a vendor
        is quoted on the cheapest of its leases that cover that term — the
        term itself or a longer one, since an hour of energy serves a
        five-minute transfer as well as five minutes do — and on the exact
        term when two print the same price. The row's own `duration_s` names
        the lease it is quoted on, so a five-minute answer can list a vendor
        at `3600`. A shorter lease never stands in for a longer one: a vendor
        with no lease of that term or longer is left out. `ours` is that
        lease's own price, so which vendors clear it is decided per product
        too, and against every covering lease a vendor sells: a printed rate
        at or below `ours` in either column of any of them leaves the vendor
        out, whichever lease it would have been shown on. Without it the
        answer is what it has always been: each vendor on the product we rank
        first for it, `ours` at the five-minute price, and `duration_s` echoed
        as `null`. Anything outside the leases we sell is
        `400 invalid_request` whose `details` carries both the refused
        `duration_s` and `allowed`.
      security: []
      operationId: getMarket
      parameters:
        - name: duration_s
          in: query
          description: |
            Which lease to compare, in seconds: `300`, `3600` or `86400` —
            all three, on sale or not, as on `GET /tariff/history`.

            Given, each vendor is quoted on its cheapest lease that covers
            this one — this term or a longer one, the exact term on a tie —
            and `vendors[].duration_s` names that lease. A shorter lease is
            never quoted for a longer term.

            Left off, no term is asked for and none is imposed: every vendor
            is quoted on the product we rank first for it, which need not be
            the same term for two vendors, and `vendors[].duration_s` says
            which each row is. That is the answer this endpoint gave before
            the parameter existed.

            Anything outside those three is `400 invalid_request` whose
            `details` carries both the refused `duration_s` and `allowed`,
            the accepted values.
          schema: { type: integer, examples: [3600] }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [duration_s, observed_at, ours, vendors]
                properties:
                  duration_s:
                    type: integer
                    nullable: true
                    description: |
                      The lease this comparison is about, echoed from the
                      request. `null` when none was asked for — which is not
                      the same answer as `300`: the rows are then each on
                      their own vendor's best product and say so individually.
                      With a lease asked for, a row can still be on a longer
                      lease that covers it, and its own `duration_s` says so.

                      Read it rather than remembering what you asked for. Two
                      terms fetched at once are two answers that look alike,
                      and the one thing that tells them apart is this field.
                    examples: [3600]
                  observed_at:
                    type: string
                    format: date-time
                    nullable: true
                    examples: ["2026-09-04T00:20:00Z"]
                    description: |
                      The latest pass among the vendors listed — the moment
                      the freshest row in `vendors` was taken. `null` when
                      `vendors` is empty, because then there is no pass to
                      name.
                  ours:
                    type: object
                    required: [current_price_sun]
                    description: |
                      Our own price at the same moment, from the same
                      computation `GET /tariff` answers with. It is here so
                      that a comparison needs one request rather than two
                      taken a second apart.
                    properties:
                      current_price_sun:
                        type: integer
                        examples: [24]
                        description: |
                          Our price per unit of energy right now, in sun. An
                          integer, and not reformatted: it is a tariff, not a
                          measurement.
                  vendors:
                    type: array
                    description: |
                      One entry per vendor with an error-free observation in
                      the last 24 hours and a readable `sun_65k`, sorted by
                      `sun_65k` ascending, then by `name`. A vendor nobody
                      observes is simply absent, and the array may be empty.
                    items:
                      type: object
                      required:
                        [
                          name,
                          site,
                          channels,
                          product,
                          duration_s,
                          sun_65k,
                          sun_131k,
                          basis,
                          change_24h_pct,
                          available_energy,
                          min_order,
                          max_order,
                          observed_at,
                          stale,
                        ]
                      properties:
                        name:
                          type: string
                          examples: [Example Energy]
                          description: |
                            The vendor's own public brand name, and the key of
                            the row. Named as a market participant and nothing
                            else: nobody in this array is a supplier of ours,
                            and this response never says who is.
                        site:
                          type: string
                          nullable: true
                          examples: ["https://example-energy.test"]
                          description: |
                            The vendor's site, or `null` where we found none.
                            We do not link to it, and neither should a page
                            built from this feed without deciding to.
                        channels:
                          type: array
                          description: |
                            How the vendor can be reached, as far as we
                            established: an API, a web front, a bot. An empty
                            array means we established none — not that there
                            are none.
                          items:
                            type: string
                            enum: [api, web, bot]
                        product:
                          type: string
                          examples: ["1h"]
                          description: |
                            The product id as the observer records it — usually
                            the vendor's own spelling; for a derived rate it is
                            ours, since what was costed is not a product the
                            vendor sells under that name.

                            One product per vendor. Without `duration_s` in the
                            request: an hour's rental where there is one, else
                            the shortest term at least an hour long, else the
                            shortest term. With it: the cheapest of the
                            vendor's leases that cover the term asked for —
                            that term or a longer one, the exact term when two
                            print the same `sun_65k`. Bandwidth products are
                            never quoted here — this feed is about energy, and
                            a rate per unit of bandwidth is not a cheaper
                            energy price.
                        duration_s:
                          type: integer
                          nullable: true
                          examples: [3600]
                          description: |
                            The term of that product in seconds; `null` where
                            the product has no fixed term at all. With
                            `duration_s` in the request it can be longer than
                            the lease asked for — `3600` in a `300` answer is a
                            vendor whose hour is its cheapest way to cover five
                            minutes — and never shorter.
                        sun_65k:
                          type: string
                          nullable: true
                          examples: ["34.19"]
                          description: |
                            Fee-inclusive price per unit of energy for one
                            order of 65 000 units, in sun, always with two
                            decimals. Fee-inclusive because ranking by a bare
                            rate compares a number nobody is ever charged: at
                            this size a fixed per-order fee is a tenth of the
                            bill. Nullable in this schema and never `null` in
                            practice: a vendor with no readable price at this
                            size is not listed at all, so the field is here to
                            keep the contract from narrowing under clients
                            already written against it.
                        sun_131k:
                          type: string
                          nullable: true
                          examples: ["33.99"]
                          description: |
                            The same for an order of 131 000 units. `null`
                            where the vendor will not serve that size — never
                            the price of the nearest size it will.
                        basis:
                          type: string
                          enum: [published, computed]
                          description: |
                            What kind of number `sun_65k` and `sun_131k` are.

                            `published` — the vendor quoted this rate itself,
                            per unit of energy, at this order size. The figure
                            is the vendor's own.

                            `computed` — the vendor publishes a rate for
                            another unit, and this is our conversion of it: a
                            price per 10 000 units per day turned into the cost
                            of a unit held for an hour, say. The arithmetic is
                            ours, so the claim is weaker than a quote and is
                            marked as one. It says nothing about how the number
                            was read — a converted rate off a documented API is
                            `computed`, and a quoted one scraped off a page is
                            `published`.
                        change_24h_pct:
                          type: string
                          nullable: true
                          examples: ["-2.5"]
                          description: |
                            `sun_65k` against the same vendor's rate a day
                            earlier, in percent, signed, one decimal
                            (`"+1.2"`, `"-0.5"`, `"0.0"`). The comparison
                            takes the observation nearest 24 hours before this
                            one within half an hour; `null` when there is none
                            — we do not stretch the window to produce a
                            number.
                        available_energy:
                          type: integer
                          nullable: true
                          examples: [4447233]
                          description: |
                            Energy the vendor says it can deliver right now.
                            `null` means it publishes none, which is a finding
                            of its own rather than a zero.
                        min_order:
                          type: integer
                          nullable: true
                          examples: [60000]
                          description: Smallest order the vendor accepts, in units of energy; `null` if unpublished.
                        max_order:
                          type: integer
                          nullable: true
                          examples: [5000000]
                          description: Largest order the vendor accepts, in units of energy; `null` if unpublished.
                        observed_at:
                          type: string
                          format: date-time
                          examples: ["2026-09-04T00:20:00Z"]
                          description: The pass these numbers come from, on our clock, UTC.
                        stale:
                          type: boolean
                          description: |
                            True when that pass is more than 15 minutes old.
                            The row is still shown — an old measurement is a
                            fact and a hidden one is not — but it is shown as
                            old.
        "400": { $ref: "#/components/responses/BadRequest" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /estimate:
    post:
      tags: [Orders]
      summary: Estimate the cost
      description: |
        A reference calculation: how much energy is needed and what it
        costs. It reserves nothing, and it is not a final price: it is the
        price an order would be created with at this moment, and an order's
        price can still be raised at fulfillment when the market is dearer
        than it leaves room for (see "Order price" above). Recipients on
        Tether's USDT blacklist are flagged and not accepted into orders.

        **The estimate refuses nothing about an address.** Everything it
        notices comes back as `warnings` on the item, including the things
        that *would* be a refusal on `POST /orders`: an estimate reserves
        nothing, so there is nothing here to protect by refusing, and an
        integrator pricing a batch needs to see every position, not the ones
        that survive.

        A **volume** is the other half of that sentence and is refused where
        an order would refuse it — the bounds and the lease rule are the
        order's own (`400`, below). A price quoted for a body no order
        accepts would be worse than a refusal: it would look like a quote.

        **`from` is optional.** Give it and the sender is asked two questions
        — is it activated on chain, is it on Tether's blacklist — and both
        answers arrive as `inactive_sender` and `blacklisted_sender` on that
        item. Each has a counterpart at order creation, and a different one:
        a non-activated sender is a `422` in modes `a` and `c`, while a
        marked sender is a `422` in **mode `b` alone**, with
        `details.reason = blacklisted_wallet` — there we hold the signed
        transaction and broadcast it ourselves, so a wallet that cannot move
        USDT is a transfer the network refuses after we paid for its energy.
        In modes `a` and `c` the sender's mark is not checked at all and
        never refuses an order: it forbids that address to move USDT, not to
        receive energy, and what you want the energy for is your business.
        Omit `from` and the item says nothing about the sender; the older
        request shape, with `to` alone, keeps its old meaning.

        **`duration_s` names the lease being priced.** Three products exist —
        `300` (5 minutes), `3600` (1 hour) and `86400` (1 day) — and the
        values accepted here are the ones **on sale**, which may be a shorter
        list and moves without a new version of this document. The one-day
        lease has been off sale since 2026-10-25, and `products[]` says what
        is on sale today. Read it from `products[].duration_s` of
        `GET /tariff` instead of hard-coding the list: which durations we
        sell is data, not schema, and a client that
        decides for itself will offer a lease the order refuses. Send nothing and you price the five-minute lease,
        exactly as before; the response echoes back whichever product priced
        the answer.

        A duration we are not selling is `400 invalid_request` naming the
        allowed values in the message and, in `details`, both the refused
        `duration_s` and `allowed` — never the price of the nearest product:
        adjacent leases cost similar money, so that answer would look
        plausible and refer to different goods.

        **Or price a volume instead of transfers.** Send `energy_units`
        rather than `transfers` and the answer is about that number: its
        price, and `coverage` — how much of it the market could supply right
        now. Both halves are worth calling for before a large mode `c`
        order. The price is the one an order for this volume on this lease
        would be created with at this moment: `energy_units` × the current price from
        `GET /tariff`, **or × our cost floor when assembling the volume
        costs more than the current price** (see `total_trx`) — so it is not
        always arithmetic you can do from `GET /tariff`. Whether the volume
        is there today is `coverage`. Exactly one of the two fields; both
        together are `400 invalid_request` with
        `details.reason = kind_and_energy_units`.
      operationId: createEstimate
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              # The either/or, and nothing else, is in the `oneOf`; the
              # properties stay at the top level, where a client generator
              # keeps them (see the mode `c` item, which lost its required
              # `from` to branches that repeated it). Nothing here is
              # required unconditionally, so there is no `required` beside
              # them: the two alternatives are the branches, `duration_s` is
              # optional.
              oneOf:
                - required: [transfers]
                - required: [energy_units]
              properties:
                energy_units:
                  type: integer
                  minimum: 65000
                  maximum: 50000000
                  examples: [1000000]
                  description: |
                    Price a **volume** instead of a list of transfers — the
                    same number a mode `c` position may name. Exactly one of
                    the two: a body carrying both is
                    `400 invalid_request` with
                    `details.reason = kind_and_energy_units`, one carrying
                    neither is the same code with the usual `details.errors`.

                    The answer echoes the volume back in `energy_units`,
                    prices it in `total_trx` — the price an order for it
                    would be created with right now, which can be above the
                    current price (see there) — leaves `items` empty, since there are no
                    transfers to say anything about, and adds `coverage`,
                    which says whether the volume is on the market.

                    Outside the bounds the answer is `400 invalid_request`
                    with `details.reason = bulk_volume_out_of_range`. The
                    bounds are the order's, so a volume this endpoint
                    refuses is a volume no order would take either — and,
                    like the order's, they say what we **accept**, not what
                    is on the market: a number inside them is a number you
                    may ask for, and `coverage` in the answer is the half
                    that says whether it is there.
                transfers:
                  type: array
                  minItems: 1
                  maxItems: 500
                  items:
                    type: object
                    required: [to]
                    properties:
                      to:
                        $ref: "#/components/schemas/TronAddress"
                      from:
                        anyOf:
                          - $ref: "#/components/schemas/TronAddress"
                          - type: "null"
                        description: |
                          The wallet that will sign the transfer, if you
                          already know it. Optional and advisory: it changes
                          nothing about the price, only what the item's
                          `warnings` can tell you.
                duration_s:
                  type: integer
                  default: 300
                  examples: [300]
                  description: |
                    Seconds of lease the prices are asked for — one of the
                    products on sale, listed by `products[].duration_s` of
                    `GET /tariff`. Of the three durations that exist (`300`,
                    `3600`, `86400`) only some may be on sale at a given
                    moment, so the field carries no `enum`: an enumeration in a
                    generated client would go stale the day the list moves,
                    and it moves without a release.

                    Anything not on sale is `400 invalid_request` with the
                    allowed list in the message and, in `details`, the
                    refused `duration_s` beside `allowed`.

                    With `energy_units` above 131,000 it must be `3600` or
                    longer, exactly as on the order
                    (`details.reason = bulk_needs_longer_lease`): pricing a
                    volume against a lease no order would accept would quote
                    goods we do not sell.
            examples:
              batch:
                summary: Two ordinary wallets
                value:
                  transfers:
                    - to: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9
                    - to: TMu1y9vAczkdbXZFefE1rf6USo45k1PMUf
              contract:
                summary: A contract recipient (here, the USDT TRC-20 contract)
                description: |
                  Not a mistake and not a special call — the same request with
                  a recipient that happens to be a contract, shown because the
                  answer looks different. A contract has its own `transfer`
                  logic, so the 65,000 / 131,000 figures do not apply to it:
                  we price it from an actual dry-run of the transfer, the item
                  comes back with `kind: custom` and an `energy_units` that is
                  neither of the two standard numbers, and `warnings` carries
                  `contract_recipient`.

                  The warning is a heads-up, not a refusal: unlike a
                  blacklisted recipient, a contract is accepted into an order.
                  If you did not mean to send USDT to a contract, this is
                  where you find out.
                value:
                  transfers:
                    - to: TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t
              station:
                summary: Pricing a transfer whose sender is already known
                description: |
                  What a gas station in front of a custody withdrawal sends:
                  both addresses and the lease it is about to buy. The price
                  is the same as it would be without `from` — the sender is
                  asked about only so the answer can carry
                  `inactive_sender` / `blacklisted_sender` before the money
                  moves rather than as a `422` after it.
                value:
                  duration_s: 300
                  transfers:
                    - from: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9
                      to: TMu1y9vAczkdbXZFefE1rf6USo45k1PMUf
              hourly_lease:
                summary: The same batch priced as a one-hour lease
                description: |
                  A longer product is the same request with another
                  `duration_s`. The answer's shape does not change — only the
                  numbers and the `duration_s` echoed back with them. The
                  value has to be on sale at that moment
                  (`GET /tariff` → `products[].duration_s`); a duration that
                  is not comes back as `400 invalid_request` whose `details`
                  carries the refused `duration_s` and `allowed`.
                value:
                  duration_s: 3600
                  transfers:
                    - to: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9
                    - to: TMu1y9vAczkdbXZFefE1rf6USo45k1PMUf
              volume:
                summary: A volume rather than a list of transfers
                description: |
                  What to send before a large mode `c` order: no addresses,
                  one number, and an hour of lease because the volume is
                  above 131,000. The answer prices it and says, in
                  `coverage`, how much of it could be assembled right now.
                value:
                  duration_s: 3600
                  energy_units: 1000000
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required:
                  [
                    items,
                    energy_units,
                    coverage,
                    total_trx,
                    burn_cost_trx,
                    duration_s,
                  ]
                properties:
                  energy_units:
                    type: integer
                    nullable: true
                    examples: [1000000]
                    description: |
                      The volume this estimate priced, echoed back — present
                      only when you asked for one. `null` when the request
                      named `transfers`: there the volume is per item and
                      lives on each of them.
                  coverage:
                    type: object
                    nullable: true
                    required: [fillable_units, complete, checked_at]
                    description: |
                      How much of `energy_units` could be assembled right
                      now. `null` when the request named `transfers`.

                      **A floor, not a promise.** It is computed from the
                      capacity suppliers publish about themselves: a figure
                      they can revise between this answer and your order,
                      and one we cannot audit. A supplier that publishes no
                      capacity figure is **not counted** — it is not treated
                      as unlimited — so the real market is at least this
                      large and usually larger. Read it as "this much is
                      certainly there", never as "this much is reserved":
                      nothing here is reserved, and the same volume may be
                      sold to someone else a second later.

                      **This is the answer to "is it there".** The
                      `maximum` on `energy_units` is not: that bound says
                      what a request may name, and it is far above what the
                      market takes in one lease on an ordinary day. A volume
                      inside the bounds is a volume we accept; a volume with
                      `complete: true` here is a volume that was on the
                      market when `checked_at` says we looked.
                    properties:
                      fillable_units:
                        type: integer
                        examples: [1000000]
                        description: >-
                          How many units the published capacity adds up to,
                          counted only up to what you asked for.
                      complete:
                        type: boolean
                        description: >-
                          Whether that reaches `energy_units` in full. False
                          means an order for this volume would need
                          `allow_partial` to be accepted at all.
                      checked_at:
                        type: string
                        format: date-time
                        examples: ["2026-09-09T08:00:13Z"]
                        description: >-
                          When the capacity figures behind this were read.
                          They age: a stale floor is a floor about a market
                          that has moved.
                  items:
                    type: array
                    description: >-
                      One entry per transfer asked about. **Empty when the
                      request named `energy_units`** — a volume has no
                      addresses, so there is nothing per-address to say.
                    items:
                      type: object
                      required: [to, kind, energy_units, price_trx, warnings]
                      properties:
                        to: { $ref: "#/components/schemas/TronAddress" }
                        kind: { $ref: "#/components/schemas/TransferKind" }
                        energy_units: { type: integer, examples: [65000] }
                        price_trx: { $ref: "#/components/schemas/TRX" }
                        warnings:
                          type: array
                          description: |
                            What we noticed about this transfer's addresses.
                            Empty is the ordinary case, and more than one can
                            appear at once. The first three are about `to`,
                            the last two about `from` and present only if you
                            sent one.

                            - `blacklisted` — the address is on Tether's USDT
                              blacklist. The only one of the five that is a
                              refusal: the position is kept in the estimate so
                              you can see what will fall out, but an order
                              containing it is rejected.
                            - `inactive_recipient` — the address has never
                              been activated on chain. Not a refusal, and not
                              what prices the position either: `kind` follows
                              the USDT balance alone, so an unactivated
                              recipient that holds USDT is `single`. Worth
                              checking against your own records — the chain
                              carries no account for it, so nothing on chain
                              confirms it is the one you meant. Only your own
                              records can.
                            - `contract_recipient` — the address is a contract
                              rather than a wallet. Not a refusal either, and
                              it is why `kind` is `custom`: a contract runs its
                              own `transfer` logic, so `energy_units` comes
                              from a dry-run of the actual transfer instead of
                              the 65,000 / 131,000 figures. Worth checking
                              against your own records — sending USDT to a
                              contract address is more often a mistake than an
                              intention.
                            - `inactive_sender` — the `from` wallet has never
                              been activated on chain. Here it is advice; the
                              same finding at order creation is `422
                              invalid_address` with `details.reason =
                              inactive_wallet`, because energy cannot be
                              delegated to an account that does not exist.
                              Activate the wallet and send the order; a retry
                              without activating cannot help. **The order does
                              not trust the age of this answer:** activation
                              is re-read past the cache before an order is
                              refused for it, so a wallet activated seconds
                              after this estimate is accepted straight away
                              rather than once the cached answer expires.
                            - `blacklisted_sender` — the `from` wallet is on
                              Tether's USDT blacklist. Advice in modes `a` and
                              `c`, where the mark is not checked at all: it
                              stops that address from moving USDT, not from
                              receiving energy, and what you want the energy
                              for is your decision. In **mode `b` it is a
                              refusal** — `422 invalid_address` with
                              `details.reason = blacklisted_wallet` — because
                              there we hold the signed transaction and
                              broadcast it, so a marked sender is a transfer
                              the network rejects after we have paid for its
                              energy. Worth reading in any mode: energy
                              delivered to a marked wallet buys a transfer
                              that will not go through.
                          items:
                            type: string
                            enum:
                              [
                                blacklisted,
                                inactive_recipient,
                                contract_recipient,
                                inactive_sender,
                                blacklisted_sender,
                              ]
                  total_trx:
                    allOf: [{ $ref: "#/components/schemas/TRX" }]
                    description: |
                      The price. For `transfers`, the sum of the items'
                      `price_trx`. For `energy_units`, the price an order for
                      this volume on this lease would be created with right
                      now: `energy_units` × a per-unit price in whole sun,
                      which is **the higher of two numbers** — the current
                      price of `GET /tariff` for the lease, and our cost floor
                      for the volume: what assembling the whole of it from the
                      market's published capacity costs at this moment. The
                      floor only ever raises the price;
                      where it is under the current price the current price
                      stands. It is read from the same market data as
                      `coverage` and moves with it, so an order placed a few
                      minutes later can be priced differently, exactly as one
                      placed after the current price was recomputed can. When
                      fresh market data does not cover the whole volume, there
                      is no floor and the current price applies.

                      Either way this is the price an order is **created**
                      with, not a guaranteed final price: a market dearer at
                      fulfillment than this price leaves our minimum margin
                      under raises the order's price, the difference held from
                      your balance (see "Order price" in the introduction).
                      Where that raise cannot be made — the balance is short
                      of it, or it is above the cap — the position is refused
                      at purchase or delivered short (see `allow_partial` on
                      `POST /orders`).
                  burn_cost_trx:
                    allOf: [{ $ref: "#/components/schemas/TRX" }]
                    description: What the transfer would have cost by burning TRX
                  duration_s:
                    type: integer
                    examples: [300]
                    description: |
                      The lease these prices are for, in seconds — the value
                      you sent, or the default if you sent none. Echoed rather
                      than left implied: how long the energy lives is the one
                      thing an estimate must not leave to be looked up.
        "400":
          description: |
            Malformed request. Where the request was well-formed but asked
            for something we do not price, `details.reason` says which — the
            same words the order gives for the same conditions:

            `bulk_disabled` — volume estimates are switched off. The field
            is in the contract and the service is not serving it; nothing
            about the request will change that, and `transfers` still works.

            `bulk_volume_out_of_range` — `energy_units` is outside the bounds
            the schema declares. `details`: `energy_units`, `min_units`,
            `max_units`.

            `bulk_needs_longer_lease` — a volume above 131,000 was asked for
            against a lease shorter than 3600 s. `details`: `energy_units`,
            `duration_s`, `min_duration_s`.

            None of the three carries an `index`, and that is the only way
            they differ from the order's: an estimate prices one volume and
            has no positions to point at.

            `kind_and_energy_units` — the body named both `transfers` and
            `energy_units`. Exactly one of them. The word is the order's,
            where the pair is `kind` and `energy_units`; it is one word
            rather than two so that a client can branch on "you named the
            volume twice" once.

            `energy_units` is read as the schema declares it: an integer,
            and only an integer. A JSON string or a fractional number is
            the ordinary `details.errors`, not a coercion — and so is an
            explicit `null` in the field you did not choose, on either side
            of the either/or: a body omits the alternative it did not take.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "429": { $ref: "#/components/responses/RateLimited" }
        "503": { $ref: "#/components/responses/CapacityUnavailable" }

  /orders:
    post:
      tags: [Orders]
      summary: Create an energy order
      description: |
        Creates an order and places a hold on the balance. Processing is
        asynchronous: the response is `202`, then the status changes to
        `ready` (webhook `order.ready`).

        **Important:** after `ready` you have until `send_before` — the lease
        you bought, less a 3-second safety margin. On the five-minute
        product that is 297 seconds; on the one-day product 86 397. Send the
        transaction as soon as you get the signal and not near the deadline:
        3 seconds is arithmetic, not slack (see `send_before` in the
        schema). In
        mode `b` that window is also capped by the expiry of the signed
        transaction you sent (less a broadcast margin), so it can be far
        shorter than the lease: read `send_before` rather than computing it
        from `duration_s`.

        **`duration_s` chooses the lease**, and the durations accepted are
        the ones on sale — `products[].duration_s` of `GET /tariff`, in
        ascending order. Omit the field and the order is the five-minute
        one it has always been. A duration we are not selling is
        `400 invalid_request` whose `details` carries the refused
        `duration_s` and `allowed`, the accepted values;
        we do not quietly move the order to the nearest product, because
        adjacent leases cost similar money and the substitution would look
        like the order you sent.

        **How to wait.** The `202` carries `Location` — the order's own URL,
        the one to poll — and `Retry-After`, the number of seconds to wait
        before the first poll and between polls. Read them from the
        response instead of assembling the URL and inventing an interval:
        polling faster than `Retry-After` (currently 2 s) returns the same
        answer and spends your rate limit, and the value is served exactly
        so that we can change it without breaking your loop.

        Better still, do not poll: subscribe to the `order.ready` webhook.
        It arrives at the moment the energy is delegated and carries
        `send_before`, which is the number you plan around — a poller
        learns the same thing later by definition.

        Idempotency: the same `Idempotency-Key` with a byte-identical body
        returns the original order; with a different body —
        `409 idempotency_conflict`. A request that fails validation does
        not consume the key.

        **Two checks come before the network is asked anything**, right
        after the body's own form: the balance must cover the least the
        batch could cost — every transfer of modes `a` and `b` counted at the
        cheapest a USDT transfer is priced at, mode `c` at its stated volume —
        or the answer is `402 insufficient_balance` with that lower bound in
        `required_trx`; and the account's node budget (see "Rate limits")
        must have room for the body's transfers, or it is `429 rate_limited`.
        So an account with nothing on it gets its `402` before any
        `422` about the addresses. The `402` that comes after the network
        names the exact price and may ask for more than the first one did —
        recipients with no USDT make a transfer `double`. A mode `b` order
        that `auto_topup` would park is not refused by the first check: it
        is priced exactly and parked as before.

        **Three modes, and `mode` chooses between them.** In `a` you name
        the transfer and send it yourself; in `b` you hand us the signed
        transaction and we broadcast it. In `c` there is no transfer at
        all — you name a wallet and a volume, and the energy is delegated
        there. Only `a` and `b` derive how much energy a transfer needs
        from the recipient's USDT balance; `c` has no recipient to read,
        so the volume is yours to state and yours to get right — as a
        `kind` (one transfer's worth) or as `energy_units`, any number
        between the bounds that field declares.
      operationId: createOrder
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - $ref: "#/components/schemas/OrderRequestModeA"
                - $ref: "#/components/schemas/OrderRequestModeB"
                - $ref: "#/components/schemas/OrderRequestModeC"
              discriminator:
                propertyName: mode
                mapping:
                  a: "#/components/schemas/OrderRequestModeA"
                  b: "#/components/schemas/OrderRequestModeB"
                  c: "#/components/schemas/OrderRequestModeC"
            examples:
              single_mode_a:
                summary: One transfer, mode A
                value:
                  mode: a
                  transfers:
                    - from: TQ5NMqJjW8sBGqcpvUcXhbXm3jGnyDCmwK
                      to: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9
                  client_ref: invoice-1042
              batch_mode_a:
                summary: Batch, mode A
                value:
                  mode: a
                  transfers:
                    - from: TQ5NMqJjW8sBGqcpvUcXhbXm3jGnyDCmwK
                      to: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9
                    - from: TQ5NMqJjW8sBGqcpvUcXhbXm3jGnyDCmwK
                      to: TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t
              mode_b:
                summary: Signed transaction, broadcast on our side
                value:
                  mode: b
                  transfers:
                    - signed_tx: "0a02f1e22208...c1054d"
              mode_c:
                summary: Energy for a wallet, no recipient named
                value:
                  mode: c
                  transfers:
                    - from: TQ5NMqJjW8sBGqcpvUcXhbXm3jGnyDCmwK
                      kind: single
              mode_c_hourly:
                summary: The same wallet, energised for an hour
                description: |
                  A longer lease is the same body with `duration_s` on it. The
                  wallet keeps the energy for the whole term, so
                  `send_before` lands 3 597 seconds out rather than 297 —
                  one field decides both the price and the window.
                value:
                  mode: c
                  duration_s: 3600
                  transfers:
                    - from: TQ5NMqJjW8sBGqcpvUcXhbXm3jGnyDCmwK
                      kind: double
                  client_ref: treasury-wallet-september
              mode_c_bulk:
                summary: A million units on one wallet, all or nothing
                description: |
                  The volume is named instead of `kind`, so the item comes
                  back with `kind: bulk`. An hour of lease because the
                  volume is above 131,000: it is assembled from whichever
                  sources are cheapest and the pieces land seconds apart,
                  each leasing from its own delegation.

                  `allow_partial` is left out, so the default stands: if the
                  market cannot cover the whole million when we look — at
                  the position's price, or at the price it is raised to when
                  the market is dearer and your balance covers the raise (see
                  "Order price" in the introduction) — nothing is bought,
                  nothing is charged and the position ends `failed` with
                  `purchase_failed`. Ask `POST /estimate` with
                  the same `energy_units` first if you want to know whether
                  it is there. That check is made before the first purchase
                  and cannot be repeated afterwards — a market that empties
                  mid-fill leaves the position delivered short and billed for
                  what arrived.
                value:
                  mode: c
                  duration_s: 3600
                  transfers:
                    - from: TQ5NMqJjW8sBGqcpvUcXhbXm3jGnyDCmwK
                      energy_units: 1000000
                  client_ref: payout-batch-2026-09-09
              mode_c_bulk_partial:
                summary: The same volume, taking whatever can be had
                description: |
                  `allow_partial: true` turns the up-front refusal into a
                  short fill: the volume is accepted even when the market
                  visibly does not hold it, the position is delivered with
                  less than a million, `energy_delivered` says how much, the
                  charge is that number at the same per-unit price, and the
                  order ends `partially_completed`.
                value:
                  mode: c
                  duration_s: 3600
                  transfers:
                    - from: TQ5NMqJjW8sBGqcpvUcXhbXm3jGnyDCmwK
                      energy_units: 1000000
                      allow_partial: true
      responses:
        "202":
          description: |
            Order accepted for processing.

            Normally the status is `funded` — the money is reserved and the
            purchase has started. In one case it is `awaiting_funds`
            instead: mode `b`, `auto_topup` enabled, and the balance short.
            The signed transaction is held, no reserve is taken, a top-up
            request goes out, and `fund_before` says how long the deposit
            has. Branch on `status`, not on the code: a parked order is
            accepted, not delivered. A mode `c` order that named volumes is
            accepted the same way, and how much of each volume actually
            arrived is read later from the items' `energy_delivered`.
          headers:
            Location:
              description: |
                The order's own URL — `/v1/orders/{order_id}`. Poll it, or
                use it as the link you store next to your invoice.
              schema: { type: string }
            Retry-After:
              description: |
                Seconds to wait before the first poll and between polls
                (currently 2). Read the header rather than hard-coding the
                number.
              schema: { type: integer }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Order" }
        "400":
          description: |
            Malformed request. Where the request is well-formed but names an
            order we will not take, `details.reason` says which. Six of
            these belong to a mode `c` position that named `energy_units`,
            and each of them names the position in `details.index` except
            where it is said below that it does not:

            `bulk_disabled` — volumes are switched off. `kind` positions are
            unaffected, and nothing about the volume in the request will
            change this answer. No `index`: it is about the service, not
            about a position.

            `bulk_volume_out_of_range` — `energy_units` is outside the
            bounds the schema declares. `details`: `index`, `energy_units`,
            `min_units`, `max_units`.

            `bulk_needs_longer_lease` — a volume above 131,000 against a
            lease shorter than 3600 s. The volume arrives in pieces whose
            leases each start at their own delegation, seconds apart, and a
            five-minute lease cannot hold them together. `details`: `index`,
            `energy_units`, `duration_s`, `min_duration_s`.

            `duplicate_bulk_address` — a wallet that takes a volume was
            named by another position of the same order. Delivery on a
            volume position is measured as the growth of that wallet's
            energy over a reading taken before the first purchase, so
            anything else delegated to it in the same order is counted as
            our delivery — a short fill confirmed as whole, and billed as
            whole. It makes no difference what the neighbouring position is:
            another volume or a `kind`. `details`: `index` and `first_index`,
            the two positions. Order them separately, or ask for their sum in
            one volume position.

            `bulk_order_over_cap` — the order's volumes add up to more than
            your account's whole hourly allowance. No `index`: the sum
            belongs to the order rather than to any one position. `details`:
            `requested_units` and `cap_units`. Distinct from the `429`
            (`bulk_volume_cap`) on purpose: that one means "the same body,
            later", and this one has no later — the allowance is emptiest
            when the window is empty, and this order does not fit even then.
            Split it across hours, or ask for less.

            `kind_and_energy_units` — a position named both. Exactly one of
            them: there is no rule saying which would win. `details`:
            `index`. A position naming **neither** is the same code with the
            ordinary `details.errors`, and the entry there names the
            position (`body.c.transfers.0`).

            **A malformed position is refused before any of this**, by the
            request schema: naming both fields or neither, sending `null` in
            the field you did not choose, or sending `energy_units` as a JSON
            string are all answered without the service being consulted — so
            such a body gets `kind_and_energy_units` (or the schema error)
            even where volumes are switched off and `bulk_disabled` would
            otherwise be the answer.

            All six refuse the **order**, not the position — one is enough —
            and none of them consumes the `Idempotency-Key`.

            Mode `b` adds five more, about the signed transaction itself:
            rules every node enforces, so a transaction breaking one would be
            refused by the network, or run out of energy, after we bought its
            energy. All five carry `details.index`, the transaction in the
            batch (the first such transaction, if several break the rule):

            `expiration_too_far` — the transaction's `expiration` leaves it
            more than 86,340 seconds of life when we receive it (24 hours
            less a minute: no node accepts a deadline more than a day past
            its head block). Sign it again with a nearer deadline. Too
            little life — under 180 seconds — is refused too, with
            `details.index` alone, as it always was.

            `ref_block_invalid` — the TAPOS reference is not two bytes of
            `ref_block_bytes` and eight of `ref_block_hash`, a shape no node
            can look up. Build it again against a recent block, as wallets
            do.

            `ref_block_unknown` — the reference has the right shape, but the
            block the network holds under those two bytes has another id: it
            is older than the last 65,536 blocks (about 54 hours) a node
            remembers, from another network (Nile, Shasta), invented, or a
            block the network has just replaced (a fork). We ask the chain
            before accepting the order. Build the transaction again against
            the current block of mainnet. When we cannot get an
            answer from the chain, the order is accepted rather than refused,
            and a node's `TAPOS_ERROR` after delivery is billed as before.

            `malformed_tx` — the bytes are not what a node's parser would
            read the way we do: a field the transaction format does not have
            at that level (an outer `ret`, `raw_data.auths` or `scripts`, a
            TRC-10 attachment on the call), a field written twice, a nested
            message that does not parse, a varint in a longer spelling than
            its value needs, a field the transfer needs that is missing or of
            another type, a deadline no int64 holds, or a `type_url` other
            than exactly `type.googleapis.com/protocol.TriggerSmartContract`.
            Inside `raw_data` the shape a node re-encodes before hashing is
            required too — fields in ascending number, no field written with
            its default (`0`, empty) — because a node checks the signature
            against its own re-encoding and refuses any other shape. The
            outer envelope's two fields may come in either order. What a
            wallet's encoder writes passes; build the transaction with one.

            `fee_limit_too_low` — the transaction's `fee_limit` cannot pay
            for the energy the transfer needs at the network's current
            price. A node caps a call at `fee_limit / energy price` units and
            counts the energy we delegate against that cap as it counts TRX
            it would burn, so below the transfer's requirement it runs out
            of energy however much we deliver; a transaction without a
            `fee_limit` (the field left out, which is zero) gets no energy
            at all. A `fee_limit` of at least the position's `burn_cost`
            from `POST /estimate` always passes: it is the requirement times
            the same price. It is a ceiling, not a spend — with the energy
            delivered, none of your TRX is burnt unless the transfer costs
            more than its estimate (a recipient whose USDT balance emptied
            after the dry run doubles it): the difference is then burnt from
            the sender's TRX, up to the `fee_limit`. Checked after the dry run,
            whose measurement is the requirement of an unusual transfer.

            Every other refusal of a signed transaction is the same
            `400 invalid_request` with `details.index` alone.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
              examples:
                bulk_needs_longer_lease:
                  summary: A million units asked for on a five-minute lease
                  value:
                    error:
                      code: invalid_request
                      message: "A volume above 131000 units needs a lease of 3600 s or longer"
                      details:
                        reason: bulk_needs_longer_lease
                        index: 0
                        energy_units: 1000000
                        duration_s: 300
                        min_duration_s: 3600
                kind_and_energy_units:
                  summary: A position named both the kind and the volume
                  value:
                    error:
                      code: invalid_request
                      message: "A position names either kind or energy_units, not both"
                      details:
                        reason: kind_and_energy_units
                        index: 0
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402":
          description: |
            Insufficient balance.

            Answered at one of two points. **Before the network is asked
            anything**, when the balance does not cover even the cheapest price
            the batch could have: `required_trx` is then that lower bound,
            the least to add before the same body is priced at all. **After
            it**, when the exact price is known and does not fit:
            `required_trx` is the exact price. The two can follow each other on
            the same body — top up by the first figure, repeat, and the second
            names the rest — so read `required_trx` from the latest answer.

            With `auto_topup` on, the request a refusal of the first kind
            raises is **not** sized from that lower bound but from every
            transfer priced as a `double` (mode `c`: its own `kind` or volume),
            so `topup_amount_trx` there exceeds `required_trx`, and paying
            exactly it lets the same request through; what it overshoots stays
            on your balance. A second `402` after such a payment remains
            possible when the price or your free balance changed before the
            retry, and where the exact price is above a `double`: a mode `b`
            transfer whose dry run measures more (sold as `custom`), a
            recipient contract whose transfer costs more, or a mode `c` volume
            whose cost floor is above the current price. It then names a new
            `topup_request_id` — the payment closed the first.

            **A mode `b` order with `auto_topup` enabled does not come back
            here** — it is parked and answered `202` with the status
            `awaiting_funds` (see above). This `402` remains the answer for
            modes `a` and `c`, for any mode with the policy off, and for a
            mode `b` transaction with too little life left to be worth
            waiting on.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
              examples:
                low:
                  summary: The plain refusal — `auto_topup` is off
                  value:
                    error:
                      code: insufficient_balance
                      message: "Insufficient balance: 4.160000 TRX required, 1.020000 TRX available"
                      details: { required_trx: "4.160000", available_trx: "1.020000" }
                low_with_a_topup_request:
                  summary: >-
                    The same refusal with `auto_topup` enabled: a top-up
                    request has been raised for the difference
                  description: |
                    The order was **not** created and the `Idempotency-Key`
                    was not consumed — send the TRX to `deposit_address` and
                    repeat the same request. The request also arrives as
                    `topup.requested` and is readable at
                    `GET /topup-requests/{topup_request_id}`.

                    **Read the three fields by presence.** They are absent
                    whenever no request could be raised — see the next
                    example.
                  value:
                    error:
                      code: insufficient_balance
                      message: "Insufficient balance: 4.160000 TRX required, 1.020000 TRX available"
                      details:
                        required_trx: "4.160000"
                        available_trx: "1.020000"
                        topup_request_id: 9c4f0b52-31ad-4e6b-8d70-1f2a5c9e7b83
                        topup_amount_trx: "120.000000"
                        deposit_address: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9
                low_with_the_daily_cap_spent:
                  summary: >-
                    `auto_topup` enabled, but no request was raised: the daily
                    cap is spent
                  description: |
                    The same three fields are **missing**, and the body is the
                    plain refusal. Two states produce it: everything left of
                    `auto_topup.max_per_day_trx` for this UTC day is already
                    requested, or what is left of it would not cover the
                    shortfall — we do not ask for an amount that could not
                    unblock this order. Either way the answer is `402` and the
                    fix is yours: top up by however much you like, or raise the
                    cap in `PATCH /settings`.
                  value:
                    error:
                      code: insufficient_balance
                      message: "Insufficient balance: 4.160000 TRX required, 1.020000 TRX available"
                      details: { required_trx: "4.160000", available_trx: "1.020000" }
        "409":
          description: Idempotency conflict
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: |
            The addresses are well-formed, but the order cannot be taken on
            them. Three codes, and they are different situations:

            `blacklisted_recipient` — the recipient is on the USDT
            blacklist and cannot receive the transfer at all
            (`details.index`, `details.address`).

            `invalid_address` with `details.reason = inactive_wallet` — the
            `from` address is not activated on chain, so there is nowhere
            to delegate the energy to. Modes `a` and `c`; in mode `b` the
            transaction is already signed by the owner, so the account
            exists. `details.index` says which transfer of the batch,
            `details.address` which address. It is the same reason word
            `POST /auto-refill-rules` gives for the same condition.

            Two more reasons are mode `b` only and about the **sender**: we
            hold the signed transaction and we broadcast it, so a wallet
            that cannot move the USDT it signed away is a transfer the
            network will refuse after we paid for its energy. They are one
            code and two different situations, and what you do next differs.

            `invalid_address` with `details.reason = insufficient_usdt` —
            the sender does not hold what its own transfers move. The
            amounts travel with the refusal as `details.required_usdt` and
            `details.available_usdt`, and the requirement is summed **per
            sender across the batch** — ten transfers of 2 USDT from a
            wallet holding 5 need 20, and `details.index` names the first
            one the wallet cannot cover. Fund the wallet and resubmit.

            The sum also covers **what your other orders have not sent
            yet**: a wallet holding 5 USDT cannot be accepted for 5 in one
            order and 4.999999 in a second, because only one of the two
            transactions can succeed on chain and the loser reverts after
            its energy has been delivered. So `details.required_usdt` may
            exceed what this body alone moves — it is the total the wallet
            has to be able to move for every transfer of yours whose
            outcome is not yet settled on chain.

            An item counts while its status is `pending`, `delegated`,
            `broadcasting` or `broadcasted` — up to and **including** one
            we have already sent, because until a block carries it the
            wallet's balance still answers for it. It stops counting at
            `confirmed`, where the USDT has moved and the balance says so,
            and at `failed`, where it never moved and never will. A retry
            of a request under the same `Idempotency-Key` is not counted
            against itself either: it comes back as the original order.

            `invalid_address` with `details.reason = blacklisted_wallet` —
            the sender is on Tether's blacklist and cannot move USDT at
            all. `details` carries `reason`, `index` — the first transfer
            of the marked sender, this being a mark rather than a quantity
            — and `address`. **No amounts come with it:** there is no
            balance that would make this order pass, so nothing about how
            much is required or available is reported, and resubmitting
            will not help until Tether lifts the mark. In modes `a` and
            `c` the same mark is not a refusal: it forbids the address to
            move USDT, not to receive energy.

            `invalid_request` with `details.reason = dry_run_reverted` —
            mode `b` only: we ran the transfer on a node before agreeing to
            carry it, and the contract refused it. The node's own word for
            the refusal is in `details.message`. This is not a complaint
            about your request — it is well-formed — it is the network's
            answer about what would happen, given before the energy is
            bought rather than after.

            None of these refusals is about your request's shape, and none
            of them consumes the `Idempotency-Key`: the same key can be
            retried once the wallet is activated, funded, or another
            recipient is chosen. A **malformed** address is a different
            answer — `400 invalid_address`, no `details.reason`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
              examples:
                inactive_from:
                  summary: The wallet to energise does not exist on chain yet
                  value:
                    error:
                      code: invalid_address
                      message: "The address is not activated on chain"
                      details:
                        reason: inactive_wallet
                        index: 0
                        address: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9
                insufficient_usdt:
                  summary: The batch moves more USDT than the sender holds
                  value:
                    error:
                      code: invalid_address
                      message: "The sending address cannot make this transfer"
                      details:
                        reason: insufficient_usdt
                        index: 2
                        address: TQ5NMqJjW8sBGqcpvUcXhbXm3jGnyDCmwK
                        required_usdt: "6.000000"
                        available_usdt: "5.000000"
                dry_run_reverted:
                  summary: The contract would refuse the transfer
                  value:
                    error:
                      code: invalid_request
                      message: "The network would reject this transfer"
                      details:
                        reason: dry_run_reverted
                        index: 0
                        address: TQ5NMqJjW8sBGqcpvUcXhbXm3jGnyDCmwK
                        message: "REVERT opcode executed"
        "429": { $ref: "#/components/responses/RateLimited" }
        "503": { $ref: "#/components/responses/CapacityUnavailable" }

    get:
      tags: [Orders]
      summary: List orders
      operationId: listOrders
      parameters:
        - name: status
          in: query
          schema: { $ref: "#/components/schemas/OrderStatus" }
        - name: client_ref
          in: query
          schema: { type: string }
        - $ref: "#/components/parameters/Cursor"
        - $ref: "#/components/parameters/Limit"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/Order" }
                  next_cursor: { type: string, nullable: true }
        "401": { $ref: "#/components/responses/Unauthorized" }

  /orders/{order_id}:
    get:
      tags: [Orders]
      summary: Get an order
      operationId: getOrder
      parameters:
        - $ref: "#/components/parameters/OrderId"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Order" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }

  /orders/{order_id}/cancel:
    post:
      tags: [Orders]
      summary: Cancel an order
      description: Only possible before energy purchasing has started.
      operationId: cancelOrder
      parameters:
        - $ref: "#/components/parameters/OrderId"
      responses:
        "200":
          description: Order canceled, hold released
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Order" }
        "409":
          description: The order can no longer be canceled
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404": { $ref: "#/components/responses/NotFound" }

  /balance:
    get:
      tags: [Billing]
      summary: Balance
      operationId: getBalance
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [balance_trx, held_trx, available_trx]
                properties:
                  balance_trx: { $ref: "#/components/schemas/TRX" }
                  held_trx:
                    allOf: [{ $ref: "#/components/schemas/TRX" }]
                    description: Reserved for active orders
                  available_trx: { $ref: "#/components/schemas/TRX" }
        "401": { $ref: "#/components/responses/Unauthorized" }

  /deposit-address:
    get:
      tags: [Billing]
      summary: Deposit address
      description: |
        Your account's permanent address. **In v1 it accepts TRX only.**
        Funds are credited after network confirmation — the
        `deposit.credited` event. A deposit below 1 TRX is credited
        without `deposit.credited`; `GET /balance` and `GET /ledger` show
        it like any other.

        **Do not send USDT here.** The balance is kept in TRX, and
        USDT (TRC-20) sent to this address is not credited automatically —
        it reaches the operator as an unidentified deposit and is credited
        manually, which takes time. USDT deposits with automatic conversion
        will come later.
      operationId: getDepositAddress
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [address, accepts, confirmations_required]
                properties:
                  address: { $ref: "#/components/schemas/TronAddress" }
                  accepts:
                    type: array
                    items: { type: string }
                    description: Currencies accepted for automatic crediting. In v1 — TRX only.
                    examples: [["TRX"]]
                  confirmations_required: { type: integer, examples: [3] }
        "401": { $ref: "#/components/responses/Unauthorized" }

  /ledger:
    get:
      tags: [Billing]
      summary: Account ledger
      description: |
        Balance movements, newest first.

        **Amounts are always positive.** Direction comes from `type`, not
        from the sign: `deposit`, `hold_release`, `refund`,
        `adjustment_credit` add funds; `hold`, `charge`, `adjustment_debit`
        subtract.

        **`balance_after_trx` is the full balance after the operation.** It
        does not change on `hold` and `hold_release` rows: a hold does not
        spend money, it reserves it, affecting `available_trx` rather than
        `balance_trx` (see `GET /balance`).

        **An order can leave more than one `hold`.** The first is placed at
        creation for `quoted_total_trx`; each raise of a position at
        fulfillment adds one more for the difference, with the same
        `order_id` (see "Order price" in the introduction). A volume raise
        taken back before the order settles is a `hold_release` for the
        difference. When the order settles, its `charge` and `hold_release`
        rows together add up to all of its `hold` rows.
      operationId: listLedger
      parameters:
        - name: type
          in: query
          schema:
            type: string
            enum:
              - deposit
              - hold
              - hold_release
              - charge
              - refund
              - adjustment_credit
              - adjustment_debit
        - $ref: "#/components/parameters/Cursor"
        - $ref: "#/components/parameters/Limit"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/LedgerRow" }
                  next_cursor: { type: string, nullable: true }
        "401": { $ref: "#/components/responses/Unauthorized" }

  /topup-requests:
    get:
      tags: [Billing]
      summary: List top-up requests
      description: |
        What we have asked you to send, and how each ask ended. A request is
        created by **us**, never by a call: when an order is refused for lack
        of balance (`402`), or when the available balance falls under your
        `balance_low` threshold. Both only happen while `auto_topup.enabled`
        is on in `GET /settings`; with it off nothing here is ever written.

        At most one request is `open` at a time. A second need raises the one
        already open — same `id` — and re-sends `topup.requested`; it does not
        add a second row. "Raises" is not only about money: the `reason` can
        escalate from `balance_low` to `order_insufficient_balance` with
        `amount_trx` unchanged, and `expires_at` moves on every re-send. Do not
        deduplicate on `(topup_request_id, amount_trx)`.

        Not to be confused with `maintenance.topup` (§10): that is **energy**
        delivered to a wallet under an auto-refill rule. Here it is **TRX**
        for your prepaid balance. Money actually credited is
        `deposit.credited`, as always — for a deposit of 1 TRX or more. A
        smaller one is credited without `deposit.credited`, and if it is the
        one that completes a request, `topup.fulfilled` still arrives naming
        its txid (see `WebhookEvent`).
      operationId: listTopupRequests
      parameters:
        - name: status
          in: query
          schema: { $ref: "#/components/schemas/TopupRequestStatus" }
        - $ref: "#/components/parameters/Cursor"
        - $ref: "#/components/parameters/Limit"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/TopupRequest" }
                  next_cursor: { type: string, nullable: true }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }

  /topup-requests/{topup_request_id}:
    get:
      tags: [Billing]
      summary: Get a top-up request
      operationId: getTopupRequest
      parameters:
        - $ref: "#/components/parameters/TopupRequestId"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TopupRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }

  /topup-requests/{topup_request_id}/cancel:
    post:
      tags: [Billing]
      summary: Cancel a top-up request
      description: |
        Withdraw a request you do not intend to pay. Only an `open` one can be
        cancelled; anything else answers `409 topup_request_not_cancelable`.

        **This refuses nothing but the request.** TRX sent to the deposit
        address is credited whenever it arrives, cancelled request or not.
        What the cancellation frees is the room the amount took in your daily
        `auto_topup.max_per_day_trx` cap, and the slot for a new request.
      operationId: cancelTopupRequest
      parameters:
        - $ref: "#/components/parameters/TopupRequestId"
      responses:
        "200":
          description: Cancelled
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TopupRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: |
            The request is not `open` any more — it was fulfilled, it expired,
            or it has already been cancelled (`topup_request_not_cancelable`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /address-check:
    get:
      tags: [Utility]
      summary: Check an address
      description: Whether the address is activated, holds USDT, is on Tether's blacklist, or is a contract.
      operationId: checkAddress
      parameters:
        - name: address
          in: query
          required: true
          schema: { $ref: "#/components/schemas/TronAddress" }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required:
                  [
                    address,
                    activated,
                    holds_usdt,
                    blacklisted,
                    is_contract,
                    expected_kind,
                  ]
                properties:
                  address: { $ref: "#/components/schemas/TronAddress" }
                  activated: { type: boolean }
                  holds_usdt: { type: boolean }
                  blacklisted: { type: boolean }
                  is_contract: { type: boolean }
                  expected_kind: { $ref: "#/components/schemas/TransferKind" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "429": { $ref: "#/components/responses/RateLimited" }
        "503": { $ref: "#/components/responses/CapacityUnavailable" }

  /settings:
    get:
      tags: [Account]
      summary: Account settings
      operationId: getSettings
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Settings" }
        "401": { $ref: "#/components/responses/Unauthorized" }
    patch:
      tags: [Account]
      summary: Update settings
      description: |
        **Only the fields you send change.** A field left out keeps its
        stored value, and an empty body `{}` is a legal no-op returning the
        settings as they are. Nothing is reset by omission.

        **An omitted field and an explicit `null` are different requests.**
        Sending `"baseline_price_sun": null` clears the baseline price, and
        with it the `baseline_*` fields of `GET /stats/savings`, which become
        `null` — there is then nothing to compare against. Omitting the field
        leaves whatever is stored. This is the only way to remove a baseline
        price once set: there is no value that means "unset", and `0` is
        rejected (the range is 1 to 100000 sun per unit of energy — a price
        outside it is a unit error, not a provider).

        `balance_low_threshold_trx` draws no such distinction, because it does
        not need one: `"0.000000"` is how the `balance.low` event is switched
        off, so `null` there says nothing beyond "not sent" and is treated as
        an omission.

        **`auto_topup` follows the same rule one level down.** The object is
        optional, every field in it is optional, and a `null` anywhere in it
        means "not sent" — there is nothing to clear these to that `"0.000000"`
        does not already say. Switching the policy on requires
        `max_per_day_trx` above zero, and the rule is checked on the
        **resulting** settings: an account that already has a cap may send
        `enabled` by itself, one that has not gets `400 invalid_request`
        naming the field. The same check refuses an enabled policy whose
        `target_trx` is under `balance_low_threshold_trx` while both are set
        (see `AutoTopup.target_trx`), and it runs on every `PATCH` — a body
        that only raises the threshold over a standing target is refused too.

        The change is written to `audit_log` together with the previous value.
      operationId: updateSettings
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              # Not the `Settings` schema of the response: there both fields
              # are required, and a client generated from it would be unable
              # to send one of them alone. Here both are optional — only what
              # is sent changes — and an explicit `null` in
              # `baseline_price_sun` is a reset rather than an omission.
              properties:
                baseline_price_sun:
                  anyOf:
                    - type: integer
                      minimum: 1
                      maximum: 100000
                    - type: "null"
                  description: >-
                    Your current price with another provider, in sun per
                    **unit of energy** — not per transfer. `null` clears it;
                    leave the field out to keep it. The same bounds as
                    `baseline_sun` on `GET /stats/savings`, and for the same
                    reason.
                  examples: [40]
                balance_low_threshold_trx:
                  anyOf:
                    - $ref: "#/components/schemas/TRX"
                    - type: "null"
                  description: >-
                    Threshold for the `balance.low` event; `"0.000000"`
                    switches the event off. It is also the line the auto
                    top-up review measures against — one threshold, not two.
                auto_topup:
                  anyOf:
                    - $ref: "#/components/schemas/AutoTopupPatch"
                    - type: "null"
            examples:
              set_baseline:
                summary: Set your current provider's price for comparison
                value:
                  baseline_price_sun: 40
                  balance_low_threshold_trx: "500.000000"
              clear_baseline:
                summary: Remove the baseline price — an explicit null, not an omission
                value:
                  baseline_price_sun: null
              one_field_only:
                summary: Change the threshold; the baseline price is untouched
                value:
                  balance_low_threshold_trx: "500.000000"
              enable_auto_topup:
                summary: Ask us to request top-ups, capped at 500 TRX a day
                value:
                  balance_low_threshold_trx: "50.000000"
                  auto_topup:
                    enabled: true
                    target_trx: "200.000000"
                    min_trx: "20.000000"
                    max_per_day_trx: "500.000000"
              switch_auto_topup_off:
                summary: Stop asking; the amounts are kept for when it is turned back on
                value:
                  auto_topup: { enabled: false }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Settings" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }

  /stats/savings:
    get:
      tags: [Account]
      summary: How much you saved
      description: |
        Two comparisons over a period:
        - **against burning TRX** — if you had not rented energy at all. The
          base is `burn_cost_sun`, fixed when each order was created;
        - **against your current price** — based on `baseline_price_sun`
          from settings (or the `baseline_sun` parameter). If no baseline
          price is set, the corresponding fields return `null`.

        Counted are the orders you **paid for**: settled and having delivered
        energy. A cancelled order and one still in flight have no charged sum
        at all. A failed order does reach settlement — with a zero sum — but
        no energy was delivered and nothing was charged, so its burn cost is
        not a saving and the order is left out. The same selection stands
        behind every field of the response, `orders`, `energy_units` and
        `burn_cost_trx` included. Both sides of the comparison are taken per
        whole order: `burn_cost_sun` is not split across items.

        Savings are floored at zero per order, and equally so in **both**
        comparisons: an order that came out dearer than burning contributes
        zero to `saved_vs_burn_trx` rather than a negative, and one dearer
        than your own price contributes zero to `saved_vs_baseline_trx`.
        Neither eats into the savings of the orders next to it. The floor sits
        on the order and not on the period's total — otherwise one figure
        would stand for two different facts. The comparison bases are
        unchanged by it: `burn_cost_trx` and `baseline_cost_trx` remain the
        full sums over those same orders.

        Percentages are shares of the comparison base, not of what you paid:
        `saved_vs_burn_pct` is a share of `burn_cost_trx`, and
        `saved_vs_baseline_pct` a share of `baseline_cost_trx`. Neither is the
        mirror of what you paid — because of the per-order floor, "92%" does
        not mean "you paid 8% of what burning would have cost". An order
        dearer than burning adds to `paid_trx` without subtracting from
        `saved_vs_burn_trx`, so the two can add up to more than
        `burn_cost_trx`; the same holds for the baseline pair. It is the
        savings that are reported honestly rather than the identity that is
        kept tidy.
      operationId: getSavings
      parameters:
        - name: period
          in: query
          schema:
            type: string
            enum: [24h, 7d, 30d, 90d, all]
            default: 30d
        - name: baseline_sun
          in: query
          description: >-
            Override the baseline price for this request — sun per **unit of
            energy**, not per transfer. At least 1: zero would read as "your
            provider is free", and the way to say "there is nothing to compare
            with" is to leave the parameter out and the setting empty. At most
            100000 (0.1 TRX per unit), which is some two hundred times the
            dearest way energy is obtained on TRON at all; a larger number is a
            price stated per transfer rather than per unit, and it is refused
            as `400 invalid_request` rather than answered with savings sixty-five
            thousand times the fact.
          schema: { type: integer, minimum: 1, maximum: 100000 }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required:
                  [
                    period,
                    orders,
                    energy_units,
                    paid_trx,
                    burn_cost_trx,
                    saved_vs_burn_trx,
                    saved_vs_burn_pct,
                    baseline_price_sun,
                    baseline_cost_trx,
                    saved_vs_baseline_trx,
                    saved_vs_baseline_pct,
                  ]
                properties:
                  period: { type: string, examples: [30d] }
                  orders:
                    type: integer
                    examples: [12401]
                    description: >-
                      How many orders the figures cover — settled and having
                      delivered energy. A failed order settles at zero and is
                      not among them.
                  energy_units:
                    type: integer
                    examples: [1149000000]
                    description: Energy over the items of those same orders.
                  paid_trx: { $ref: "#/components/schemas/TRX" }
                  burn_cost_trx:
                    allOf: [{ $ref: "#/components/schemas/TRX" }]
                    description: What burning would have cost over those same orders.
                  saved_vs_burn_trx:
                    allOf: [{ $ref: "#/components/schemas/TRX" }]
                    description: Summed per order, each floored at zero.
                  saved_vs_burn_pct:
                    type: number
                    examples: [92.4]
                    description: >-
                      A share of `burn_cost_trx`, not of what was paid, and not
                      the mirror of it — see the per-order floor above.
                  baseline_price_sun: { type: integer, nullable: true, examples: [40] }
                  baseline_cost_trx:
                    oneOf:
                      - $ref: "#/components/schemas/TRX"
                      - type: "null"
                    description: >-
                      All the counted energy at your baseline price — the base
                      of the second comparison, which the per-order floor does
                      not change. `null` — no baseline price is set.
                  saved_vs_baseline_trx:
                    oneOf:
                      - $ref: "#/components/schemas/TRX"
                      - type: "null"
                    description: >-
                      Savings against your own price, summed per order and
                      each floored at zero — the same floor as
                      `saved_vs_burn_trx`. `null` — no baseline price is set.
                  saved_vs_baseline_pct:
                    type: number
                    nullable: true
                    examples: [20.0]
                    description: >-
                      A share of `baseline_cost_trx`, not of what was paid, and
                      not the mirror of it — see the per-order floor above.
                      `null` — no baseline price is set.
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /webhooks:
    get:
      tags: [Account]
      summary: List webhook endpoints
      description: |
        Your endpoints, oldest first.

        **The response shape changed on 2026-08-26.** It used to be a bare
        array; it is now the same `{data, next_cursor}` envelope as
        `/orders`, `/ledger` and `/auto-refill-rules`. The old shape was not
        kept behind an alias or a header: an array and an object part company
        at parse time, so a generated client fails loudly on the first line
        instead of quietly reading the wrong field.
      operationId: listWebhooks
      parameters:
        - $ref: "#/components/parameters/Cursor"
        - $ref: "#/components/parameters/Limit"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/WebhookEndpoint" }
                  next_cursor: { type: string, nullable: true }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
    post:
      tags: [Account]
      summary: Register a webhook
      description: |
        The signing secret is returned only once, on creation.

        **The `url` must be `https`, carry no credentials, resolve to a public
        host, and hold no ASCII control character** — `\x00`–`\x1f` (tab,
        newline and carriage return among them) and `\x7f` — anywhere in the
        string. A control character is refused with `400 invalid_request` and
        `details = {position}`, the offset of the first one: the character is
        invisible, and the offset is the only way you will find it in your own
        configuration. It usually arrives as a trailing `\n` read out of a file
        or a command's output.

        **An account may hold at most 5 active endpoints.** One more is
        refused with `400 invalid_request`, carrying
        `details = {active_webhooks, limit}`. Deliveries are sent one after
        another with a five-second budget per attempt, so the endpoints of one
        account queue up in front of everybody else's events. Only active ones
        count: an endpoint switched off by the failure rule, and a deleted
        one, hold no slot. Free a slot with `DELETE /v1/webhooks/{id}`.
      operationId: createWebhook
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url, events]
              properties:
                url: { type: string, format: uri }
                events:
                  type: array
                  items: { $ref: "#/components/schemas/WebhookEvent" }
            examples:
              basic:
                value:
                  url: https://example.com/hooks/nrg
                  events: [order.ready, order.completed, order.failed, deposit.credited]
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/WebhookEndpoint"
                  - type: object
                    required: [secret]
                    properties:
                      secret:
                        type: string
                        description: Shown only once
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }

  /webhooks/{webhook_id}:
    patch:
      tags: [Account]
      summary: Change a webhook
      description: |
        Change the address, the subscription, or both. **The signing secret
        does not change and is not returned here** — that is what this request
        is for.

        Without it an edit meant `DELETE` + `POST`: a new endpoint id and a
        new secret, which you have to deploy on your side *before* the next
        event arrives, because the old one is never shown twice. Adding one
        event to a subscription cost a release.

        Send either of `url` and `events`, or both; an omitted field is left
        as it is. An empty body is `400` rather than a quiet "nothing
        changed".

        `url` is checked exactly as at registration: `https` only, no
        credentials in the address, a public host only, and no ASCII control
        character anywhere in the string. A check that stands only at
        registration is a check the second request walks past.

        A switched-off endpoint (`status: disabled`) is not edited: `400` with
        `details.reason = endpoint_disabled`. You cannot switch it back on
        yourself; we do, and we decide by reading `disabled_at` and
        `disabled_reason` against the address the endpoint carries — an edit
        would change the address without clearing the cause. Write to support
        and name the new address in the same message. A deleted endpoint, like
        somebody else's, is `404`.
      operationId: updateWebhook
      parameters:
        - name: webhook_id
          in: path
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              # Both fields are optional; only what is sent changes. An empty
              # body is **not** a legal no-op here, unlike a maintenance rule:
              # there is nothing to answer it with but the endpoint as it
              # already was, and the way a client arrives at that body is by
              # building it out of a field name this route does not have.
              properties:
                url:
                  anyOf:
                    - { type: string, format: uri }
                    - type: "null"
                events:
                  anyOf:
                    - type: array
                      items: { $ref: "#/components/schemas/WebhookEvent" }
                    - type: "null"
            examples:
              moved:
                summary: The receiver moved to another address
                value:
                  url: https://example.com/hooks/nrg-v2
              subscribed:
                summary: One more event, same address, same secret
                value:
                  events: [order.ready, order.completed, order.failed, deposit.credited]
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookEndpoint" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
    delete:
      tags: [Account]
      summary: Delete a webhook
      description: |
        The endpoint stops receiving events and disappears from the list.
        The history of deliveries already sent to it is retained on our
        side. Deleting again returns `404`: a deleted endpoint is
        indistinguishable from one that never existed.
      operationId: deleteWebhook
      parameters:
        - name: webhook_id
          in: path
          required: true
          schema: { type: string }
      responses:
        "204": { description: Deleted }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }

  /webhooks/{webhook_id}/deliveries:
    get:
      tags: [Account]
      summary: Delivery log
      description: |
        Every attempt made against this endpoint, newest first: the event,
        its `event_id`, the status, the number of attempts, the status code
        the receiver answered with and the error text.

        This is the answer to "why did the event not arrive". An empty
        `response_status` means there was no answer at all — a timeout, DNS,
        a dropped connection; that is a separate fact, not a zero.

        `event_id` is the same value that went out in the body and in the
        `X-NRG-Event-Id` header, so a row here lines up with a row in your
        own log without guessing by timestamp.
      operationId: listWebhookDeliveries
      parameters:
        - name: webhook_id
          in: path
          required: true
          schema: { type: string }
        - $ref: "#/components/parameters/Cursor"
        - $ref: "#/components/parameters/Limit"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/WebhookDelivery" }
                  next_cursor: { type: string, nullable: true }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }

  /webhooks/{webhook_id}/deliveries/{delivery_id}/retry:
    post:
      tags: [Account]
      summary: Replay a delivery
      description: |
        Puts the delivery back in the queue — **and resets the attempt
        counter**: the retry schedule is computed from it, so without the
        reset a replayed delivery would get one attempt instead of five.

        **`event_id` does not change.** The copy arrives carrying the same
        identifier as the original, so a receiver that already processed the
        event recognises it and drops the duplicate.

        The sending is done by the delivery worker, not by this request: the
        next pass picks the row up. `204` means "queued", not "delivered" —
        read the outcome from the delivery log.

        A delivery the receiver already accepted is not replayed (`400`):
        that is not "send it again", it is a duplicate broadcast on one
        request.

        A `webhook.test` row is not replayed either (`400`). A probe has no
        retry ladder, so "the full five attempts" is not a thing that can be
        restored for one, and a queued copy would answer nothing to whoever
        pressed the button. Ask the receiver again with
        `POST /webhooks/{webhook_id}/test`, which waits for the answer and
        hands it back.
      operationId: retryWebhookDelivery
      parameters:
        - name: webhook_id
          in: path
          required: true
          schema: { type: string }
        - name: delivery_id
          in: path
          required: true
          schema: { type: string }
      responses:
        "204": { description: Queued }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }

  /webhooks/{webhook_id}/test:
    post:
      tags: [Account]
      summary: Send a test event
      description: |
        Sends the endpoint a `webhook.test` event and answers with what came
        of it: whether the receiver accepted it, what status code it
        answered with, what got in the way. No order is created and no money
        moves.

        **It is the real delivery path**, not a rehearsal of one: the same
        secret, the same signature, the same headers, the same `event_id`
        taken from the same table, the same 5-second budget for your answer,
        and the row stays in the delivery log beside the rest. A probe that
        waited less than a real delivery does would report a receiver as
        failed while your live events were reaching it.

        No subscription is needed: the probe goes to the endpoint named in
        the path whatever its `events` are — a receiver that does not work
        yet has nothing to subscribe to. For the same reason `webhook.test`
        cannot be subscribed to: it is not in the event list, so a handler
        that switches on the event name cannot mistake a probe for a real
        event.

        Exactly one attempt is made — a probe answers "does it accept right
        now", and there is no retry ladder for it. Its failures neither count
        towards the automatic disabling of the endpoint nor trigger the
        check, and the row it leaves cannot be replayed: ask again with this
        same call.

        A `disabled` endpoint is refused (`400`) and nothing is sent. We
        deliver nothing to such an endpoint, so there is no question about
        your receiver to answer; `GET /webhooks` is where that state shows.
        A probe that could not leave us at all is a `500` for the same
        reason, and leaves no row: `delivered: false` means your receiver
        was asked and did not accept, never that we failed to ask.

        If the request is cut short — you disconnect, or we restart mid-trip
        — the row is left `failed` with `last_error: probe_result_unknown`.
        Your receiver may or may not have been called; nobody found out, and
        nothing will retry it. Ask again with this same call.
      operationId: sendTestWebhook
      parameters:
        - name: webhook_id
          in: path
          required: true
          schema: { type: string }
      responses:
        "200":
          description: The probe was attempted; the body says how it went
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WebhookTestResult" }
              examples:
                accepted:
                  value:
                    delivery_id: "1841"
                    event_id: 0f0f6b1e-4a1e-4a5f-9b8a-2f5f0d9c1a77
                    event: webhook.test
                    delivered: true
                    response_status: 200
                    error: null
                refused:
                  value:
                    delivery_id: "1842"
                    event_id: 6d2f1c0a-7e3b-4f4e-b1a4-9c0e2d3f5a10
                    event: webhook.test
                    delivered: false
                    response_status: 502
                    error: HTTP 502
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
        "500":
          description: |
            The probe never left us — a fault on our side, and nothing about
            your receiver. No row is written and nothing was sent.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /auto-refill-rules:
    get:
      tags: [Maintenance]
      summary: List auto-refill rules
      operationId: listAutoRefillRules
      parameters:
        - $ref: "#/components/parameters/Cursor"
        - $ref: "#/components/parameters/Limit"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/MaintenanceRule" }
                  next_cursor: { type: string, nullable: true }
        "401": { $ref: "#/components/responses/Unauthorized" }
    post:
      tags: [Maintenance]
      summary: Create an auto-refill rule
      description: |
        "Keep energy on this wallet": after every spend it is topped up, so
        no separate order per transfer is needed. Idling costs almost
        nothing — no spend, no top-ups.

        The daily budget is mandatory: it is the rule's spending cap per
        UTC day; a hold for it is placed from the available balance,
        spending is drawn from the hold, and the remainder is released at
        the day boundary.

        You are charged for every top-up **confirmed on-chain**, at the
        `GET /tariff` price in effect at the moment of confirmation.

        The address must be activated and must not be a contract. Only one
        active rule may exist per (account, address) pair.

        `201` means the **daily hold is in place**, not merely that the
        rule was recorded: a rule without a hold is an unbacked promise
        to spend.
      operationId: createAutoRefillRule
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/MaintenanceRuleCreate" }
            examples:
              wallet:
                value:
                  address: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9
                  daily_budget_trx: "20.000000"
      responses:
        "201":
          description: Rule created, daily hold placed
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MaintenanceRule" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402":
          description: Available balance does not cover the daily budget
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: An active rule for this address already exists
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: |
            The address is well-formed, but a rule cannot be created on it,
            the budget does not cover top-ups, or as many rules already
            exist as are allowed. The specific reason is in
            `details.reason`: `inactive_wallet` (the wallet is not
            activated — there is nowhere to delegate energy to),
            `contract_wallet` (a contract: its energy consumption works
            differently), `rules_limit_reached` (with `limit` and the
            current `current` there),
            `budget_below_topup_price` (the daily budget is below the
            `double` rate — even the rule's first top-up would not fit
            into it; the minimum is in `details.min_daily_budget_trx`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /auto-refill-rules/{rule_id}:
    get:
      tags: [Maintenance]
      summary: Get a rule
      operationId: getAutoRefillRule
      parameters:
        - $ref: "#/components/parameters/RuleId"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MaintenanceRule" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
    patch:
      tags: [Maintenance]
      summary: Update a rule
      description: |
        `status` (`active` ↔ `paused`) and the daily budget can be changed.
        A rule stopped due to `insufficient_balance` is resumed only by
        this request — it never turns back on silently.

        Both changes account for **what is already spent today**: the hold
        is re-placed for `budget − spent`, not the full budget — otherwise
        a pause and resume would reset the daily cap. A budget lowered
        below what is already spent closes the hold: the rule spends
        nothing until the end of the UTC day.

        **A pause returns the rest of the daily hold a few minutes later
        rather than at once.** The rule stops at once, but when it has a
        live daily hold and its wallet is connected, the hold stays until
        the network has been read past the moment of the pause (typically
        4–5 minutes, at most an hour). A top-up delivered before the pause,
        or in the seconds right after it for a spend made while the rule
        was running, is charged from that hold like any other — a `charge`
        in `GET /ledger` and a `maintenance.topup` event; nothing delivered
        later is charged to the paused rule. A pause never charges for
        connecting the wallet. Resumed before the hold comes back, the rule
        carries on with the same hold; deleted while it waits, the wait goes
        on under the deletion's rules, from the moment of the pause.

        Budget bounds are the same as at creation: below the price of a
        single top-up — `422` with
        `details.reason = budget_below_topup_price`.
      operationId: updateAutoRefillRule
      parameters:
        - $ref: "#/components/parameters/RuleId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/MaintenanceRulePatch" }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MaintenanceRule" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402":
          description: Resuming requires the daily hold, and the balance does not cover it
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404": { $ref: "#/components/responses/NotFound" }
        "422":
          description: |
            The daily budget is below the `double` rate
            (`details.reason = budget_below_topup_price`; the minimum is
            in `details.min_daily_budget_trx`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    delete:
      tags: [Maintenance]
      summary: Delete a rule
      description: |
        The rule stops operating, and the remainder of the daily hold is
        released. The charge history is retained. Deleting again returns
        `404`.

        **The remainder may come back a few minutes later rather than at
        once.** The rule is deleted immediately — `404` from then on, gone
        from the list, its address free for a new rule. But when it still
        has a live daily hold and its wallet is connected, the hold stays
        until the network has been read past the moment of deletion
        (typically 4–5 minutes, at most an hour). A top-up delivered before
        the deletion, or in the seconds right after it for a spend made
        while the rule was running, is charged from that hold like any
        other — a `charge` in `GET /ledger` and a `maintenance.topup` event
        with the deleted rule's `rule_id`; nothing delivered later is
        charged to it. Then the rest is released. A rule whose hold for the
        day is used up, or a paused rule whose hold has already come back,
        has nothing to wait with and is settled at once, but for a supplier
        prepayment still in progress (below); a paused rule whose
        hold still waits keeps waiting, from the moment of the pause. If what the rule still owes for connecting the
        wallet (below) is more than that hold, the difference is reserved
        from the available balance at the `DELETE` — the hold is released
        and placed again, larger by it; when the available balance cannot
        cover it, the deletion is refused with `402 insufficient_balance`
        and nothing changes.

        **A rule deleted before charges have covered what the supplier was
        paid for its wallet pays the difference.** The first pass that
        finds the wallet short of a full top-up connects it with the supplier,
        paid for up front; a wallet that already holds a full top-up is
        connected after its first spend. The difference is the supplier cost
        paid under this rule less what this rule was charged, but no more
        than the supplier cost paid for the wallet less what all rules of
        the wallet were charged (costs and charges from 2026-11-06 on). A
        prepayment for the rule that is still in progress at the `DELETE`
        counts at its expected cost, in the `402` check too, and that much
        stays held after the `DELETE` until the supplier answers: its actual
        cost is then charged from it and the rest released, or all of it is
        released if the prepayment did not go through. The difference
        is charged before the rest of the hold
        is released: from the rule's daily hold first, then from the
        available balance. When the two together do not cover it, the
        deletion is refused with `402 insufficient_balance` and the rule
        stays as it was; `details.required_trx` is the part due from the
        available balance. It shows in `GET /ledger` as a `charge` (from the
        available balance, with a `hold` of the same amount) and is not
        refundable. Pausing a rule charges nothing by itself.
      operationId: deleteAutoRefillRule
      parameters:
        - $ref: "#/components/parameters/RuleId"
      responses:
        "204": { description: Deleted }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402":
          description: |
            The rule's supplier cost is not yet covered by its charges, and
            its daily hold plus the available balance do not cover the
            difference — a supplier prepayment still in progress counting at
            its expected cost. Nothing is charged and the rule stays as it was;
            `details.required_trx` is the part due from the available balance.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404": { $ref: "#/components/responses/NotFound" }

  # Alias of the canonical `/auto-refill-rules` — the path the resource
  # originally shipped under. Same handlers, same responses; works until
  # 2026-12-01, responding with `Deprecation: true` and `Sunset` headers.
  # After that date the path is gone.
  /maintenance-rules:
    get:
      tags: [Maintenance]
      summary: List auto-refill rules (deprecated path)
      description: |
        **Deprecated path.** The canonical one is `/auto-refill-rules`;
        this alias responds identically and works until 2026-12-01, marking
        successful responses with `Deprecation` and `Sunset` headers.
      operationId: listMaintenanceRules
      deprecated: true
      parameters:
        - $ref: "#/components/parameters/Cursor"
        - $ref: "#/components/parameters/Limit"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/MaintenanceRule" }
                  next_cursor: { type: string, nullable: true }
        "401": { $ref: "#/components/responses/Unauthorized" }
    post:
      tags: [Maintenance]
      summary: Create an auto-refill rule (deprecated path)
      description: |
        **Deprecated path.** The canonical one is `/auto-refill-rules`;
        this alias responds identically and works until 2026-12-01, marking
        successful responses with `Deprecation` and `Sunset` headers.
      operationId: createMaintenanceRule
      deprecated: true
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/MaintenanceRuleCreate" }
      responses:
        "201":
          description: Rule created, daily hold placed
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MaintenanceRule" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402":
          description: Available balance does not cover the daily budget
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: An active rule for this address already exists
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: The rule cannot be created; the specific reason is in `details.reason`
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /maintenance-rules/{rule_id}:
    get:
      tags: [Maintenance]
      summary: Get a rule (deprecated path)
      description: |
        **Deprecated path.** The canonical one is
        `/auto-refill-rules/{rule_id}`; this alias responds identically and
        works until 2026-12-01, marking successful responses with
        `Deprecation` and `Sunset` headers.
      operationId: getMaintenanceRule
      deprecated: true
      parameters:
        - $ref: "#/components/parameters/RuleId"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MaintenanceRule" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
    patch:
      tags: [Maintenance]
      summary: Update a rule (deprecated path)
      description: |
        **Deprecated path.** The canonical one is
        `/auto-refill-rules/{rule_id}`; this alias responds identically and
        works until 2026-12-01, marking successful responses with
        `Deprecation` and `Sunset` headers.
      operationId: updateMaintenanceRule
      deprecated: true
      parameters:
        - $ref: "#/components/parameters/RuleId"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/MaintenanceRulePatch" }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MaintenanceRule" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402":
          description: Resuming requires the daily hold, and the balance does not cover it
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404": { $ref: "#/components/responses/NotFound" }
        "422":
          description: The daily budget is below the `double` rate
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    delete:
      tags: [Maintenance]
      summary: Delete a rule (deprecated path)
      description: |
        **Deprecated path.** The canonical one is
        `/auto-refill-rules/{rule_id}`; this alias responds identically and
        works until 2026-12-01, marking successful responses with
        `Deprecation` and `Sunset` headers.
      operationId: deleteMaintenanceRule
      deprecated: true
      parameters:
        - $ref: "#/components/parameters/RuleId"
      responses:
        "204": { description: Deleted }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402":
          description: |
            The rule's supplier cost is not yet covered by its charges, and
            its daily hold plus the available balance do not cover the
            difference — a supplier prepayment still in progress counting at
            its expected cost. Nothing is charged and the rule stays as it was;
            `details.required_trx` is the part due from the available balance.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404": { $ref: "#/components/responses/NotFound" }

  /queue-sessions:
    get:
      tags: [Queue]
      summary: List queue sessions
      description: |
        Your queue sessions, newest first. `status` and `from` narrow the
        list; pagination is cursor-based like `GET /orders`.

        Answers `404 not_found` — like every `/queue-sessions` path — while
        queue mode is switched off for your account. It is on for every
        account by default; contact support if it has been switched off for
        yours.
      operationId: listQueueSessions
      parameters:
        - name: status
          in: query
          schema: { $ref: "#/components/schemas/QueueSessionStatus" }
        - name: from
          in: query
          description: Only sessions on this sender wallet
          schema: { $ref: "#/components/schemas/TronAddress" }
        - $ref: "#/components/parameters/Cursor"
        - $ref: "#/components/parameters/Limit"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/QueueSession" }
                  next_cursor: { type: string, nullable: true }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
        "429": { $ref: "#/components/responses/RateLimited" }
    post:
      tags: [Queue]
      summary: Create a queue session
      description: |
        A queue session on one sender wallet: a target level of free energy
        and either an ordered list of the USDT transfers you are about to
        send from it (`items`) or just how many are coming
        (`expected_transfers`). Nothing is bought and nothing is reserved
        yet — the session is `created`; `POST /queue-sessions/{session_id}/start`
        places the hold and starts buying (`api-spec.md` §12).

        From Start, the session keeps the wallet at `target_units` of free
        energy by buying the cheapest five-minute energy packet by packet:
        a packet your transfer consumed is replaced on the next pass, a
        packet about to expire is replaced before it expires, and towards
        the end of the list the level shrinks to what is left to send —
        nothing is bought for an empty list. It pauses by itself when the
        wallet's USDT balance no longer covers the next transfer and resumes
        by itself when it does; it completes when the queue is exhausted.
        You are charged **only for packets whose delivery is seen
        on-chain**, at the packet's price, and each charge arrives as a
        `queue.packet_delivered` event — energy delivered to your wallet is
        paid whether or not you spent it, so press Stop when you stop
        sending. A packet's price is the five-minute tariff price of the
        moment of purchase, or more when the vendor selling that packet
        costs more than the tariff leaves our minimum margin under: then the
        lowest whole-sun price that covers that cost with the margin. A
        vendor whose packet would cost above a fixed multiple of the tariff
        is not bought from. The packet is bought only when the session's
        hold, topped up from your available balance, covers it at that
        price; otherwise the session pauses `hold_exhausted`.

        `items` may be empty: append with `POST /queue-sessions/{session_id}/items`
        at any time before the session completes or is stopped. Transfers
        are matched to items in queue order by recipient; an item at the
        head of the queue that is not seen sent within the skip window is
        skipped and never blocks the ones behind it.

        With `expected_transfers` there is no list: every outgoing USDT
        transfer of the wallet after Start counts as one of them, the level
        is sized by what a transfer of this wallet has been costing (its
        recent history; a transfer to an empty address until there is any),
        the USDT-balance pause does not apply, and items cannot be appended
        — create another session for more. `items` and `expected_transfers`
        together are `400 invalid_request` with
        `details.reason = items_or_expected_transfers`; a count outside
        `1…` the per-session ceiling is `400 invalid_request` with
        `details.reason = expected_transfers_out_of_range`.

        Checks, in this order: the body (`target_units` within bounds,
        `amount_usdt` a positive decimal with at most six places, at most
        500 items) → `400 invalid_request`; every address well-formed →
        `400 invalid_address` with `details.index` of the first bad one;
        then, before anything is asked of the chain, the available balance
        covering one transfer's energy at the five-minute price
        → `402 insufficient_balance` (nothing is reserved here — the
        reserve is Start's, and Start's own `402` is still the one that
        asks for it — this only refuses an account that could not pay for a
        single transfer) and room in the account's node budget for the
        sender and every item → `429 rate_limited` (see "Rate limits"); the
        sender usable — activated, not a contract, not on the USDT
        blacklist → `422 invalid_address` with `details.reason` =
        `inactive_wallet` / `contract_wallet` / `blacklisted_wallet`; no
        recipient on the USDT blacklist → `422 blacklisted_recipient` with
        `details.index`; fewer live sessions than your account allows →
        `422 invalid_request` with `details.reason = sessions_limit_reached`;
        the wallet not kept by a session of another account →
        `409 wallet_busy`; no live (`created`, `running` or `paused`) session
        of yours on this wallet already → `409 queue_session_active`.

        One account at a time keeps a wallet in queue mode: deliveries are
        matched to the session that reads the wallet, and two accounts on one
        wallet could not be told apart. A session that is `running` or
        `paused`, or `stopped` but still settling its last packets, keeps the
        wallet until it is settled. `wallet_busy` tells you only that some
        other queue session uses the wallet — never whose, nor in what
        state. A `created` session keeps nothing — Start is where the
        wallet is taken. If several of your accounts stand behind one
        treasury wallet, run queue sessions on it from one account at a
        time; orders from a shared wallet are accepted as before.

        `Idempotency-Key` is required and behaves exactly as on
        `POST /orders`: a byte-identical retry returns the original session
        with the same `201`, the same key with a different body is
        `409 idempotency_conflict`, and a request refused by validation does
        not consume the key.
      operationId: createQueueSession
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/QueueSessionCreate" }
            examples:
              with_items:
                summary: A wallet, the default target and the first three payments
                value:
                  from: TQ5NMqJjW8sBGqcpvUcXhbXm3jGnyDCmwK
                  items:
                    - { to: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9, amount_usdt: "120.50" }
                    - { to: TLa2f6VPqDgRE67v1736s7bJ8Ray5wYjU7, amount_usdt: "1000" }
                    - { to: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9, amount_usdt: "35.000000" }
              empty:
                summary: A session to append to later, with a higher target
                value:
                  from: TQ5NMqJjW8sBGqcpvUcXhbXm3jGnyDCmwK
                  target_units: 2000000
      responses:
        "201":
          description: Session created; nothing reserved until Start
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QueueSession" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402":
          description: |
            `insufficient_balance` — the available balance does not cover one
            transfer's energy at the five-minute price, so the
            session could not pay for anything. Checked before the
            chain is asked about the addresses; `required_trx` is that one
            transfer's price, `available_trx` what you have. Nothing is
            reserved and the `Idempotency-Key` is not consumed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: |
            `queue_session_active` — a `created`, `running` or `paused`
            session of yours already exists on this wallet; stop it or reuse
            it. `wallet_busy` — a session of another account keeps this
            wallet; `details` names only the wallet (`from`). Try again once
            it ends, or use another wallet. `idempotency_conflict` — the same
            `Idempotency-Key` with a different body.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: |
            The sender is well-formed but cannot be served, a recipient is
            on the USDT blacklist, or the account is at its session limit.
            `details.reason` says which: `inactive_wallet`,
            `contract_wallet`, `blacklisted_wallet` (the sender), or
            `sessions_limit_reached` (with `limit`); `blacklisted_recipient`
            is its own code, with `details.index` of the item.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /queue-sessions/{session_id}:
    get:
      tags: [Queue]
      summary: Get a queue session
      description: |
        The session with its counters, the head of the queue (`next_item`)
        and the last uncached readings of the wallet — free energy and USDT
        balance, each with the time it was taken. A session belonging to
        another account is `404`, the same as a session that does not exist.
      operationId: getQueueSession
      parameters:
        - $ref: "#/components/parameters/QueueSessionId"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QueueSession" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /queue-sessions/{session_id}/items:
    get:
      tags: [Queue]
      summary: List the session's items
      description: |
        The queue in sending order (`seq` ascending), cursor-paginated;
        `status` narrows it to `pending`, `sent` or `skipped` items.
      operationId: listQueueItems
      parameters:
        - $ref: "#/components/parameters/QueueSessionId"
        - name: status
          in: query
          schema: { $ref: "#/components/schemas/QueueItemStatus" }
        - $ref: "#/components/parameters/Cursor"
        - $ref: "#/components/parameters/Limit"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/QueueItem" }
                  next_cursor: { type: string, nullable: true }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
        "429": { $ref: "#/components/responses/RateLimited" }
    post:
      tags: [Queue]
      summary: Append items to the queue
      description: |
        Appends 1 to 500 transfers to the end of the queue, in the order of
        the body; they get the next `seq` numbers. Allowed while the session
        is `created`, `running` or `paused`; a `completed` or `stopped`
        session answers `409 queue_session_closed`. A session created with
        `expected_transfers` has no list to append to and answers
        `422 invalid_request` with `details.reason = session_without_items`
        — create another session for more transfers.

        Recipients are checked the same way as at creation: well-formed →
        else `400 invalid_address` with `details.index`; then, before the
        chain is asked, the balance gate of creation while the session is
        still `created` (`402 insufficient_balance` — a started session
        holds its reserve and is not asked for spare money) and room in the
        node budget for every item (`429 rate_limited`); not on the USDT
        blacklist → else `422 blacklisted_recipient` with `details.index`.
        The queue has a ceiling per session; past it the append is
        `422 invalid_request` with `details.reason = items_limit_reached`.

        `Idempotency-Key` is required, with the `POST /orders` semantics: a
        byte-identical retry returns the original result — `added` as it
        was, the counters as they are now — and does not append again.
      operationId: appendQueueItems
      parameters:
        - $ref: "#/components/parameters/QueueSessionId"
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/QueueItemsAppend" }
            examples:
              two_more:
                value:
                  items:
                    - { to: TLa2f6VPqDgRE67v1736s7bJ8Ray5wYjU7, amount_usdt: "250" }
                    - { to: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9, amount_usdt: "12.75" }
      responses:
        "201":
          description: Items appended
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QueueItemsAppended" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402":
          description: |
            `insufficient_balance` — the session is still `created` (nothing
            reserved) and the available balance does not cover one transfer's
            energy at the five-minute price. Checked before the
            chain is asked about the recipients. A started session is never
            refused this way: its reserve is already in place.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: |
            `queue_session_closed` — the session is `completed` or
            `stopped`; open a new one. `idempotency_conflict` — the same
            `Idempotency-Key` with a different body.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: |
            A recipient is on the USDT blacklist (`blacklisted_recipient`,
            `details.index`), or the session is at its item ceiling
            (`invalid_request`, `details.reason = items_limit_reached`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /queue-sessions/{session_id}/start:
    post:
      tags: [Queue]
      summary: Start the session
      description: |
        `created → running`. Places the session's hold — the target's worth
        of five-minute energy at today's price, times a safety multiplier,
        reserved from your available balance like an order hold — and starts
        buying. `hold_trx` in the response is what was reserved; it is
        topped up from your balance as packets are charged against it and
        the unused remainder is released when the session ends.

        Idempotent on a session that is already `running` or `paused`: `200`
        with the session unchanged. A `completed` or `stopped` session cannot
        be restarted — `409 queue_session_closed`; create a new one. The
        wallet kept by a session of another account — `409 wallet_busy`,
        checked before the hold: nothing is reserved, the session stays
        `created`, and Start can be repeated once the wallet is free. Not
        enough available balance for the hold — `402 insufficient_balance`
        with `required_trx` and `available_trx`; the session stays
        `created`, and Start can be repeated after a deposit.
      operationId: startQueueSession
      parameters:
        - $ref: "#/components/parameters/QueueSessionId"
      responses:
        "200":
          description: Running (or already running / paused)
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QueueSession" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402":
          description: Available balance does not cover the session hold
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: |
            `queue_session_closed` — the session is `completed` or `stopped`.
            `wallet_busy` — a session of another account keeps this wallet
            (`running`, `paused`, or `stopped` and still settling); nothing
            was reserved, and `details` names only the wallet (`from`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /queue-sessions/{session_id}/stop:
    post:
      tags: [Queue]
      summary: Stop the session
      description: |
        `created | running | paused → stopped`: buying stops with this call.
        Energy already delivered stays on the wallet until its lease ends
        and is not refunded — it was delivered — and packets bought a moment
        ago are still settled: each one confirmed on-chain is charged and
        reported by `queue.packet_delivered` after the stop, and the unused
        part of the hold is released once the last of them is settled.

        Idempotent on a `stopped` session: `200` unchanged. A `completed`
        session answers `409 queue_session_closed` — there is nothing left
        to stop.
      operationId: stopQueueSession
      parameters:
        - $ref: "#/components/parameters/QueueSessionId"
      responses:
        "200":
          description: Stopped (or already stopped)
          content:
            application/json:
              schema: { $ref: "#/components/schemas/QueueSession" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: "`queue_session_closed` — the session is `completed`"
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /address-book:
    get:
      tags: [Address book]
      summary: List address book entries
      description: |
        Your saved addresses, ordered by name (case-insensitive), then by
        `id`. Only active entries are ever returned. Each entry carries
        `usage` — what this account did with the address — computed when
        you read it, so it is the same for an address deleted and saved
        again.

        Filters combine: `q` is a case-insensitive fragment of the name, of
        any tag, or of the address; `tag` may be repeated, and an entry must
        carry **every** tag named. A `tag` value matches the tags your book
        holds under the same identity the book stores them by (Unicode case
        folding, see `POST`), and a value your book has no such tag for
        matches nothing. At most ten `tag` values: an entry carries no more
        than ten tags. `address` may be repeated, up to
        50 times, and narrows the list to the entries with **exactly** these
        addresses; an address your book does not hold is simply absent from
        the answer, not an error. A value that is not a valid TRON address is
        `400 invalid_address`; more than 50 is `400 invalid_request`. Order
        and pagination are the same with or without it — reading the
        network's facts for rows you already show is
        `address=…&address=…&include=chain`.

        **`include=chain`** adds the network's facts about each address —
        the same ones `GET /address-check` gives, minus the address. The page
        is then at most 50 entries (a larger `limit` is
        `400 invalid_request`, which costs only the request's own token).

        **It is priced like `POST /estimate`:** besides the request's own
        token, each address of the page that our short-lived address cache
        does not hold costs one more token of the reference bucket; a cached
        address is free, so repeating the same read at once costs one token.
        The charge is taken before anything is asked of the chain. A request
        the bucket cannot pay for is refused whole — `429 rate_limited`, no
        list — with a `Retry-After` that is the time until the bucket is full
        again (the same as `RateLimit-Reset`); after it the same request
        passes, provided the key spends nothing else from the bucket
        meanwhile. To get the list without paying for the facts, ask without
        `include=chain`. The `RateLimit-*` headers of a success describe the
        reference bucket after both charges.

        If the network cannot be read, the list is **not** refused: every
        entry comes back with `chain: null`, and `chain_unavailable` is
        `true`. Without `include=chain`, `chain` is always `null` and
        `chain_unavailable` always `false`.
      operationId: listAddressBookEntries
      parameters:
        - name: q
          in: query
          schema: { type: string }
        - name: tag
          in: query
          style: form
          explode: true
          schema:
            type: array
            items: { type: string }
            maxItems: 10
        - name: address
          in: query
          style: form
          explode: true
          schema:
            type: array
            items: { $ref: "#/components/schemas/TronAddress" }
            minItems: 1
            maxItems: 50
        - name: include
          in: query
          schema: { type: string, enum: [chain] }
        - $ref: "#/components/parameters/Cursor"
        - $ref: "#/components/parameters/Limit"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor, chain_unavailable]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/AddressBookEntry" }
                  next_cursor: { type: string, nullable: true }
                  chain_unavailable:
                    type: boolean
                    description: |
                      `true` only when `include=chain` was asked and the
                      network could not be read; every entry then has
                      `chain: null`.
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "429": { $ref: "#/components/responses/RateLimited" }
    post:
      tags: [Address book]
      summary: Save an address
      description: |
        Gives an address a name, an optional note and up to ten tags. One
        active entry per address: saving an address that is already in the
        book is `409 address_book_conflict` with
        `details.reason = address_already_saved` and the existing entry in
        `details.id` — edit that one instead.

        **Tags are case-insensitive**, by Unicode default case folding:
        `exchanges` and `Exchanges` are one tag, and so are `ΟΔΟΣ` and
        `οδος`, or `STRASSE` and `straße`. No language-specific rule is
        applied: `İstanbul` and `istanbul` are two tags. A tag repeated in
        another case within the body keeps its first spelling, and a tag your
        book already uses is stored in the spelling the book already has.

        The book holds at most 2000 active entries and 200 distinct tags.
        Past either, `409 address_book_conflict` with
        `details.reason = entries_limit_reached` or `tags_limit_reached`,
        and `details.limit` and `details.current`. Deleted entries count
        towards neither.

        A malformed address is `400 invalid_address`; a name, note or tag
        out of bounds, or carrying text that cannot be stored — a NUL
        character (`\u0000`) or a lone UTF-16 surrogate (an unpaired
        `\ud800`–`\udfff` escape) — is `400 invalid_request` with
        `details.errors`. An empty or blank `note` is stored as `null`.
      operationId: createAddressBookEntry
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AddressBookEntryCreate" }
            examples:
              payroll:
                value:
                  address: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9
                  name: Payroll hot wallet
                  tags: [Staff, Hot]
      responses:
        "201":
          description: Saved
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AddressBookEntry" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "409":
          description: |
            `address_book_conflict`. `details.reason`:
            `address_already_saved` (with `id`), `entries_limit_reached` or
            `tags_limit_reached` (with `limit` and `current`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /address-book/{entry_id}:
    patch:
      tags: [Address book]
      summary: Edit an entry
      description: |
        Only the fields you send change. `tags` replaces the whole array
        (`[]` removes every tag); `note: null` clears the note. `name` and
        `tags` may be omitted but not sent as `null`. The address is not
        editable: `address` in this body is ignored, like any key the body
        does not define — a name for another address is another entry. An
        empty body is a legal no-op and returns the entry as it is.

        Tags follow the same rules as on `POST`, and so does the tag
        ceiling: a new tag past 200 distinct ones is
        `409 address_book_conflict`, `details.reason = tags_limit_reached`.
        A deleted entry, like another account's, is `404`.
      operationId: updateAddressBookEntry
      parameters:
        - name: entry_id
          in: path
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AddressBookEntryUpdate" }
            examples:
              retag:
                summary: New tags, same name
                value:
                  tags: [Staff, Cold]
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AddressBookEntry" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: "`address_book_conflict`, `details.reason = tags_limit_reached`"
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    delete:
      tags: [Address book]
      summary: Delete an entry
      description: |
        The entry leaves the book, and the address may be saved again at
        once. What the account did with the address is untouched: saved
        again, it shows the same `usage`. Deleting again returns `404`.
        A deleted entry is kept for the record, up to as many as the book
        holds live entries (2000); past that, the oldest deleted entries are
        removed for good.
      operationId: deleteAddressBookEntry
      parameters:
        - name: entry_id
          in: path
          required: true
          schema: { type: string }
      responses:
        "204": { description: Deleted }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }

  /address-book/import:
    post:
      tags: [Address book]
      summary: Import addresses
      description: |
        Saves up to 500 rows in one call. **Not atomic**: every row is
        judged on its own, valid rows are saved even when others fail, and
        each row gets a result at its `index` in the body — `created` (with
        the new entry's `id`), `exists` (with the `id` of the entry already
        saved for that address, which is left untouched) or `error` with a
        `reason`.

        A row follows the rules of `POST /address-book` — the same bounds,
        the same tag rules — and is judged in this order: its shape, field by
        field (`invalid_address`, `invalid_name`, `invalid_note`,
        `invalid_tags`; a NUL character or a lone surrogate in any of them
        is that field's error); then `duplicate_in_request` for every row after the first
        that names the same address (the first one is the row judged,
        whatever became of it); then `exists`; then the book's ceilings,
        counted with the rows this body has already saved:
        `entries_limit_reached` for every new address once the book is full,
        `tags_limit_reached` for a row that would bring a new tag past 200 —
        a later row that reuses the book's tags is still saved.

        Only the body as a whole can be refused: not an object with an
        `entries` list, an empty list, more than 500 rows, or a row that is
        not an object is `400 invalid_request`, and nothing is saved.

        **Priced by size.** Besides the request's own token, the body pays
        one more token of the reference bucket per started 25 rows past
        the first 25 — 500 rows cost 20 tokens, 26 cost 2, 25 or fewer cost 1. The charge is taken before anything is
        done; when the bucket cannot cover it the answer is `429` with a
        `Retry-After` after which the same body passes, and nothing is
        written. No body costs more than a full bucket.
      operationId: importAddressBookEntries
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AddressBookImport" }
            examples:
              two:
                value:
                  entries:
                    - address: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9
                      name: Payroll hot wallet
                      tags: [Staff]
                    - address: TJCnKsPa7y5okkXvQAidZBzqx3QyQ6sxMW
                      name: Cold storage
      responses:
        "200":
          description: Every row's result, in body order
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AddressBookImportResult" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /address-book/suggestions:
    get:
      tags: [Address book]
      summary: Addresses worth saving
      description: |
        Addresses from this account's own history — its order items (either
        side), queue sessions, queue items and auto-refill rules — that have
        no entry in the book. An address whose entry was deleted is suggested
        again. Your own deposit addresses are never suggested, and neither is
        anything from another account's history.

        Ordered by `orders_as_sender + orders_as_recipient` descending, then
        `last_used_at` descending. The counts and `last_used_at` mean what
        they mean in an entry's `usage`.
      operationId: listAddressBookSuggestions
      parameters:
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 50, default: 20 }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/AddressBookSuggestion" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /address-book/tags:
    get:
      tags: [Address book]
      summary: List the book's tags
      description: |
        Every tag in the book, once per tag (tags compare by Unicode case
        folding, as on `POST /address-book`) and in the book's spelling,
        with `count` — the number of entries carrying it. Deleted entries
        count for nothing: a tag that only they carried is not listed.
        Ordered case-insensitively, by that same folding.
      operationId: listAddressBookTags
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/AddressBookTag" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /address-book/tags/rename:
    post:
      tags: [Address book]
      summary: Rename a tag
      description: |
        Every entry carrying `from` gets `to` in its place, at the same
        position; `updated` is the number of entries changed. Both are
        matched case-insensitively, by Unicode case folding.

        - **Merge.** If `to` is already a tag of the book, the two become
          one: an entry carrying both keeps a single copy, and the book's
          existing spelling of `to` is kept — the rule of every write.
        - **Re-spelling.** `from` and `to` equal case-insensitively
          (`hot` → `HOT`) re-spells the tag on every entry carrying it,
          exactly as `to` is sent.

        `from` on no entry of the book is `404 not_found`. Both follow the
        rules of a tag (1–32 characters after trimming, no `,`, `|`, line
        break, NUL or lone surrogate); otherwise `400 invalid_request`.
      operationId: renameAddressBookTag
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AddressBookTagRename" }
            examples:
              merge:
                value: { from: Exchanges, to: Exchange }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AddressBookUpdated" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }

  /address-book/tags/delete:
    post:
      tags: [Address book]
      summary: Delete a tag
      description: |
        Takes the tag — in any case — off every entry carrying it; the
        entries themselves stay. `updated` is the number of entries changed.
        A tag on no entry of the book is `404 not_found`.
      operationId: deleteAddressBookTag
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AddressBookTagDelete" }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AddressBookUpdated" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }

  /address-book/bulk-tags:
    post:
      tags: [Address book]
      summary: Tag or untag many entries
      description: |
        Adds and removes tags on up to 500 entries at once. **`remove` is
        applied first, then `add`**: a tag named in both ends up on every
        listed entry — where it already stood on the entries that carried
        it, at the end on the others. Adding a tag an entry already carries
        (in any case), or removing one it does not carry, changes nothing
        and is not an error. An added tag the book already has is stored in
        the book's spelling. `updated` is the number of entries actually
        changed, not the number listed.

        **All or nothing.** Nothing is changed unless every check passes, in
        this order: an id that is not an active entry of your book (deleted,
        another account's, unknown) is `404 not_found`; an entry that would
        end with more than ten tags is `409 address_book_conflict` with
        `details.reason = entry_tags_limit_reached` and every such entry in
        `details.ids`; a new tag past the book's 200 distinct tags is `409`
        with `tags_limit_reached` — counted after the removals.

        At least one of `add` and `remove` must name a tag, and each carries
        at most ten items as sent — not only ten distinct ones. A malformed
        id is `400 invalid_request`.

        **Priced by size.** Besides the request's own token, the body pays
        one more token of the reference bucket per started 25 ids past
        the first 25 — 500 ids cost 20 tokens, 25 or fewer cost 1. The charge is taken before anything is
        done; when the bucket cannot cover it the answer is `429` with a
        `Retry-After` after which the same body passes, and nothing is
        written. No body costs more than a full bucket.
      operationId: bulkTagAddressBookEntries
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AddressBookBulkTags" }
            examples:
              retag:
                value:
                  ids: [0b6f2c1e-4a1e-4a5f-9b8a-2f5f0d9c1a77]
                  add: [Staff]
                  remove: [Contractors]
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AddressBookUpdated" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
        "429": { $ref: "#/components/responses/RateLimited" }
        "409":
          description: |
            `address_book_conflict`. `details.reason`:
            `entry_tags_limit_reached` (with `ids`) or `tags_limit_reached`
            (with `limit` and `current`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /address-book/bulk-delete:
    post:
      tags: [Address book]
      summary: Delete many entries
      description: |
        Deletes, in one transaction, every listed id that is an entry of your
        book — the same soft deletion as `DELETE /address-book/{entry_id}`:
        each address may be saved again at once, and its `usage` is
        unchanged.

        An id that is not an entry of your book — another account's, one
        already deleted, one that never existed — is **skipped without an
        error**, and the answer does not say which of the three it was. The
        call is therefore idempotent: repeating it after a lost answer
        deletes nothing twice. `deleted` counts the entries this call
        deleted. A repeated id counts once.

        A malformed id, or fewer than 1 or more than 500 ids, is
        `400 invalid_request`.

        **Priced by size.** Besides the request's own token, the body pays
        one more token of the reference bucket per started 25 ids past
        the first 25 — 500 ids cost 20 tokens, 25 or fewer cost 1. The charge is taken before anything is
        done; when the bucket cannot cover it the answer is `429` with a
        `Retry-After` after which the same body passes, and nothing is
        written. No body costs more than a full bucket.
      operationId: bulkDeleteAddressBookEntries
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AddressBookBulkDelete" }
            examples:
              two:
                value:
                  ids:
                    - 0b6f2c1e-4a1e-4a5f-9b8a-2f5f0d9c1a77
                    - 7c1d9e20-3b4a-4f2e-8d1c-5a6b7c8d9e0f
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AddressBookDeleted" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /health:
    get:
      tags: [Utility]
      summary: Service status
      security: []
      operationId: getHealth
      description: |
        `status` is the service as a whole: `degraded` means the API answers
        and orders are accepted while something behind it (cache, nodes) is
        not healthy.

        `components` is the same service split into the parts you can feel,
        each of them either `ok` or `down`. It is what our status page shows
        and it is safe to poll: no component is computed from anything you
        pay for.

        - `api` — requests are answered.
        - `orders` — an order can be created and will be fulfilled.
        - `delivery` — delegated energy is reaching the address.
        - `deposits` — deposits are being credited.

        A component whose state we cannot establish reads `down`, never the
        last known value.
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required: [status, time, components]
                properties:
                  status: { type: string, enum: [ok, degraded, down] }
                  time: { type: string, format: date-time }
                  components:
                    type: object
                    required: [api, orders, delivery, deposits]
                    properties:
                      api: { type: string, enum: [ok, down] }
                      orders: { type: string, enum: [ok, down] }
                      delivery: { type: string, enum: [ok, down] }
                      deposits: { type: string, enum: [ok, down] }

  /contract.yaml:
    get:
      tags: [Utility]
      summary: Machine-readable API contract
      description: |
        This document itself, byte for byte as it is written in our
        repository — the same file the documentation site renders. Fetch it
        with a program: generate a client from it, diff it in CI, vendor it.
        Public endpoint, no authorization required; rate limited by IP, since
        a public request carries no key.

        **This is not `/v1/openapi.json`.** That one is generated by the
        framework from the code running in this deployment, so it lags: it
        describes what has shipped. This one is written by hand and is the
        promise — it can describe an endpoint that goes live in the next
        release, and where the two disagree, this file is the one we are held
        to. Generate clients from this one. A mistyped extension
        (`/v1/contract.json`) is a `404` rather than the other document,
        which is why the two paths deliberately share no stem.

        Serve-from-the-API is the point of the endpoint: the copy on the
        documentation site sits behind an edge that answers some
        programmatic clients with a plain-text `403 error code: 1010` before
        anything of ours is reached (see "User-Agent" in the client docs).
        This URL is the API's own host and has no such rule in front of it.

        `ETag` is the SHA-256 of the body, so `sha256sum` of what you
        downloaded reproduces it; send it back as `If-None-Match` to get a
        `304` instead of the document. That works on every request and is the
        cheap way to poll for a change.

        The answer also carries `Cache-Control: public, max-age=300` — the
        document changes when we deploy, never between requests, so five
        minutes is how long a stored copy may outlive a release. One
        exception, and it is easy to hit by accident: a request carrying an
        `Authorization` header is answered `no-store` instead, because this
        API marks anything asked for with a key as private. This endpoint
        needs no key — fetch it with a plain client if you want the cacheable
        answer. With `ETag` it makes no practical difference.
      security: []
      operationId: getContract
      responses:
        "200":
          description: The contract, exactly as it stands in our repository.
          headers:
            ETag:
              description: SHA-256 of the body, in quotes.
              schema: { type: string }
            Content-Disposition:
              description: "`inline`, with a filename for browser downloads."
              schema: { type: string }
          content:
            application/yaml:
              schema:
                type: string
        "304":
          description: Your `If-None-Match` names the copy we would send.
        "429": { $ref: "#/components/responses/RateLimited" }
        "500":
          description: |
            This deployment does not carry the contract file — a packaging
            defect on our side, not something a retry fixes. The document is
            still on the documentation site.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  # Sandbox only. The path exists on `https://sandbox.nrg.market/v1` and
  # nowhere else: production carries no such route and answers `404`. It is
  # written here rather than in a separate document so that one contract
  # describes both hosts — the rest of this file applies to each of them
  # unchanged, and this is the whole of the difference.
  /sandbox/deposit:
    post:
      tags: [Sandbox]
      summary: Credit test TRX (sandbox only)
      description: |
        Puts test money on your sandbox balance, with no chain to wait for.

        The amount is credited **down the same path the deposit watcher uses
        in production**, so what you get is an ordinary deposit and not a
        special case: a `deposit` entry in `GET /ledger` carrying a txid of
        the form `sandbox-<uuid>`, the balance moved by that amount, and a
        real `deposit.credited` delivery to every endpoint subscribed to it.
        If your integration reacts to being funded, this is the call that
        exercises the reaction. As in production, an amount below 1 TRX is
        credited without `deposit.credited` — which is how to rehearse the
        silence too.

        A new account does not need it to start: activating a sandbox account
        — confirming the e-mail, or the first Google sign-in — grants
        10,000 TRX, which arrives as an `adjustment_credit`.

        Two limits: **100,000 TRX in one call** and **ten calls per client
        per UTC day**. An amount above the cap is refused the same way a
        malformed one is — `400 invalid_request`, with the field named in
        `details.errors`. The eleventh call of the day is `429 rate_limited`
        with `Retry-After`. That allowance is counted per day and separately
        from the per-minute buckets in "Rate limits", and the `RateLimit-*`
        headers on this endpoint describe it: a limit of 10 and a reset at
        the UTC day boundary, not a minute's worth of anything.

        **On production this path does not exist.** A `POST` to
        `https://api.nrg.market/v1/sandbox/deposit` answers `404 not_found`
        like any unknown path: it is absent there rather than disabled, and
        no key of any kind opens it.
      operationId: createSandboxDeposit
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [amount_trx]
              properties:
                amount_trx:
                  allOf: [{ $ref: "#/components/schemas/TRX" }]
                  description: |
                    How much test TRX to credit — the same string with six
                    decimal places as every other amount in this API.
                    Greater than zero and no more than `100000.000000`.
            examples:
              topup:
                summary: A thousand test TRX
                value:
                  amount_trx: "1000.000000"
      responses:
        "201":
          description: |
            Credited. The body is the ledger entry this call wrote, and it is
            the **same schema** `GET /ledger` returns its rows in — literally
            the same `LedgerRow`, so one parser reads both and rehearsing here
            exercises the type your code will meet in production.

            Three things are always true of a row from this endpoint, and they
            are said here rather than narrowed in the schema — a narrower
            schema would be a second shape, which is the divergence this
            wording exists to prevent:

            - `type` is `deposit`. The endpoint credits a deposit and nothing
              else, though the field can carry any of the seven ledger types.
            - `order_id` is `null`. A deposit belongs to no order.
            - `txid` matches `sandbox-<uuid>` — `sandbox-` followed by a dashed
              UUID. Shaped so a test deposit is recognizable at a glance and can
              never be mistaken for a mainnet txid: nothing on chain looks like
              this. Do not parse it as one.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LedgerRow" }
              examples:
                credited:
                  value:
                    id: "418223"
                    type: deposit
                    amount_trx: "1000.000000"
                    balance_after_trx: "11000.000000"
                    order_id: null
                    txid: sandbox-5f2c8a1d-7e64-4b93-9a10-c3d7e5b28f41
                    created_at: "2026-08-31T09:14:07Z"
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404":
          description: |
            You are on production, where this path does not exist. The
            envelope and the code are the ordinary ones for an unknown path
            (`not_found`); the sandbox is at
            `https://sandbox.nrg.market/v1`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429": { $ref: "#/components/responses/RateLimited" }

webhooks:

  orderReady:
    post:
      summary: order.ready — energy delivered, you can send
      description: |
        The main event. The `send_before` field is the deadline for sending
        the transaction. The countdown starts when energy has been
        delivered for the **last** item of the order, so in a batch the
        window is shared by all transfers.

        `duration_s` beside it is the lease the order was sold as. The two
        answer different questions and neither can be computed from the other:
        the deadline is the lease **less** a margin, and in mode `b` it is cut
        shorter again by the signed transaction's own expiry. Read the term
        here rather than subtracting it out of the deadline.

        ## Verifying a delivery

        Three headers arrive with every delivery, this one and all the
        others:

        | Header | What it is |
        | --- | --- |
        | `X-NRG-Timestamp` | Unix seconds, minted **per attempt** |
        | `X-NRG-Signature` | HMAC-SHA256(secret, `X-NRG-Timestamp` + "." + raw body), hex |
        | `X-NRG-Event-Id` | Copy of the body's `event_id` |

        1. **Check the signature over the raw bytes.** Compute
           HMAC-SHA256(secret, `X-NRG-Timestamp` + "." + raw body) and
           compare it to `X-NRG-Signature` with a constant-time comparison.
           Sign the bytes you received, not a re-serialized parse of them:
           your JSON encoder orders keys and spaces differently from ours
           and the signature will not match.
        2. **Check the timestamp is fresh: accept ±5 minutes, refuse
           anything outside that window.** A signature with no freshness
           window is replayable forever — the exact bytes we sent, with the
           exact headers we sent, verify just as well a year later in
           anyone's hands. Five minutes is generous enough for a clock that
           has drifted and short enough to be worth having; every attempt
           carries its own timestamp, so a retry twelve minutes after the
           event is still fresh when it arrives.
        3. **Deduplicate on `event_id`, not on your own guesswork.** It is
           stable across every retry of one event — the automatic ones and
           the replays you request — so "have I seen this id" is the whole
           check. Retries happen; the receiver being slow to answer is
           enough to cause one, and an event you have already processed
           must not be processed twice.
        4. **Answer 2xx, quickly.** Anything else, and anything slower than
           5 seconds, counts as a failed attempt. Do the work after
           answering.

        ## Retries and disabling

        Five attempts, spread over about 13 minutes: the first one
        immediately, then — after each failure — a retry in 5 s, in 30 s, in
        2 min and in 10 min. After the fifth failure the delivery is
        `failed` and is not tried again on its own; you can replay it with
        `POST /webhooks/{id}/deliveries/{delivery_id}/retry`, which restores
        the full five attempts and keeps the original `event_id`.

        A failed attempt is any non-2xx answer, and equally no answer at all
        — a timeout, a refused connection, a host that stopped resolving.
        Redirects are not followed: a `3xx` is a failed attempt too.

        When **20 deliveries queued within 24 hours** have used up all their
        attempts, the endpoint moves to `status: disabled` and stops
        receiving events entirely; probes sent with
        `POST /webhooks/{id}/test` never count towards this, and never
        trigger the check either. Counted are deliveries that spent all five
        attempts — a delivery that ends without a request ever being made
        (the two cases below) is not one of them.

        No call re-enables an endpoint, and none is planned: register a new
        one, which issues a new signing secret. If you would rather keep this
        endpoint and its secret, write to support@nrg.market — we can switch
        it back on from our side once the receiver is fixed. Either way you
        hear about the switch-off: we send an email to everyone on the
        account, and `GET /webhooks` carries `disabled_at` and
        `disabled_reason` alongside the status.

        Two things also end a delivery early, with no retries and without
        counting as an attempt: your URL resolving to a private or loopback
        address (the endpoint is disabled on the spot — that is a request we
        would be making into our own network) and the endpoint no longer
        being active when the queued event comes up for delivery.
      requestBody:
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WebhookPayload" }
            examples:
              ready:
                value:
                  event: order.ready
                  event_id: 3f9a1d2e-6c47-4b1a-9f0e-8d5c2a7b4e13
                  sent_at: "2026-08-06T12:00:03Z"
                  data:
                    order_id: ord_9c1f2a
                    status: ready
                    duration_s: 3600
                    send_before: "2026-08-06T12:59:57Z"
      responses:
        "200": { description: Delivery acknowledged }

  orderLifecycle:
    post:
      summary: Other order and billing events
      description: |
        The order's closing events — `order.completed`,
        `order.partially_completed` and `order.failed` — and the per-transfer
        ones, `order.item.sent` and `order.item.expired`.

        A closing payload carries `order_id`, `status`, `duration_s` and
        `charged_trx`. `duration_s` is the lease the order was sold as, on
        every `order.*` payload alike (see `order.ready`): with several products
        the amount no longer says what it was for, and the same
        `charged_trx` can be a large five-minute order or a small hourly one.

        The item events carry `order_id`, `item_id` and — on
        `order.item.sent` — the `txid` of the transfer we saw. They are about
        one transfer rather than about the order, and they carry no lease.

        `order.item.expired` means "the energy was delivered, the transfer
        did not happen, it is charged". In modes `a` and `c` it comes when the
        send window closes on an item still `ready`. In mode `b` it comes when
        your signed transaction fails on its own after delivery — the node
        refused it for what it is (`error: broadcast_failed`), or it was
        mined and the contract refused it, or it ran out of energy having
        spent less than the transfer's requirement — the energy we delivered
        was not on the address (`error: transaction_reverted`) — and the item
        is closed `expired` and charged. A mode `b` item we failed to
        broadcast, one no node could take, or one mined and run out of energy
        where the shortfall is shown to be ours, is refunded and gets no item
        event.
      requestBody:
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WebhookPayload" }
            examples:
              completed:
                value:
                  event: order.completed
                  event_id: 8c2b7f10-4d6e-4a3b-9c15-2e7f6a0b3d94
                  sent_at: "2026-08-06T12:05:11Z"
                  data:
                    order_id: ord_9c1f2a
                    status: completed
                    duration_s: 3600
                    charged_trx: "1.235000"
      responses:
        "200": { description: Delivery acknowledged }

  orderRepriced:
    post:
      summary: order.repriced — the order's price moved at fulfillment
      description: |
        Sent when a position of the order was raised to the market right
        before it was bought, and when a volume raise that nothing more was
        bought after is taken back (see "Order price" in the introduction).
        One order can send it more than once; an order whose price never
        moves never sends it.

        `data` carries `order_id`, `status` (the order's status at that
        moment — `purchasing` as a rule), `duration_s` and three amounts:

        * `quoted_total_trx` — the order's total at creation, the same in
          every `order.repriced` of one order;
        * `previous_total_trx` — the order's `total_trx` before this change;
        * `total_trx` — its `total_trx` after it, the amount now held for the
          order. Above `previous_total_trx` on a raise; below it on a raise
          taken back, and never below `quoted_total_trx`.

        The difference was held from your available balance at the same
        moment (released back to it, on a take-back), and `GET /ledger` shows
        it as a `hold` (or `hold_release`) entry carrying the order's id. The
        raise is made before the purchase it pays for, so it does not mean
        the energy was bought: `order.ready` and the closing events follow as
        usual, and the closing event's `charged_trx` is counted at the price
        the positions stand at by then.

        A raise your balance cannot cover, or one above the cap, is never
        made and sends no `order.repriced`. A transfer position then fails
        with `purchase_failed` and its hold comes back in full; a volume
        position is refused that way only while nothing has been bought for
        it and `allow_partial` is off, and otherwise ends short, charged for
        what was delivered. The order's closing event says which.

        Deliveries are retried independently and can arrive out of order.
        Deduplicate on `event_id` as always, and take the order's current
        `total_trx` from `GET /orders/{order_id}` rather than adding events
        up.
      requestBody:
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WebhookPayload" }
            examples:
              raised:
                summary: A volume raised to the market between two pieces
                value:
                  event: order.repriced
                  event_id: 6d0e2b71-58c3-4f9a-a1d4-3e7c90b2f518
                  sent_at: "2026-10-15T15:31:07Z"
                  data:
                    order_id: ord_9c1f2a
                    status: purchasing
                    duration_s: 3600
                    quoted_total_trx: "20.000000"
                    previous_total_trx: "20.000000"
                    total_trx: "25.000000"
              taken_back:
                summary: >-
                  The same raise taken back — the fill ended short without
                  buying anything after it, so the volume returns to the
                  price its last piece was bought at
                value:
                  event: order.repriced
                  event_id: 1f7a9c34-0b26-4e58-9d13-a6c2e8f40b97
                  sent_at: "2026-10-15T15:33:42Z"
                  data:
                    order_id: ord_9c1f2a
                    status: purchasing
                    duration_s: 3600
                    quoted_total_trx: "20.000000"
                    previous_total_trx: "25.000000"
                    total_trx: "20.000000"
      responses:
        "200": { description: Delivery acknowledged }

  topupLifecycle:
    post:
      summary: Top-up request events
      description: |
        The life of a request for TRX (`GET /topup-requests`). All three are
        sent only while `auto_topup.enabled` is on.

        `topup.requested` — we are asking you for money: an order was refused
        for lack of balance, or the available balance fell under your
        `balance_low` threshold. **It can arrive twice with the same
        `topup_request_id`**, and the second one supersedes the first: a
        further need raises the open request instead of opening a second one.

        It is re-sent when **either** of two things happens, and only one of
        them is the amount:

        * `amount_trx` grew;
        * `reason` **escalated** from `balance_low` to
          `order_insufficient_balance` — an order has now been refused and is
          waiting on this deposit. `amount_trx` may be unchanged.

        The escalation is one-way; `reason` never goes back. `expires_at` is
        pushed out a fresh TTL on every re-send, because a raise makes it a
        different ask.

        **Do not deduplicate on `(topup_request_id, amount_trx)`**: a repeat at
        the same amount is not a copy, it is a change of `reason` and of
        `expires_at`. Deduplicate on `event_id` like every other event, and act
        on the newest state you have seen for that `topup_request_id`.

        `topup.fulfilled` — deposits credited since the request add up to
        `amount_trx` (`credited_trx` says how much), or your `target_trx` was
        reached by some other route. `txid` is the transaction that finished
        it, which may be the last of several — and it is **`null`** when
        nothing on chain finished it: a released hold, a refund or an operator
        adjustment can carry the balance to the target, and that closure is
        found by a periodic pass rather than by a credit, so there is no
        transaction to name. Do not key on `txid` being present.

        `topup.expired` — nobody answered within a day. This refuses no money:
        TRX arriving at the address afterwards is credited exactly as ever, and
        a new request is raised the next time the balance is short.

        **`topup.*` is not `maintenance.topup`.** That one is energy delivered
        to a wallet under an auto-refill rule; these are TRX for the prepaid
        balance. And the money landing is still `deposit.credited` —
        `topup.fulfilled` is news about the request, not a second announcement
        of the deposit, so an integration crediting its own books should key on
        `deposit.credited` and not on this. A deposit below 1 TRX has no
        `deposit.credited` at all (see `WebhookEvent`), though a request it
        completes still gets `topup.fulfilled` with its txid; books kept to
        the last sun reconcile against `GET /balance` and `GET /ledger`.
      requestBody:
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WebhookPayload" }
            examples:
              requested:
                value:
                  event: topup.requested
                  event_id: 2a9f13c7-6d84-4e02-b1ef-70c5a83d4b16
                  sent_at: "2026-09-04T11:02:18Z"
                  data:
                    topup_request_id: 9c4f0b52-31ad-4e6b-8d70-1f2a5c9e7b83
                    amount_trx: "120.000000"
                    deposit_address: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9
                    reason: order_insufficient_balance
                    order_id: null
                    expires_at: "2026-09-05T11:02:18Z"
                    available_trx: "1.020000"
              fulfilled:
                value:
                  event: topup.fulfilled
                  event_id: 5f1b8d90-4c27-4a3e-9b06-8ad2e14f7c35
                  sent_at: "2026-09-04T11:29:44Z"
                  data:
                    topup_request_id: 9c4f0b52-31ad-4e6b-8d70-1f2a5c9e7b83
                    amount_trx: "120.000000"
                    credited_trx: "150.000000"
                    txid: 3f9d1a6c58b24e07af31d20e9c7b45816ad3f0e2c94b7815d6a0f32c8e14b7d9
                    order_id: null
                    balance_trx: "151.020000"
              fulfilled_without_a_transaction:
                summary: >-
                  The target was reached by something other than a deposit —
                  `txid` is null
                value:
                  event: topup.fulfilled
                  event_id: b7302c19-8d54-4f6a-91ee-2c0d5a83f174
                  sent_at: "2026-09-04T12:04:09Z"
                  data:
                    topup_request_id: 9c4f0b52-31ad-4e6b-8d70-1f2a5c9e7b83
                    amount_trx: "120.000000"
                    credited_trx: "0.000000"
                    txid: null
                    order_id: null
                    balance_trx: "205.400000"
              expired:
                value:
                  event: topup.expired
                  event_id: 8e6c2f41-0b73-4d95-a2c8-63f19d4e70ba
                  sent_at: "2026-09-05T11:02:20Z"
                  data:
                    topup_request_id: 9c4f0b52-31ad-4e6b-8d70-1f2a5c9e7b83
                    amount_trx: "120.000000"
                    reason: order_insufficient_balance
                    order_id: null
      responses:
        "200": { description: Delivery acknowledged }

  maintenanceLifecycle:
    post:
      summary: Energy maintenance events
      description: |
        `maintenance.topup` — energy delivered to the rule's wallet;
        `maintenance.budget_exhausted` — the daily budget is exhausted, no
        more top-ups until the end of the UTC day; `maintenance.paused` —
        the rule has been stopped (currently the only reason is
        `insufficient_balance`) and resumes only via a PATCH request.
      requestBody:
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WebhookPayload" }
            examples:
              topup:
                value:
                  event: maintenance.topup
                  event_id: 7b2c9e04-1f83-4d6a-8e57-0a3b6c1d9f42
                  sent_at: "2026-08-18T09:15:02Z"
                  data:
                    rule_id: mnt_4b7d1c
                    address: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9
                    units: 131000
                    charged_trx: "4.192000"
              budget_exhausted:
                value:
                  event: maintenance.budget_exhausted
                  event_id: c41e7a58-90b2-4f31-a6d8-52e7f0c3b19d
                  sent_at: "2026-08-18T17:40:11Z"
                  data:
                    rule_id: mnt_4b7d1c
                    address: TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9
                    spent_today_trx: "19.552000"
                    daily_budget_trx: "20.000000"
      responses:
        "200": { description: Delivery acknowledged }

  queueLifecycle:
    post:
      summary: Queue session events
      description: |
        The life of a queue session (`api-spec.md` §12). Six events, one
        envelope, and every `data` carries `session_id` and the session's
        `counters`:

        * `queue.started` — Start went through and the hold is placed;
        * `queue.packet_delivered` — one packet was seen delivered on-chain
          and charged; this is the only event that moves money, and it comes
          once per packet rather than as a total;
        * `queue.paused` / `queue.resumed` — with the `reason`; a pause
          lifts itself, so `queue.resumed` needs nothing from you;
        * `queue.completed` — the queue was exhausted and the last delivered
          packet has expired; the counters are final and the hold is
          released;
        * `queue.stopped` — you stopped it; packets in flight at that moment
          are still settled afterwards, each with its own
          `queue.packet_delivered`.

        The six names are in the subscribable list (`WebhookEvent`), so a
        subscription may name them today; they are sent from the moment the
        mode is enabled for the account and a session is started.
      requestBody:
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WebhookPayload"
                - type: object
                  properties:
                    data:
                      oneOf:
                        - $ref: "#/components/schemas/QueueStartedData"
                        - $ref: "#/components/schemas/QueuePacketDeliveredData"
                        - $ref: "#/components/schemas/QueuePausedData"
                        - $ref: "#/components/schemas/QueueResumedData"
                        - $ref: "#/components/schemas/QueueCompletedData"
                        - $ref: "#/components/schemas/QueueStoppedData"
            examples:
              packet_delivered:
                value:
                  event: queue.packet_delivered
                  event_id: 5e1c8a3f-7b2d-4c96-a0e4-93f1d2b7c608
                  sent_at: "2026-09-17T10:12:41Z"
                  data:
                    session_id: qs_2f8e41
                    packet_id: "184"
                    units: 650000
                    price_sun: 35
                    charged_trx: "22.750000"
                    hold_trx: "14.000000"
                    counters:
                      items_total: 120
                      items_pending: 97
                      items_sent: 23
                      items_skipped: 0
                      packets_bought: 4
                      packets_confirmed: 4
                      units_delivered: 2600000
                      charged_trx: "91.000000"
              paused:
                value:
                  event: queue.paused
                  event_id: 9a7d0c2e-13f4-4b8a-9d61-4c2e7f80b153
                  sent_at: "2026-09-17T10:20:03Z"
                  data:
                    session_id: qs_2f8e41
                    reason: insufficient_balance
                    counters:
                      items_total: 120
                      items_pending: 61
                      items_sent: 59
                      items_skipped: 0
                      packets_bought: 9
                      packets_confirmed: 9
                      units_delivered: 5850000
                      charged_trx: "204.750000"
              completed:
                value:
                  event: queue.completed
                  event_id: 0c3b6e19-8d47-4f5a-b2e8-6a91c0d4f7e2
                  sent_at: "2026-09-17T10:41:17Z"
                  data:
                    session_id: qs_2f8e41
                    reason: queue_exhausted
                    hold_trx: "0.000000"
                    counters:
                      items_total: 120
                      items_pending: 0
                      items_sent: 118
                      items_skipped: 2
                      packets_bought: 17
                      packets_confirmed: 17
                      units_delivered: 11050000
                      charged_trx: "386.750000"
      responses:
        "200": { description: Delivery acknowledged }

  webhookTest:
    post:
      summary: webhook.test — a probe you asked for
      description: |
        Sent only by `POST /webhooks/{id}/test`, never by anything that
        happens to your account. Signed, headed and logged exactly like a
        real event, so it is a genuine end-to-end check of your handler —
        which is why the event name is unmistakable: dispatch on it and
        return 2xx, and never let it fall through to the branch that fills
        an order.

        Not subscribable, and not affected by your endpoint's `events`: it
        goes to the endpoint you named. One attempt, no retry ladder, and
        its failures do not count towards disabling the endpoint.
      requestBody:
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WebhookPayload" }
            examples:
              test:
                value:
                  event: webhook.test
                  event_id: 0f0f6b1e-4a1e-4a5f-9b8a-2f5f0d9c1a77
                  sent_at: "2026-08-26T10:31:44Z"
                  data:
                    message: This is a test event from nrg.market. No order was created.
      responses:
        "200": { description: Delivery acknowledged }

components:

  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: |
        The API key from your dashboard — the key of the stand you are
        calling: `Authorization: Bearer nrg_live_...` on production,
        `Authorization: Bearer nrg_test_...` in the sandbox. The key is shown
        only once. A key can be restricted to a list of allowed IPs.

        The prefix says which host the key belongs to: `nrg_live_…` to
        `https://api.nrg.market/v1`, issued at `app.nrg.market`, and
        `nrg_test_…` to `https://sandbox.nrg.market/v1`, issued at
        `sandbox-app.nrg.market`. Each host accepts its own kind and refuses
        the other with `401 unauthorized` — the same code as any key we do
        not accept, with the right base URL named in `message`.

        The key is transmitted whole and only in this header. The service
        stores only values derived from it: the lookup index is a
        deterministic hash of the **entire token**, verification is
        argon2id. A truncated secret is not used as an index (see
        `api-spec.md` §8).

  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: |
        A unique request string (e.g., a UUID). A retry returns the
        original order.

        Body equality is checked by hashing the **raw bytes** of the
        request, not the parsed JSON: a retry must be byte-identical.
        Changed key order, whitespace or number formatting yields
        `409 idempotency_conflict` — serialize the body once and retry the
        same bytes.

        The key is bound **only to a created order**. A request rejected by
        validation (`400`, `422`) does not consume the key: the same key
        can be used again with a corrected body.
      schema: { type: string, minLength: 1, maxLength: 128 }
    OrderId:
      name: order_id
      in: path
      required: true
      schema: { type: string }
    RuleId:
      name: rule_id
      in: path
      required: true
      schema: { type: string }
    TopupRequestId:
      name: topup_request_id
      in: path
      required: true
      schema: { type: string }
    QueueSessionId:
      name: session_id
      in: path
      required: true
      schema: { type: string }
    Cursor:
      name: cursor
      in: query
      schema: { type: string }
    Limit:
      name: limit
      in: query
      schema: { type: integer, minimum: 1, maximum: 200, default: 50 }

  responses:
    BadRequest:
      description: Malformed request
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    Unauthorized:
      description: Invalid key or IP not allowed
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    NotFound:
      description: Not found
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    CapacityUnavailable:
      description: |
        We temporarily cannot accept the request: no purchasing quota with
        the energy providers, or the TRON network is unavailable (without
        it we cannot check the recipient against the blacklist or the
        sender's activation). For a volume (`energy_units`), also when the
        market data its price would be built from is out of range: nothing
        is reserved or charged. Retry later.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    RateLimited:
      description: |
        Rate limit exceeded (`rate_limited`), or too many failed
        authorizations from this credential (`too_many_auth_failures`). Both
        are `429` and both carry `Retry-After`; they differ in what you
        should do about it, which is why they differ in `code` and not only
        in `message`. `rate_limited` also carries the `RateLimit-*` state of
        the bucket it came from; `too_many_auth_failures` does not, because
        the counter behind it is not a bucket. See "Rate limits" and
        "Repeated authorization failures" above.

        On `POST /orders` a `rate_limited` may also carry
        `details.reason = bulk_volume_cap`: not requests per minute but
        **energy per window** — a mode `c` order whose volumes would take
        your account past the bulk allowance. `details` carries `cap_units`
        (the allowance), `spent_units` (your volume already inside the
        window), `requested_units` (what this order asked for) and
        `window_s` (the width of the window, 3600). `Retry-After` is the
        first instant at which **this** body can be accepted: enough of your
        counted volume has to leave the window to make room for
        `requested_units`, which is not in general the moment the oldest
        position leaves — one departure frees only that position's units.
        An order whose own volume is larger than the whole allowance is not
        answered here at all: no waiting would help it, and it is
        `400 invalid_request` with
        `details.reason = bulk_order_over_cap`. It is a pace limit like the
        others, so it is the same code: the order is not wrong, and the same
        body sent later is accepted. It carries no `RateLimit-*` headers:
        those describe a bucket of requests per minute, and this allowance
        is energy per hour — `details` above is its whole state.
      headers:
        Retry-After:
          description: Seconds to wait before retrying.
          schema: { type: integer }
        RateLimit-Limit:
          description: |
            Requests per minute in this bucket — per UTC day on
            `POST /sandbox/deposit`, the one allowance in this API that is
            not counted per minute. Absent in exactly three cases,
            and in none is a number invented for it: the limiter could not
            read the bucket state (the request is let through then), the
            answer is `too_many_auth_failures`, which is counted by the
            authorization-failure counter and not by a bucket — see "Repeated
            authorization failures" — or it is the volume allowance
            (`details.reason = bulk_volume_cap`), which is energy per hour
            rather than requests per minute.
          schema: { type: integer }
        RateLimit-Remaining:
          description: Requests left in this bucket right now.
          schema: { type: integer }
        RateLimit-Reset:
          description: Seconds until the bucket is full again.
          schema: { type: integer }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }

  schemas:

    TRX:
      type: string
      pattern: '^\d+\.\d{6}$'
      description: Amount in TRX, 6 decimal places
      examples: ["2.080000"]

    USD:
      type: string
      pattern: '^\d+\.\d{6}$'
      description: |
        A US dollar figure, 6 decimal places — the same shape as `TRX` and
        for the same reason. It appears in one place only, as the reference
        rate `trx_usd` of `GET /tariff`; we hold no balances in USD and
        charge nothing in USD.
      examples: ["0.337700"]

    TronAddress:
      type: string
      pattern: '^T[1-9A-HJ-NP-Za-km-z]{33}$'
      examples: [TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9]

    TransferKind:
      type: string
      enum: [single, double, custom]
      description: |
        Determined automatically and finalized when the order is created:
        `single` — the recipient already holds USDT (~65,000 energy);
        `double` — the recipient's USDT balance is zero, whether or not the
        address is activated on chain (~131,000): what doubles the figure is
        the empty balance, not a missing account — an unactivated address
        that already holds USDT is `single`, and an activated one with a zero
        balance is `double`;
        `custom` — the recipient is a contract, the amount is calculated
        from actual usage.

        Three values and no more. This is what an address check answers
        about a **transfer**, and a transfer is one of these three shapes;
        the volume a mode `c` position may name instead (`bulk`) is not a
        finding about any address, so it lives in `ItemKind` and never
        appears here. A client switching on this enum keeps its three
        branches.

    ItemKind:
      type: string
      enum: [single, double, custom, bulk]
      description: |
        What an order item was sold as — the three transfer kinds
        (`TransferKind`, with the same meanings) plus one that is not a
        transfer kind at all:

        `bulk` — a mode `c` position that named `energy_units` instead of
        `kind`. There is no transfer behind it and therefore no standard to
        derive the volume from: the number is the client's, and
        `energy_units` carries it. Such a position may be filled from
        several sources at once, which is why it is the only kind whose
        `energy_delivered` can come back below what was ordered.

        `bulk` occurs on items only. `GET /address-check` and the estimate's
        per-transfer items answer with `TransferKind` and cannot produce it.

    EnergyKind:
      type: string
      enum: [single, double]
      description: |
        The volume you are buying in mode `c`, where no recipient is named
        and there is therefore nothing to read it from: `single` — about
        65,000 energy, enough for a transfer to an address that already
        holds USDT; `double` — about 131,000, enough for one that does not.

        `custom` is absent on purpose. It is the outcome of a dry-run
        against a specific contract recipient, so it cannot be asked for in
        advance — an order to a contract goes through mode `a`.

        A position that wants some other volume does not use this enum at
        all: it names `energy_units` instead of `kind`.

    OrderStatus:
      type: string
      description: |
        `ready` occurs when **every live item is `delegated`** — the energy
        confirmed on chain — and `send_before` is computed. While one is
        still `pending`, the order stays in `purchasing`; an item that has
        already `failed` does not hold the rest back.

        **In mode B the order stays `ready` while we broadcast.**
        `broadcasting` and `broadcasted` are states of a transaction in
        flight, not resting places: `broadcasted` means a node accepted the
        transaction, not that it is in a block. An order whose items are
        all `broadcasted` is therefore still `ready`, and it becomes final
        only when each of them reaches `confirmed` (or `expired` / `failed`)
        — which is also when the money is settled. A mode B `completed`
        order can hold `expired` items: the energy was delivered and your
        transaction failed on its own (see `ItemError`); whether a transfer
        went out is the item's `confirmed`, not the order's status. Any item outside the two groups
        below (`pending`, `delegated`, `broadcasting`, `broadcasted`) means
        the order is not final yet and leaves its status where it is.

        **An order is fulfilled when the energy has been delivered**, not
        when we see the transfer: in mode A you send the transaction
        yourself, and the order status does not depend on it. Charging
        happens at the same moment; the rule is unchanged: we charge for
        energy provided.

        The final status is determined by the mix of item statuses:
        - energy delivered for all (`ready`/`sent`/`expired`/`confirmed`) → `completed`;
        - some delivered, some `failed` → `partially_completed`;
        - all `failed` → `failed`.

        `expired` remains in the enum for history: in mode A an order
        becomes final before the send window expires.

        **`awaiting_funds` — mode `b` only, and only with `auto_topup`
        enabled.** Your prepaid balance did not cover the order, but the
        signed transaction is already ours, so instead of a `402` the order
        is parked: no hold is placed, a top-up request goes out
        (`topup.requested`), and `fund_before` is the deadline for the
        deposit to be credited. Pay it in time and the order becomes
        `funded` at the price quoted in this very response — a price
        recomputed before your deposit lands does not change it; from there it is
        filled like any order, raise included (see "Order price" in the
        introduction). Miss it and the
        order goes `failed` with `error_code = funding_window_missed`: no
        money moved at either end, and the signed transaction is free to be
        submitted in a new order.
      enum:
        [
          created,
          awaiting_funds,
          funded,
          purchasing,
          ready,
          completed,
          partially_completed,
          expired,
          failed,
          canceled,
        ]

    LedgerRow:
      type: object
      description: |
        One row of the money history. `GET /ledger` returns a page of these,
        and `POST /sandbox/deposit` answers with the single row it wrote —
        deliberately the same schema, so that one parser reads both and a
        sandbox rehearsal exercises the type an integration will meet in
        production. What a sandbox row narrows (`type` is always `deposit`,
        `txid` always the `sandbox-<uuid>` form) is said at that endpoint, in
        prose and examples: narrowing it here would give the two responses two
        shapes and put the divergence back.
      required:
        [
          id,
          type,
          amount_trx,
          balance_after_trx,
          order_id,
          queue_session_id,
          txid,
          created_at,
        ]
      properties:
        id: { type: string }
        type:
          type: string
          enum:
            - deposit
            - hold
            - hold_release
            - charge
            - refund
            - adjustment_credit
            - adjustment_debit
        amount_trx:
          allOf:
            - $ref: "#/components/schemas/TRX"
          description: Absolute amount; direction is defined by `type`
        balance_after_trx:
          allOf:
            - $ref: "#/components/schemas/TRX"
          description: |
            Full balance after the operation. Unchanged for
            `hold` and `hold_release` — a hold affects
            `available_trx`.
        order_id: { type: string, nullable: true }
        queue_session_id:
          type: string
          nullable: true
          description: |
            The queue session this movement belongs to (`api-spec.md` §12.6):
            its `hold`, the `charge` for each delivered packet and the
            `hold_release` of the remainder carry it, and none of them has an
            `order_id` — a session buys without an order. `null` on every
            other row.
        txid: { type: string, nullable: true }
        created_at: { type: string, format: date-time }

    ItemStatus:
      type: string
      description: |
        `pending` — the item is accepted, energy not yet delivered;
        `delegated` — the energy is **confirmed on-chain** at the `from`
        address (a provider's response alone does not grant this status);
        `ready` — the energy is delivered and `send_before` is known; for
        mode A this is the obligation fulfilled, and the order becomes
        `completed` at this point;
        `sent` — the outgoing transaction has been seen in the network
        (informational: affects neither money nor order status);
        `broadcasting`/`broadcasted` — mode B, the transaction is being
        sent / has been accepted by the network;
        `confirmed` — mode B, after solidification (~1 min);
        `expired` — **mode A**: you did not send the transfer before
        `send_before`; the energy was delivered, so it is charged and does
        not spoil fulfillment. **Mode B**: the energy was delivered and
        your own transaction then failed — the node refused it for what it
        is (`error: broadcast_failed`), or it was mined and the contract
        refused it or it ran out of energy having spent less than the
        transfer's requirement (`error: transaction_reverted`); charged, and
        the signed transaction stays used;
        `failed` — the service was not delivered through our fault; no
        charge, the hold is returned. This also covers a mode B item we
        failed to send before `send_before`
        (`error: broadcast_window_missed`): past the promised deadline we
        do not broadcast, and we do not charge for what was not sent — a
        mode B broadcast no node took for reasons of its own
        (`error: broadcast_failed`), and a mode B transfer mined and run out
        of energy where the shortfall is shown to be ours
        (`error: transaction_reverted`; the signed transaction is in a block
        and stays used).
      enum: [pending, delegated, ready, sent, broadcasting, broadcasted, confirmed, expired, failed]

    ItemError:
      type: string
      nullable: true
      description: |
        The reason on a `failed` item — a closed list — and, in mode B, on
        an `expired` one. `null` for the other statuses; an `expired` item
        of modes A and C has no reason (it is not a failure but unused
        energy, and it is charged).

        `purchase_failed` — the energy could not be purchased. It also
        covers a market dearer than the position's price whose raise could
        not be made — your available balance was short of the difference,
        or the price would have gone above the cap (see "Order price" in the
        introduction); on a `bulk` position, only while nothing has been
        bought for it and `allow_partial` is off — later such a fill ends
        short instead. On a `bulk` position it also covers "the market could
        not cover the whole volume": a position that did not allow a partial
        fill and could not be completed is a purchase that did not happen,
        and it is refused the same way and refunded the same way;
        `broadcast_failed` — mode B, the node rejected the transaction. On
        a `failed` item no node took it for reasons of its own (none
        answered, busy, no peers, any code not listed next) and the hold is
        returned — `TRANSACTION_EXPIRATION_ERROR` among them: a deadline
        past the node's horizon is refused at acceptance, so after delivery
        it means the node's clock and ours disagree. On an `expired` item
        the node refused the transaction itself after the energy was
        delivered — `TAPOS_ERROR`, `SIGERROR`, `BANDWITH_ERROR`,
        `CONTRACT_VALIDATE_ERROR` — and the item is **charged**;
        `transaction_reverted` — mode B, the transaction made it into a
        block and did not execute. On an `expired` item it is **charged**:
        the contract refused the transfer (a `REVERT` — the USDT left the
        wallet after the order, the wallet was blacklisted — or an
        `OUT_OF_TIME`, the call past the network's execution time), or the
        call ran out of energy (`OUT_OF_ENERGY`) having spent less than the
        transfer's requirement — 64,285 units for a `single`, 130,285 for a
        `double`, the dry run's measurement for a `custom` — so the energy we
        delivered was not on the address when it ran. On a `failed` item the
        call ran out of energy and the shortfall is shown to be ours: it spent
        at least the requirement and still ran out (our estimate was short —
        a recipient balance emptied after the dry run that doubled the cost),
        or our records show the vendor revoked the delegation before your
        transfer's block, or another of your transfers from the same
        address — in this order or another — took its energy: your transfers
        from that address whose energy was on it at the block together spent
        at least what they together required;
        the hold is returned. Either way the transaction is
        in a block, and the same signed bytes are not accepted again;
        `broadcast_window_missed` — mode B, we did not send it before
        `send_before`;
        `window_closed_before_send` — the window closed on an item that
        never reached `ready`; this is an inconsistency on our side, the
        money is returned;
        `funding_window_missed` — mode B, the order was `awaiting_funds`
        and the deposit was not credited before `fund_before`. Nothing was
        ever held for it and nothing was bought, so there is no refund to
        make; the signed transaction is released and may go into a new
        order.

        On a `failed` item none of these is ever charged for. The first five
        return the hold in full; `funding_window_missed` has nothing to
        return — there was none. The two mode B reasons on an `expired` item
        are the exception, and the only one: the energy was delivered and
        your own transaction failed, so the item's price is charged.
      enum:
        - purchase_failed
        - broadcast_failed
        - transaction_reverted
        - broadcast_window_missed
        - window_closed_before_send
        - funding_window_missed

    OrderErrorCode:
      type: string
      nullable: true
      description: |
        The reason on a `failed` order — the same values as on items
        (`ItemError`), plus `multiple_causes` when items failed for
        different reasons. `null` for the other statuses.

        `transaction_reverted` is the reason of a mode `b` order whose
        transfers ran out of energy where the shortfall was shown to be
        ours, and were refunded. A transaction the contract refused is charged
        and closes its item `expired`, which sets no order reason.
      enum:
        - purchase_failed
        - broadcast_failed
        - transaction_reverted
        - broadcast_window_missed
        - window_closed_before_send
        - funding_window_missed
        - multiple_causes

    OrderRequestModeA:
      type: object
      required: [mode, transfers]
      properties:
        mode:
          type: string
          const: a
        transfers:
          type: array
          minItems: 1
          maxItems: 500
          items:
            type: object
            required: [from, to]
            properties:
              from: { $ref: "#/components/schemas/TronAddress" }
              to: { $ref: "#/components/schemas/TronAddress" }
        duration_s:
          type: integer
          default: 300
          examples: [300]
          description: |
            How long the energy is leased for, in seconds — one of the
            products on sale (`products[].duration_s` of `GET /tariff`,
            ascending). Omitted means the five-minute lease, so a body
            written before this field existed keeps its meaning exactly.

            It decides two things at once: the price of every position
            (`energy_units × that product's current price` when
            the order is created; see "Order price" in the introduction for
            when it is raised afterwards) and `send_before`, which is the lease
            less a 3-second margin. A value we are not selling is
            `400 invalid_request` whose `details` carries the refused
            `duration_s` as well as `allowed`.

            No `enum` here on purpose: the three durations that exist are
            fixed, but which of them are on sale is data and moves without a
            release of this document.
        client_ref:
          anyOf:
            - type: string
              maxLength: 128
            - type: "null"
          description: Your identifier for reconciliation

    OrderRequestModeB:
      type: object
      required: [mode, transfers]
      properties:
        mode:
          type: string
          const: b
        transfers:
          type: array
          minItems: 1
          maxItems: 500
          items:
            type: object
            required: [signed_tx]
            properties:
              signed_tx:
                type: string
                description: |
                  The signed transaction in hex. The private key is never
                  transmitted.

                  Only a `transfer` call of the USDT contract is accepted,
                  with a single signature of the sender address owner and
                  no TRX attached. Multisig (`Permission_id`) is not
                  supported: a permission's key set lives on-chain and can
                  change without our knowledge.

                  The transaction must remain valid for at least 3 minutes
                  at the moment the order is created — it has to survive
                  energy delivery and the broadcast — and for no more than
                  24 hours less a minute, past which no node accepts it.
                  Its TAPOS reference must be the usual shape: two bytes of
                  `ref_block_bytes`, eight of `ref_block_hash` — and name a
                  block of mainnet that nodes still hold, which we check
                  against the chain. Anything else → `400`; the ceiling, the
                  TAPOS shape, a reference to a block the chain does not hold
                  and bytes a node would not parse as we read them name
                  themselves in `details.reason`.

                  Its own expiry also shortens `send_before`: the window
                  we promise never runs past the transaction's deadline
                  less a broadcast margin, because a node refuses an
                  expired transaction whatever energy is on the address.
                  Give a transaction more life than the minimum and the
                  window you get is the full one.
        duration_s:
          type: integer
          default: 300
          examples: [300]
          description: |
            The lease, in seconds — same rule and same allowed values as in
            mode `a` (`products[].duration_s` of `GET /tariff`), default
            `300`.

            **A long lease does not lengthen `send_before` here.** The
            window is still capped by the expiry of the signed transaction
            less the broadcast margin, and a TRON transaction lives minutes,
            not hours: a one-day lease in this mode buys energy that
            outlives the transaction it was bought for. What it is good for
            is the same energy standing on the sender for the rest of the
            term — but the broadcast we promise still happens inside the
            transaction's own life.
        client_ref:
          anyOf:
            - type: string
              maxLength: 128
            - type: "null"

    OrderRequestModeC:
      type: object
      description: |
        Energy for a wallet, with no transfer named. You say which wallet
        and how much; there is no recipient, and so no transaction for us
        to see or to broadcast.

        This is the mode for when the recipient is not known yet, or when
        you are topping a wallet up ahead of a batch you will assemble
        later. Because there is no recipient, the volume cannot be derived
        and you state it yourself — as `kind`, which also means we cannot
        correct it (`single` on a transfer that turns out to need `double`
        leaves the transfer short of energy, and the difference burns TRX),
        or as `energy_units`, a number of your own.

        **A position names one of the two, never both and never neither.**
        `kind` is the transfer-shaped volume, `energy_units` is a volume you
        chose; sending both is `400 invalid_request` with
        `details.reason = kind_and_energy_units`, because the two would have
        to be reconciled and there is no rule that says which wins.

        Items of such an order carry `to: null` and never reach `sent`:
        there is no transfer for us to match. They stand at `ready` for the
        `send_before` window and become `expired` when it closes, which
        here means the lease ran out — the normal end, not a failure.
      required: [mode, transfers]
      properties:
        mode:
          type: string
          const: c
        transfers:
          type: array
          minItems: 1
          maxItems: 500
          items:
            type: object
            # `from` is required on the item itself, and only the either/or
            # lives in the `oneOf`. Spelling the branches as
            # `[from, kind] | [from, energy_units]` means the same to a
            # validator and something else entirely to a client generator:
            # with nothing required at the item level, openapi-typescript
            # emits every field optional and the branches as
            # `& (unknown | unknown)`, so `from` — required since mode `c`
            # existed — arrives in the generated client as optional and a
            # body without a wallet type-checks.
            required: [from]
            oneOf:
              - required: [kind]
              - required: [energy_units]
            properties:
              from:
                allOf: [{ $ref: "#/components/schemas/TronAddress" }]
                description: >-
                  The wallet the energy is delegated to. It must be
                  activated on chain, or the order is refused with
                  `422 invalid_address` and
                  `details.reason = inactive_wallet` — the same reason word
                  `POST /auto-refill-rules` uses for the same condition.
              kind: { $ref: "#/components/schemas/EnergyKind" }
              energy_units:
                type: integer
                minimum: 65000
                maximum: 50000000
                examples: [1000000]
                description: |
                  How much energy this wallet is to receive, in units —
                  instead of `kind`, and never beside it. The item comes
                  back with `kind: bulk`.

                  **Above 131,000 the order's `duration_s` must be 3600 or
                  longer**, or the order is `400 invalid_request` with
                  `details.reason = bulk_needs_longer_lease`. A volume that
                  large is not bought in one piece: it is assembled from
                  whichever sources are cheapest at that moment, several of
                  them when no single one can cover it, and the pieces land
                  seconds apart. Each piece's lease starts at **its own**
                  delegation, so on the five-minute product the first piece
                  would already be expiring while the last was still
                  arriving. An hour is the shortest lease where that spread
                  does not matter.

                  Outside `minimum`/`maximum` the answer is
                  `400 invalid_request` with
                  `details.reason = bulk_volume_out_of_range`, carrying the
                  refused `energy_units` and the bounds. The upper bound is
                  a single position's; a very large order may also meet
                  `429 rate_limited` with
                  `details.reason = bulk_volume_cap` — see there.

                  **`maximum` is what we accept, not what is available.** It
                  is the ceiling on the number a position may name; whether
                  that much energy can be assembled at the minute you order
                  is a different question, and a volume well inside the
                  bounds can still fail to fill. Nothing here is a supply
                  figure. The answer to "is it there" is `coverage` from
                  `POST /estimate` for the same `energy_units` — its
                  `complete` in particular — and, if it can be short,
                  `allow_partial` below is how you say what to do about it.

                  **The per-unit price is set when the order is created.**
                  It is the product's current price, or higher when
                  assembling this volume from the market at that moment costs
                  more than the current price covers; it is never lower than
                  the current price. `POST /estimate` with the same
                  `energy_units` and `duration_s` quotes the same number at
                  the same moment (`total_trx`), so a volume is not always
                  priced at the current price of `GET /tariff`. When we have no
                  fresh market data covering the whole volume, the current
                  price applies. Several volume positions in one order are filled
                  from the same market, so each is priced at least at what
                  `POST /estimate` quotes for it alone at that moment, and at
                  least at the price of the dearest part of the market the
                  volumes need together.

                  **The per-unit price can be raised while the volume is
                  being filled** (see "Order price" in the introduction):
                  before the first piece is bought, or between pieces, when
                  what the market sells the rest for leaves less than our
                  minimum margin under it. The raise covers the whole
                  position, units already delivered included, and is held
                  from your balance before anything more is bought; a raise
                  nothing more was bought after is taken back when the fill
                  ends short. It never goes below the price at creation.

                  **You are billed per unit that arrives.** The price you
                  are quoted is `energy_units` × that per-unit price; if
                  less than that arrives, the charge is the same per-unit
                  price times `energy_delivered` and the rest of the hold
                  comes back. See `allow_partial` for whether such a volume
                  is taken on at all.
              allow_partial:
                type: boolean
                default: false
                description: |
                  Whether to start filling a volume the market visibly
                  cannot cover. Meaningful only beside `energy_units`; on a
                  `kind` position there is nothing to fill partially.

                  `false` (the default) is **all or nothing, decided up
                  front**: before anything is bought we plan how the whole
                  volume would be bought — over as many rounds of buying as
                  the fill would take, counting only what the sources confirm
                  they would sell — and if the market cannot supply all
                  of `energy_units` within the position's price — after the
                  raise we make when the market is dearer (see "Order price"
                  in the introduction), where your balance covers it and the
                  cap allows it — nothing is bought at all: the position ends `failed`
                  with `error = purchase_failed` and its hold comes back
                  whole. Nothing is charged and nothing is delegated.

                  `true` accepts the volume regardless: the fill starts even
                  when it is visibly short, buys what can be had within the
                  position's price, and the position is delivered with
                  `energy_delivered` below `energy_units`. Where a single
                  source can supply the whole volume while the cheaper pieces
                  cannot be put together, the volume may be filled from that
                  one source in full rather than short.

                  **Neither setting can undo a delegation.** Once the first
                  piece has been bought it is on your wallet for the lease,
                  so a market that moves during the fill — capacity gone, a
                  source refusing — ends that fill where it stands, on
                  `false` as much as on `true`: the position is delivered
                  short, you are charged `energy_delivered` at the same
                  per-unit price, the rest of the hold is released and the
                  order ends `partially_completed` rather than `completed`.
                  A market that turns too dear during the fill for the rest
                  of the volume to be bought within the position's price,
                  when the raise that would follow it cannot be made (your
                  balance is short of it, or it is above the cap), ends it
                  the same way.
                  Read the status, not the absence of an error. If you need
                  to know whether the volume is there before you order, ask
                  `POST /estimate` for the same `energy_units` and read
                  `coverage.complete`.

                  It is per position. In a batch, one position may accept a
                  short fill while another insists on the whole volume.
        duration_s:
          type: integer
          default: 300
          examples: [300]
          description: |
            The lease, in seconds — same rule and same allowed values as in
            mode `a` (`products[].duration_s` of `GET /tariff`), default
            `300`.

            This is the mode where a long lease means most: there is no
            transfer to send, so the whole product is "this wallet has
            energy until `send_before`". The item still ends `expired` when
            the window closes, and that is the lease running out — the
            normal end, not a failure.

            **A position asking for more than 131,000 `energy_units`
            requires 3600 or more here**, and the default will not do: the
            volume arrives in pieces whose leases start at their own
            delegations, seconds apart. The order is refused as a whole —
            one such position is enough — with `400 invalid_request` and
            `details.reason = bulk_needs_longer_lease`.
        client_ref:
          anyOf:
            - type: string
              maxLength: 128
            - type: "null"
          description: Your identifier for reconciliation

    OrderItem:
      type: object
      required:
        [
          id,
          from,
          to,
          kind,
          energy_units,
          energy_delivered,
          price_trx,
          status,
          txid,
          error,
        ]
      properties:
        id: { type: string }
        from: { $ref: "#/components/schemas/TronAddress" }
        to:
          anyOf:
            - $ref: "#/components/schemas/TronAddress"
            - type: "null"
          description: >-
            `null` in mode `c`: the order named a wallet to energise and no
            recipient.
        kind: { $ref: "#/components/schemas/ItemKind" }
        energy_units:
          type: integer
          description: |
            The volume **ordered**, in units, and the basis of `price_trx`:
            the price is this number times the position's per-unit price —
            set when the order was created (the current price, or on a `bulk`
            position our cost floor for the volume where that was higher, see
            `energy_units` in the `POST /orders` request) and raised at
            fulfillment only by the rule in "Order price" in the
            introduction. What arrives does not move it.
        energy_delivered:
          type: integer
          nullable: true
          description: |
            The energy confirmed on chain for this position, in units.

            `null` until it is confirmed, and `null` for good on a position
            that named a `kind` rather than a volume: there the delivery
            requirement is the transfer's cost, not a number the client
            chose, and it is met or the position fails (§2.2 of the API
            spec).

            On a `bulk` position it is the number the charge is counted
            from, where the position recorded one. Equal to `energy_units`
            on a full fill; below it when the fill ended short — either
            because the position allowed a short one from the start
            (`allow_partial: true`), or because the market moved after the
            buying had begun and what was already delegated to your wallet
            could not be taken back. Either way the charge is at most
            `energy_delivered` at the same per-unit price (lower only under a
            private arrangement), the rest of the hold is released, and the order ends `partially_completed`. A
            position that closed with this still `null` — the lease ran out
            before a reading of the chain succeeded — is charged for what
            was bought for it, capped at `energy_units`. The charge itself,
            whichever way it was counted, is on the order as `charged_trx`.

            **A measurement within half a percent of `energy_units` is
            reported as `energy_units` exactly.** Suppliers hand over
            slightly under a round figure and the reading is taken between
            blocks, so a delivery you got in full lands a few hundred units
            short of the order. Reporting that as a shortfall would bill you
            short, refund the difference and close the order
            `partially_completed` over a measurement error. Below that band
            the number is the measurement itself.

            **Never above `energy_units`, and that is a cap rather than an
            observation.** What lands on the wallet can be more than you
            ordered — a supplier rounds a piece up to its product's size, and
            anyone at all may delegate to your wallet while we are filling —
            so the measurement can exceed the order, and this field is the
            measurement cut down to what you asked for. The extra energy is
            on the wallet and yours to spend: it is never billed, and a
            position that got more than it ordered is a full fill, not a
            different kind of one.
        price_trx: { $ref: "#/components/schemas/TRX" }
        status: { $ref: "#/components/schemas/ItemStatus" }
        txid: { type: string, nullable: true }
        error: { $ref: "#/components/schemas/ItemError" }

    Order:
      type: object
      required:
        [
          id,
          mode,
          status,
          duration_s,
          total_trx,
          quoted_total_trx,
          charged_trx,
          burn_cost_trx,
          send_before,
          fund_before,
          client_ref,
          items,
          error_code,
          created_at,
          updated_at,
        ]
      properties:
        id: { type: string, examples: [ord_9c1f2a] }
        mode:
          type: string
          enum: [a, b, c]
        status: { $ref: "#/components/schemas/OrderStatus" }
        duration_s:
          type: integer
          examples: [300]
          description: |
            The lease this order was sold as, in seconds — the value you
            sent or the default that stood in for it. Always present, on
            every order however old: an order created before the field
            existed was a five-minute one and says so.

            Read it rather than remembering what you asked for. It is the
            product the price was taken from and the term `send_before` was
            counted off, and it is fixed at creation: a product switched off
            afterwards does not change an order already sold.
        total_trx:
          allOf: [{ $ref: "#/components/schemas/TRX" }]
          description: |
            The price of the order now — the amount the hold stands at. It is
            `quoted_total_trx` unless a position was raised to the market at
            fulfillment (see "Order price" in the introduction): each raise
            adds the difference here, held from your balance and announced by
            `order.repriced`, and a volume raise taken back lowers it again,
            never below `quoted_total_trx`. A position that fails after a
            raise is refunded whole, the raise included, and `total_trx`
            keeps the raised figure. What the order finally cost is
            `charged_trx`.
        quoted_total_trx:
          allOf: [{ $ref: "#/components/schemas/TRX" }]
          description: |
            The order's total at creation — the amount the hold was placed
            for. It never changes. Equal to `total_trx` unless a position was
            raised to the market at fulfillment; the difference between the
            two is what the raises added.
        charged_trx:
          anyOf:
            - $ref: "#/components/schemas/TRX"
            - type: "null"
          description: |
            What the order actually cost once it settled — the amount taken
            from the hold. `null` while the order is open: the hold stands
            at `total_trx` and nothing has been charged yet.

            On `completed` it equals `total_trx`, raises included. On
            `partially_completed` it is below it: a volume position
            (`kind: bulk`) is charged for the units that were delivered, at
            the per-unit price the position stands at when the order settles
            — `energy_delivered` on the position shows those
            units where the position recorded them — and a position that
            failed in a batch is not charged at all; the difference came
            back to your balance as a `hold_release`. On `failed` and
            `canceled` it is `0.000000`: nothing was charged; a hold, where
            one had been placed, was released whole; an order that was
            parked in `awaiting_funds` never had one, so its ledger shows
            neither a `charge` nor a `hold_release`.

            The same figure the closing `order.completed`,
            `order.partially_completed` and `order.failed` events carry as
            `charged_trx`, and the amount of the `charge` entry this order
            left in `GET /ledger` (no such entry is written for a zero).
        burn_cost_trx:
          allOf: [{ $ref: "#/components/schemas/TRX" }]
          description: |
            Informational — what the transfer would have cost by burning
            TRX. Locked at order creation using the network's burn price in
            effect and never recalculated: it is the base for the savings
            in `GET /stats/savings`.
        send_before:
          type: string
          format: date-time
          nullable: true
          description: |
            Appears with the `ready` status. Send the transaction before
            this moment. Counted from the last confirmed delegation in the
            order, so in a batch the deadline is shared by all items, and
            bounded by the order's first successful purchase: energy cannot
            start before it was bought, and the promise can only be as long
            as the oldest energy in the order allows. That bound applies to
            every position — in a batch the first transfer's energy is
            bought before the last one's, so a batch's window can be shorter
            than the lease less the margin. A volume position (`kind: bulk`)
            is the same rule over its chunks: its energy arrives over an
            interval, and the earliest delivered chunk is the purchase that
            bounds the window.

            The window is `duration_s` less a 3-second safety margin — 297
            seconds on the five-minute product, 3597 on the hourly one,
            86 397 on the daily one. The 3 seconds are the same on every
            product, and they are arithmetic rather than slack: they make
            the window end before the lease does and nothing more. The gap
            between the delegation we saw confirmed and the lease the
            network actually started — a block, plus the cycle on which we
            poll for it — is normally wider than that margin, so on most
            orders this deadline falls **after** the energy on the address
            is already gone. That is the ordinary case, not an edge one:
            treat the last seconds of the window as unavailable, because a
            transfer sent there burns your TRX at full price and the charge
            is not refunded. Send on `ready`, not on the deadline.

            In mode `b` it is never later than the expiry of the signed
            transaction itself, less a margin for the broadcast — a node
            refuses an expired transaction whatever energy sits on the
            address — and in a batch that means the **soonest** expiry among
            the items. Read the field rather than assuming the full window:
            a transaction sent to us with little life left gets a short one.
        fund_before:
          type: string
          format: date-time
          nullable: true
          description: |
            Present only while the status is `awaiting_funds` (and after it,
            as the record of that wait). The deposit has to be **credited**
            by this moment — not merely sent — for the order to be funded;
            a TRON deposit is credited after three confirmations.

            It is the sooner of two deadlines: ten minutes from acceptance,
            and the expiry of your own signed transaction less the margin
            the purchase and delegation need. A transaction with little
            life left therefore gets a short window, and one with too
            little to be worth parking is refused with the ordinary `402`
            instead. Read the field rather than assuming ten minutes.
        client_ref: { type: string, nullable: true }
        items:
          type: array
          items: { $ref: "#/components/schemas/OrderItem" }
        error_code: { $ref: "#/components/schemas/OrderErrorCode" }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    ProductTariff:
      type: object
      description: |
        One lease on sale and its price now. Products are priced
        independently against the market — a day is not five minutes times
        288 — so every field here is about this `duration_s` and nothing in it
        can be derived from another entry.

        The price unit is the one used everywhere else in this contract:
        **sun per unit of energy for the whole lease**. A one-day product at
        110 sun/unit costs 110 sun per unit for the whole day, not per hour;
        nothing here is a rate to be multiplied by time.
      required: [duration_s, current_price_sun, custom, typical_price_trx]
      properties:
        duration_s:
          type: integer
          examples: [3600]
          description: |
            The lease in seconds — the value to send as `duration_s` in
            `POST /orders` and `POST /estimate`. One of `300`, `3600`,
            `86400`.
        current_price_sun:
          type: integer
          examples: [23]
          description: |
            What one unit of energy costs on this product right now, in sun,
            for the whole lease. This is the number an order of this
            duration is priced at if it is created now.
        custom:
          type: boolean
          description: |
            `true` — for this product your agreed price is in force now;
            `false` — the public price. Per product: prices may be agreed for
            one lease and not for another. Only a request with a key can see
            `true`.
          examples: [false]
        typical_price_trx:
          type: object
          description: Approximate price of a single transfer on this lease
          required: [single, double]
          properties:
            single: { $ref: "#/components/schemas/TRX" }
            double: { $ref: "#/components/schemas/TRX" }

    Settings:
      type: object
      required: [baseline_price_sun, balance_low_threshold_trx, auto_topup]
      properties:
        baseline_price_sun:
          type: integer
          nullable: true
          description: Your current price per unit of energy with another provider — for savings statistics
          examples: [40]
        balance_low_threshold_trx:
          allOf: [{ $ref: "#/components/schemas/TRX" }]
          description: Threshold for the `balance.low` event
        auto_topup: { $ref: "#/components/schemas/AutoTopup" }

    AutoTopup:
      type: object
      required: [enabled, target_trx, min_trx, max_per_day_trx]
      description: |
        Whether — and how much — we should ask you to top up. Always present,
        `enabled: false` with zeroes for an account that has never set it.

        With it off, a `402` is exactly the `402` it always was and nothing is
        written to `GET /topup-requests`. With it on, a refused order raises
        a top-up request and sends `topup.requested`; so does a balance under
        `balance_low_threshold_trx`, provided there is a `target_trx` to fill
        to. How much is asked for is under `target_trx` and `min_trx` below.
      properties:
        enabled:
          type: boolean
          description: |
            Requires `max_per_day_trx` above zero. The rule is checked on the
            **resulting** settings, so an account that already has a cap may
            send `enabled` on its own.
        target_trx:
          allOf: [{ $ref: "#/components/schemas/TRX" }]
          description: |
            The balance a request tops you up to. A refused order asks for
            the shortfall plus `min_trx`, or for the fill up to this level,
            whichever is larger; a low balance asks for the fill alone,
            lifted to `min_trx` when the fill is smaller. A low balance at or
            above this level is not asked for anything.

            `"0.000000"` — no target: a refused order then asks for the
            shortfall plus `min_trx`, and a low balance alone asks for
            nothing — there is no level to fill to, and `min_trx` is never
            asked for on its own, so no `topup.requested` goes out.

            When both are set, this must be at least
            `balance_low_threshold_trx`, or `PATCH /settings` answers
            `400 invalid_request` naming the field: between the two the
            balance would count as low and as already sufficient at once, and
            no request would be raised.
        min_trx:
          allOf: [{ $ref: "#/components/schemas/TRX" }]
          description: |
            Added on top of a shortfall, so paying a request does not leave
            you at zero and the next order refused again. On a low balance it
            is a floor rather than an addition: the fill up to `target_trx`
            is lifted to it when smaller, and it never raises a request by
            itself.
        max_per_day_trx:
          allOf: [{ $ref: "#/components/schemas/TRX" }]
          description: |
            The ceiling on everything requested within one UTC day. A request
            is clipped to what is left of it, and no request is made at all if
            the clipped amount would not cover the shortfall that prompted it —
            an amount that cannot unblock your order is worse than none.
            Cancelling a request gives its room back; letting one expire does
            not, because the money may still arrive.

    AutoTopupPatch:
      type: object
      description: |
        An edit of the auto-top-up policy. Only the fields you send change; a
        `null` in any of them means "not sent", the same as leaving it out.
      properties:
        enabled:
          anyOf:
            - type: boolean
            - type: "null"
        target_trx:
          anyOf:
            - $ref: "#/components/schemas/TRX"
            - type: "null"
        min_trx:
          anyOf:
            - $ref: "#/components/schemas/TRX"
            - type: "null"
        max_per_day_trx:
          anyOf:
            - $ref: "#/components/schemas/TRX"
            - type: "null"

    TopupRequestStatus:
      type: string
      description: |
        `open` — we are waiting for the money; `fulfilled` — deposits since the
        request covered it (or your `target_trx` was reached by some other
        route); `expired` — nobody answered within a day; `canceled` — you
        withdrew it. Only `open` can be cancelled.
      enum: [open, fulfilled, expired, canceled]

    TopupRequestReason:
      type: string
      description: |
        `order_insufficient_balance` — an order was refused just now and is
        waiting on this deposit; `balance_low` — nothing has failed yet, the
        available balance simply fell under your threshold.

        **This can change on a request you have already seen.** It escalates
        one way, `balance_low` → `order_insufficient_balance`, when an order is
        refused while the request is open, and the escalation re-sends
        `topup.requested` even if `amount_trx` did not move.
      enum: [order_insufficient_balance, balance_low]

    TopupRequest:
      type: object
      required:
        [
          id,
          status,
          reason,
          amount_trx,
          deposit_address,
          order_id,
          expires_at,
          fulfilled_at,
          fulfilled_txid,
          created_at,
          updated_at,
        ]
      properties:
        id: { type: string }
        status: { $ref: "#/components/schemas/TopupRequestStatus" }
        reason: { $ref: "#/components/schemas/TopupRequestReason" }
        amount_trx:
          allOf: [{ $ref: "#/components/schemas/TRX" }]
          description: |
            How much to send. Raised, never lowered, while the request is
            open: a further shortfall replaces this with the larger figure and
            re-sends `topup.requested` with the same `id`. It can also stay the
            same across a re-send — see `reason`, which escalates on its own.
        deposit_address:
          allOf: [{ $ref: "#/components/schemas/TronAddress" }]
          description: |
            Where to send it — your deposit address as of the moment the
            request was made, not a live lookup. It is the address the webhook
            named, and it stays the same for the life of the request.
        order_id:
          type: string
          nullable: true
          description: |
            The order waiting on this money, when there is one. `null` for a
            `balance_low` request — and `null` for a refused order too: the
            order was not created, which is what the refusal means.
        expires_at: { type: string, format: date-time }
        fulfilled_at: { type: string, format: date-time, nullable: true }
        fulfilled_txid:
          type: string
          nullable: true
          description: |
            The transaction whose credit closed the request — the last one
            counted, not the whole story: several transfers may add up to one
            request.
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    MaintenanceRuleStatus:
      type: string
      enum: [active, paused]
      description: |
        `paused` — the rule neither spends nor tops up. Set by you (PATCH)
        or by the system when the balance cannot cover the daily hold
        (`paused_reason: insufficient_balance`). Resumed only by an
        explicit PATCH.

    MaintenanceRuleCreate:
      type: object
      required: [address, daily_budget_trx]
      properties:
        address:
          allOf: [{ $ref: "#/components/schemas/TronAddress" }]
          description: The wallet on which energy is maintained
        daily_budget_trx:
          allOf: [{ $ref: "#/components/schemas/TRX" }]
          description: |
            The rule's spending cap per UTC day. Mandatory. Reserved from
            the available balance like an order hold; the remainder is
            released at the day boundary.

            No less than the `maintenance_price_trx.double` rate from
            `GET /tariff` — the rule's first top-up is charged at that rate
            and would not fit into a smaller budget — and no more than
            1,000,000 TRX.

    MaintenanceRulePatch:
      type: object
      # Both fields are optional: only what is sent changes. An empty body
      # is a legal no-op — the rule is returned as is. Budget bounds are
      # the same as at creation: a bound enforced only at creation is a
      # bound bypassed by a second request.
      properties:
        status:
          anyOf:
            - $ref: "#/components/schemas/MaintenanceRuleStatus"
            - type: "null"
        daily_budget_trx:
          anyOf:
            - $ref: "#/components/schemas/TRX"
            - type: "null"

    MaintenanceRule:
      type: object
      required:
        [
          id,
          address,
          status,
          paused_reason,
          daily_budget_trx,
          spent_today_trx,
          last_topup_at,
          created_at,
          updated_at,
        ]
      properties:
        id: { type: string, examples: [mnt_4b7d1c] }
        address: { $ref: "#/components/schemas/TronAddress" }
        daily_budget_trx: { $ref: "#/components/schemas/TRX" }
        status: { $ref: "#/components/schemas/MaintenanceRuleStatus" }
        paused_reason:
          anyOf:
            - type: string
              const: insufficient_balance
            - type: "null"
          description: |
            Set when the rule was stopped by the **system**: the available
            balance could not cover a new daily hold. A pause set by you
            has no reason (`null`) — this difference shows whether the rule
            is waiting for a deposit or for your decision.
        spent_today_trx:
          allOf: [{ $ref: "#/components/schemas/TRX" }]
          description: Charged against the daily budget during the current UTC day
        last_topup_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    # ---------------------------------------------------------- address book
    # `api-spec.md` §13. The per-entry bounds below are also CHECKs on
    # `address_book_entries` (migration `0081`).

    AddressBookEntryCreate:
      type: object
      required: [address, name]
      properties:
        address: { $ref: "#/components/schemas/TronAddress" }
        name:
          type: string
          minLength: 1
          maxLength: 64
          description: Trimmed of surrounding spaces; 1–64 characters after that.
        note:
          type: string
          nullable: true
          maxLength: 280
          description: Empty or blank is stored as `null`.
        tags:
          type: array
          maxItems: 50
          items:
            type: string
            minLength: 1
            maxLength: 32
          description: |
            Up to ten distinct tags. Each is trimmed and must then be 1–32
            characters with no comma, `|`, carriage return or line feed.
            Compared by Unicode case folding: a tag repeated in another case
            keeps its first spelling, and a tag your book already uses is
            stored in the book's spelling. The ten are counted after that
            collapse; the array itself may carry at most 50 items. Order is
            kept. Omitted, the entry has none.

    AddressBookEntryUpdate:
      type: object
      # Every field is optional: only what is sent changes, and an empty body
      # is a legal no-op. `name` and `tags` have no null form — omit them to
      # leave them; `note: null` clears the note. `address` and any other key
      # this schema does not define are ignored.
      properties:
        name:
          type: string
          minLength: 1
          maxLength: 64
        note:
          type: string
          nullable: true
          maxLength: 280
        tags:
          type: array
          maxItems: 50
          items:
            type: string
            minLength: 1
            maxLength: 32
          description: |
            Replaces the whole array. Same rules as on creation: up to ten
            distinct tags, at most 50 items as sent.

    AddressBookEntry:
      type: object
      required:
        [id, address, name, note, tags, created_at, updated_at, usage, chain]
      properties:
        id: { type: string }
        address: { $ref: "#/components/schemas/TronAddress" }
        name: { type: string }
        note: { type: string, nullable: true }
        tags:
          type: array
          items: { type: string }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        usage:
          type: object
          description: |
            What this account did with the address, computed when you read
            it from the account's own history and nobody else's. Keyed by
            the address, not by the entry: an address deleted and saved
            again shows the same numbers.
          required:
            [
              orders_as_sender,
              orders_as_recipient,
              last_used_at,
              auto_refill_rule_id,
              queue_session_id,
            ]
          properties:
            orders_as_sender:
              type: integer
              description: Order items of this account sent from the address (`from`).
            orders_as_recipient:
              type: integer
              description: Order items of this account sent to the address (`to`).
            last_used_at:
              type: string
              format: date-time
              nullable: true
              description: |
                The latest creation time among this account's order items
                (either side), queue sessions (sender), queue items
                (recipient) and auto-refill rules on the address. `null` —
                never used.
            auto_refill_rule_id:
              type: string
              nullable: true
              description: This account's live (`active` or `paused`) auto-refill rule on the address.
            queue_session_id:
              type: string
              nullable: true
              description: This account's live (`created`, `running` or `paused`) queue session on the address.
        chain:
          type: object
          nullable: true
          description: |
            `GET /address-check` for the address, minus `address`. Present
            only on a list read with `include=chain` that reached the
            network; `null` otherwise — see `chain_unavailable` on the page.
          required: [activated, holds_usdt, blacklisted, is_contract, expected_kind]
          properties:
            activated: { type: boolean }
            holds_usdt: { type: boolean }
            blacklisted: { type: boolean }
            is_contract: { type: boolean }
            expected_kind: { $ref: "#/components/schemas/TransferKind" }

    AddressBookImport:
      type: object
      required: [entries]
      properties:
        entries:
          type: array
          minItems: 1
          maxItems: 500
          description: |
            Each row has the shape of `AddressBookEntryCreate`, but is judged
            on its own: a row that breaks it is an `error` in the result, not
            a refusal of the body. Only a row that is not an object refuses
            the body.
          items: { $ref: "#/components/schemas/AddressBookEntryCreate" }

    AddressBookImportResult:
      type: object
      required: [results, created, exists, errors]
      properties:
        results:
          type: array
          description: One per row of the body, in body order.
          items:
            type: object
            required: [index, status, id, reason]
            properties:
              index:
                type: integer
                description: The row's position in `entries`, from 0.
              status:
                type: string
                enum: [created, exists, error]
              id:
                type: string
                nullable: true
                description: |
                  `created` — the new entry; `exists` — the entry already
                  saved for the address; `error` — `null`.
              reason:
                type: string
                nullable: true
                enum:
                  - invalid_address
                  - invalid_name
                  - invalid_note
                  - invalid_tags
                  - duplicate_in_request
                  - entries_limit_reached
                  - tags_limit_reached
                description: Set only when `status` is `error`.
        created: { type: integer }
        exists: { type: integer }
        errors: { type: integer }

    AddressBookSuggestion:
      type: object
      required: [address, orders_as_sender, orders_as_recipient, last_used_at]
      properties:
        address: { $ref: "#/components/schemas/TronAddress" }
        orders_as_sender:
          type: integer
          description: Order items of this account sent from the address.
        orders_as_recipient:
          type: integer
          description: Order items of this account sent to the address.
        last_used_at:
          type: string
          format: date-time
          description: |
            The latest creation time among this account's order items,
            queue sessions, queue items and auto-refill rules on the address.

    AddressBookTag:
      type: object
      required: [tag, count]
      properties:
        tag:
          type: string
          description: The tag as the book spells it.
        count:
          type: integer
          description: Entries carrying the tag.

    AddressBookTagRename:
      type: object
      required: [from, to]
      properties:
        from:
          type: string
          minLength: 1
          maxLength: 32
        to:
          type: string
          minLength: 1
          maxLength: 32

    AddressBookTagDelete:
      type: object
      required: [tag]
      properties:
        tag:
          type: string
          minLength: 1
          maxLength: 32

    AddressBookBulkTags:
      type: object
      required: [ids]
      description: At least one of `add` and `remove` must name a tag.
      properties:
        ids:
          type: array
          minItems: 1
          maxItems: 500
          items: { type: string, format: uuid }
          description: Entry ids; a repeated id counts once.
        add:
          type: array
          maxItems: 10
          items:
            type: string
            minLength: 1
            maxLength: 32
          description: |
            Tags to put on every listed entry, after `remove`. At most ten
            items as sent.
        remove:
          type: array
          maxItems: 10
          items:
            type: string
            minLength: 1
            maxLength: 32
          description: |
            Tags to take off every listed entry, before `add`. At most ten
            items as sent.

    AddressBookUpdated:
      type: object
      required: [updated]
      properties:
        updated:
          type: integer
          description: Entries actually changed.

    AddressBookBulkDelete:
      type: object
      required: [ids]
      properties:
        ids:
          type: array
          minItems: 1
          maxItems: 500
          items: { type: string, format: uuid }
          description: |
            Entry ids; a repeated id counts once, and one that is not an
            entry of your book is skipped.

    AddressBookDeleted:
      type: object
      required: [deleted]
      properties:
        deleted:
          type: integer
          description: Entries this call deleted.

    # ------------------------------------------------------------ queue mode
    # `api-spec.md` §12. The vocabularies below are the same closed lists the
    # spec carries in its `queue-vocabulary` block, and the contract test
    # `test_queue_statuses_are_one_list_in_three_places` holds the two together
    # with the constants of `app/services/queue_state.py` once that module lands.

    USDTAmount:
      type: string
      pattern: '^\d+(\.\d{1,6})?$'
      description: |
        A USDT amount as a decimal string — no float, like `TRX`. Up to six
        fractional digits are accepted on input (`"120.5"`, `"1000"`);
        responses always carry six (`"120.500000"`).

    QueueSessionStatus:
      type: string
      enum: [created, running, paused, completed, stopped]
      description: |
        `created` — the queue is recorded, nothing is reserved or bought yet;
        `running` — buying; `paused` — not buying until the cause clears,
        which it does by itself (see `QueueSessionReason`); `completed` — the
        queue was exhausted and the last delivered packet has expired;
        `stopped` — you stopped it. The last two are final.

    QueueSessionReason:
      type: string
      enum:
        - client_start
        - client_stop
        - insufficient_balance
        - hold_exhausted
        - service_paused
        - balance_restored
        - hold_restored
        - service_resumed
        - queue_exhausted
      description: |
        Why the session is in its current status — the reason of the last
        transition. Pauses: `insufficient_balance` — the wallet's USDT
        balance is below the next transfer's amount; `hold_exhausted` — the
        available balance could not cover even the next packet, at the price
        that packet is sold at (which can be above the tariff, see
        `queue.packet_delivered`); the session resumes by itself once a
        deposit covers the difference;
        `service_paused` — the service is not accepting orders right now.
        Each pause lifts itself when its cause clears: `balance_restored`,
        `hold_restored`, `service_resumed`. `queue_exhausted` closes a
        session as `completed`; `client_stop` closes it as `stopped`;
        `client_start` is a running session that has not paused yet.

    QueueItemStatus:
      type: string
      enum: [pending, sent, skipped]
      description: |
        `pending` — waiting for your transfer; `sent` — your transfer to this
        recipient was seen on-chain; `skipped` — this item was at the head of
        the queue and was not seen sent within the skip window, so the queue
        moved past it. A skipped item is not re-queued.

    QueueItemReason:
      type: string
      enum: [transfer_seen, not_sent_in_time]
      description: |
        `transfer_seen` goes with `sent`, `not_sent_in_time` with `skipped`;
        `null` while the item is `pending`.

    QueueItemInput:
      type: object
      required: [to, amount_usdt]
      properties:
        to:
          allOf: [{ $ref: "#/components/schemas/TronAddress" }]
          description: The recipient of the USDT transfer
        amount_usdt:
          allOf: [{ $ref: "#/components/schemas/USDTAmount" }]
          description: |
            The amount you are going to send. It is what the session checks
            the wallet's USDT balance against before buying energy for this
            item, and what matches your transfer to the item when several
            items name the same recipient.

    QueueSessionCreate:
      type: object
      required: [from]
      properties:
        from:
          allOf: [{ $ref: "#/components/schemas/TronAddress" }]
          description: |
            The sender wallet. Must be activated, must not be a contract and
            must not be on the USDT blacklist. One live session per wallet.
        target_units:
          type: integer
          minimum: 65000
          default: 1000000
          description: |
            The level of free energy to keep on the wallet, in energy units.
            A floor, not a purchase size: the session never holds more
            energy than the next transfers in the queue need. Not below
            65 000 — what one transfer to an address that already holds USDT
            costs: a target under that is a level no transfer can leave from,
            and it is refused rather than rounded up. The default and the
            ceiling are the service's settings (`api-spec.md` §12.8);
            above the ceiling — `400 invalid_request` with `details.max_units`.
        items:
          type: array
          maxItems: 500
          items: { $ref: "#/components/schemas/QueueItemInput" }
          description: |
            The first transfers of the queue, in sending order. May be empty.
            Not together with `expected_transfers`.
        expected_transfers:
          type: integer
          nullable: true
          minimum: 1
          description: |
            A session without a list: how many transfers are coming, and
            nothing about them. Every outgoing USDT transfer of the wallet
            after Start counts as one; the level is sized by what a transfer
            of this wallet has been costing (its recent history — a transfer
            to an empty address until there is any); the USDT-balance pause
            does not apply, and items cannot be appended — create another
            session for more. One of `items` and `expected_transfers`, never
            both (`400 invalid_request`, `details.reason =
            items_or_expected_transfers`); at most the per-session ceiling
            (`400 invalid_request`, `details.reason =
            expected_transfers_out_of_range` with `min` and `max`).

    QueueItemsAppend:
      type: object
      required: [items]
      properties:
        items:
          type: array
          minItems: 1
          maxItems: 500
          items: { $ref: "#/components/schemas/QueueItemInput" }

    QueueItemsAppended:
      type: object
      required: [added, items_total, items_pending]
      properties:
        added:
          type: integer
          description: How many items this request appended
        items_total:
          type: integer
          description: Items in the session after the append
        items_pending:
          type: integer
          description: Items still waiting to be sent — the remaining-payments counter

    QueueNextItem:
      type: object
      required: [seq, to, amount_usdt, kind, need_units]
      properties:
        seq: { type: integer }
        to: { $ref: "#/components/schemas/TronAddress" }
        amount_usdt: { $ref: "#/components/schemas/USDTAmount" }
        kind:
          anyOf:
            - $ref: "#/components/schemas/TransferKind"
            - type: "null"
          description: The transfer kind of the recipient as last checked; `null` until checked
        need_units:
          type: integer
          nullable: true
          description: |
            Energy the transfer needs by its `kind` — the `single` or `double`
            norm; `null` until checked, and for `custom`, whose dry-run
            measurement is taken on the keeper's pass and not stored on the item

    QueueCounters:
      type: object
      description: |
        The session's counters. `items_pending` is the remaining-payments
        counter; `packets_confirmed` counts every packet whose delivery was
        seen on-chain, including those whose lease has since ended;
        `units_delivered` and `charged_trx` sum those packets.
      required:
        [
          items_total,
          items_pending,
          items_sent,
          items_skipped,
          packets_bought,
          packets_confirmed,
          units_delivered,
          charged_trx,
        ]
      properties:
        items_total: { type: integer }
        items_pending: { type: integer }
        items_sent: { type: integer }
        items_skipped: { type: integer }
        packets_bought: { type: integer }
        packets_confirmed: { type: integer }
        units_delivered: { type: integer }
        charged_trx: { $ref: "#/components/schemas/TRX" }

    QueueSession:
      allOf:
        - $ref: "#/components/schemas/QueueCounters"
        - type: object
          required:
            [
              id,
              from,
              target_units,
              expected_transfers,
              status,
              reason,
              hold_trx,
              free_energy_units,
              free_energy_at,
              usdt_balance,
              usdt_balance_at,
              next_item,
              created_at,
              started_at,
              stopped_at,
              updated_at,
            ]
          properties:
            id: { type: string }
            from: { $ref: "#/components/schemas/TronAddress" }
            target_units: { type: integer }
            expected_transfers:
              type: integer
              nullable: true
              description: |
                The count a session without a list was created with; `null`
                on a session with a list. On a count-only session
                `items_total` is this number, `items_sent` counts every
                outgoing USDT transfer since Start, `items_pending` is what is
                left, and `next_item` is always `null`.
            status: { $ref: "#/components/schemas/QueueSessionStatus" }
            reason:
              anyOf:
                - $ref: "#/components/schemas/QueueSessionReason"
                - type: "null"
              description: The reason of the last status transition; `null` on a `created` session
            hold_trx:
              allOf: [{ $ref: "#/components/schemas/TRX" }]
              description: |
                What is currently reserved on your balance for this session —
                the remainder of its hold. `"0.000000"` before Start and once
                the session has settled.
            free_energy_units:
              type: integer
              nullable: true
              description: Free energy on the wallet at the last uncached reading; `null` before the first
            free_energy_at: { type: string, format: date-time, nullable: true }
            usdt_balance:
              anyOf:
                - $ref: "#/components/schemas/USDTAmount"
                - type: "null"
              description: The wallet's USDT balance at the last reading; `null` before the first
            usdt_balance_at: { type: string, format: date-time, nullable: true }
            next_item:
              anyOf:
                - $ref: "#/components/schemas/QueueNextItem"
                - type: "null"
              description: The head of the queue — the next transfer we expect; `null` when nothing is pending
            created_at: { type: string, format: date-time }
            started_at: { type: string, format: date-time, nullable: true }
            stopped_at:
              type: string
              format: date-time
              nullable: true
              description: When buying ended — set on `completed` and on `stopped` alike
            updated_at: { type: string, format: date-time }

    QueueItem:
      type: object
      required: [seq, to, amount_usdt, kind, status, reason, sent_txid, sent_at]
      properties:
        seq:
          type: integer
          description: 1-based position in the queue, in append order
        to: { $ref: "#/components/schemas/TronAddress" }
        amount_usdt: { $ref: "#/components/schemas/USDTAmount" }
        kind:
          anyOf:
            - $ref: "#/components/schemas/TransferKind"
            - type: "null"
          description: |
            The recipient's transfer kind as last checked — re-read while the
            item is within the sizing window, because a recipient's USDT
            balance can change between append and send; `null` until checked.
        status: { $ref: "#/components/schemas/QueueItemStatus" }
        reason:
          anyOf:
            - $ref: "#/components/schemas/QueueItemReason"
            - type: "null"
        sent_txid:
          type: string
          nullable: true
          description: The transfer we matched to this item; `null` unless `sent`
        sent_at: { type: string, format: date-time, nullable: true }

    QueueStartedData:
      type: object
      required: [session_id, from, target_units, hold_trx, counters]
      properties:
        session_id: { type: string }
        from: { $ref: "#/components/schemas/TronAddress" }
        target_units: { type: integer }
        hold_trx: { $ref: "#/components/schemas/TRX" }
        counters: { $ref: "#/components/schemas/QueueCounters" }

    QueuePacketDeliveredData:
      type: object
      description: |
        One packet, confirmed on-chain and charged. `units` is what was
        bought, `price_sun` the price per unit the packet was sold at (an
        integer, like `current_price_sun` in `GET /tariff`), `charged_trx`
        their product — this packet's charge; the session's running totals
        are in `counters`.

        `price_sun` is the five-minute tariff price of the moment of
        purchase, **or above it** when the vendor that sold the packet cost
        more than the tariff leaves our minimum margin under — then the
        lowest whole-sun price that covers that cost with the margin (see
        `POST /queue-sessions`). Read the charge from here, not from
        `GET /tariff`.
      required: [session_id, packet_id, units, price_sun, charged_trx, hold_trx, counters]
      properties:
        session_id: { type: string }
        packet_id: { type: string }
        units: { type: integer }
        price_sun: { type: integer }
        charged_trx: { $ref: "#/components/schemas/TRX" }
        hold_trx:
          allOf: [{ $ref: "#/components/schemas/TRX" }]
          description: The hold's remainder after this charge
        counters: { $ref: "#/components/schemas/QueueCounters" }

    QueuePausedData:
      type: object
      required: [session_id, reason, counters]
      properties:
        session_id: { type: string }
        reason:
          allOf: [{ $ref: "#/components/schemas/QueueSessionReason" }]
          description: "`insufficient_balance`, `hold_exhausted` or `service_paused`"
        counters: { $ref: "#/components/schemas/QueueCounters" }

    QueueResumedData:
      type: object
      required: [session_id, reason, counters]
      properties:
        session_id: { type: string }
        reason:
          allOf: [{ $ref: "#/components/schemas/QueueSessionReason" }]
          description: "`balance_restored`, `hold_restored` or `service_resumed`"
        counters: { $ref: "#/components/schemas/QueueCounters" }

    QueueCompletedData:
      type: object
      required: [session_id, reason, hold_trx, counters]
      properties:
        session_id: { type: string }
        reason:
          allOf: [{ $ref: "#/components/schemas/QueueSessionReason" }]
          description: "`queue_exhausted`"
        hold_trx:
          allOf: [{ $ref: "#/components/schemas/TRX" }]
          description: "`\"0.000000\"`: the hold is released on completion"
        counters:
          allOf: [{ $ref: "#/components/schemas/QueueCounters" }]
          description: Final — nothing is bought or charged after this event

    QueueStoppedData:
      type: object
      required: [session_id, reason, hold_trx, counters]
      properties:
        session_id: { type: string }
        reason:
          allOf: [{ $ref: "#/components/schemas/QueueSessionReason" }]
          description: "`client_stop`"
        hold_trx:
          allOf: [{ $ref: "#/components/schemas/TRX" }]
          description: |
            The hold's remainder at the moment of the stop. Not necessarily
            zero: packets bought just before the stop are still settled, each
            with its own `queue.packet_delivered`, and the remainder is
            released after the last of them.
        counters:
          allOf: [{ $ref: "#/components/schemas/QueueCounters" }]
          description: As of the stop; packets settled afterwards add to them

    WebhookEvent:
      type: string
      description: |
        `topup.*` and `maintenance.topup` are close in name and are not the
        same thing. `maintenance.topup` is **energy** delivered to a wallet
        under an auto-refill rule (§10); `topup.requested` / `topup.fulfilled`
        / `topup.expired` are about **TRX** we asked you to send to your
        deposit address. Money actually credited stays `deposit.credited`.

        `deposit.credited` is sent for a deposit of **1 TRX or more**. A
        smaller one — a wallet probing the address, change, the tail of a
        test — is credited without it: the balance moves and the `deposit`
        row is in `GET /ledger`, but no `deposit.credited` is sent, to a
        webhook or anywhere else. Exactly 1 TRX is announced. The events
        about the request and the balance are not muted: if such a deposit
        completes an open top-up request, `topup.fulfilled` still arrives,
        carrying its txid, and `balance.low` still fires if the balance stays
        under your threshold. An integration that keeps its own books to the
        last sun reconciles against `GET /balance` and
        `GET /ledger?type=deposit`, not against the events.

        `queue.*` is the life of a queue session (`api-spec.md` §12.10, the
        `queueLifecycle` entry under `webhooks:`), in the order a session
        goes through them.

        `order.repriced` is an order's price raised to the market at
        fulfillment, or a volume raise taken back (the `orderRepriced` entry
        under `webhooks:`, and "Order price" in the introduction). It is not
        a closing event: the order goes on.
      # One list in several places: `WEBHOOK_EVENTS` in the code, the two
      # enums here, the two of `openapi-cabinet.yaml` and the cabinet's own
      # lists. This one is compared with the application's `Literal` by
      # `test_response_body_matches_spec`, so a name added here alone is red.
      enum:
        - order.ready
        - order.item.sent
        - order.item.expired
        - order.completed
        - order.partially_completed
        - order.failed
        - order.repriced
        - deposit.credited
        - balance.low
        - topup.requested
        - topup.fulfilled
        - topup.expired
        - maintenance.topup
        - maintenance.budget_exhausted
        - maintenance.paused
        - queue.started
        - queue.packet_delivered
        - queue.paused
        - queue.resumed
        - queue.completed
        - queue.stopped

    DeliveredWebhookEvent:
      type: string
      description: |
        What can stand in a delivery-log row: every subscribable event plus
        `webhook.test`, the probe from `POST /webhooks/{id}/test`. The probe
        is deliberately absent from `WebhookEvent` — it cannot be subscribed
        to — but it is delivered through the same queue and shows up in the
        same log.
      # `WebhookEvent` plus the probe, in the same order: this enum is compared
      # with the application's `DeliveredEvent` literal as a list, not a set.
      enum:
        - order.ready
        - order.item.sent
        - order.item.expired
        - order.completed
        - order.partially_completed
        - order.failed
        - order.repriced
        - deposit.credited
        - balance.low
        - topup.requested
        - topup.fulfilled
        - topup.expired
        - maintenance.topup
        - maintenance.budget_exhausted
        - maintenance.paused
        - queue.started
        - queue.packet_delivered
        - queue.paused
        - queue.resumed
        - queue.completed
        - queue.stopped
        - webhook.test

    WebhookEndpoint:
      type: object
      required: [id, url, events, status, disabled_at, disabled_reason, created_at]
      properties:
        id: { type: string }
        url: { type: string, format: uri }
        events:
          type: array
          items: { $ref: "#/components/schemas/WebhookEvent" }
        status:
          type: string
          enum: [active, disabled]
          description: |
            `disabled` — we have stopped delivering here. It is set
            automatically after a run of failures (see the retry policy under
            `webhooks` below) and cannot be undone through the API: register
            a new endpoint, which issues a new signing secret, or write to
            support and ask us to switch this one back on.
        disabled_at:
          type: string
          format: date-time
          nullable: true
          description: |
            When we stopped delivering here. `null` — we never did. Read it
            together with `status`: on its own the status cannot tell a
            receiver that fell off ten minutes ago from one that fell off
            three weeks ago, and those are different conversations.
        disabled_reason:
          type: string
          nullable: true
          description: |
            Why we stopped, `null` when we did not. Three values occur:
            `too_many_failures` — too many deliveries used up all five
            attempts within 24 hours; `target_not_public` — the URL stopped
            resolving to a public address, and we do not send requests into
            private networks; `url_unusable` — no request can be built from
            the address at all, because it holds an ASCII control character.
            Registration has refused such an address since 2026-08-30, so
            `url_unusable` belongs to endpoints registered before that; it is
            terminal in the same way — waiting changes nothing about the
            string, so nothing is retried. A `disabled` endpoint with `null`
            here was switched off before we started recording the cause. Treat
            the set as open: match on the values you know and fall back to the
            text.
        created_at: { type: string, format: date-time }

    WebhookDelivery:
      type: object
      required:
        [
          id,
          event,
          event_id,
          status,
          attempts,
          response_status,
          last_error,
          last_attempt_at,
          failed_attempts,
          last_failure_at,
          last_failure_status,
          last_failure_error,
          next_retry_at,
          created_at,
        ]
      properties:
        id: { type: string }
        event: { $ref: "#/components/schemas/DeliveredWebhookEvent" }
        event_id:
          type: string
          format: uuid
          description: The same value the receiver saw in the body and header
        status: { type: string, enum: [pending, delivered, failed] }
        attempts:
          type: integer
          description: |
            Attempts made so far. A replay resets it to zero, so the row can
            read `attempts: 0` after having been tried five times.
        response_status:
          type: integer
          nullable: true
          description: |
            What the receiver answered with. `null` — there was no answer at
            all (timeout, DNS, dropped connection); a separate fact, not a
            zero.
        last_error: { type: string, nullable: true }
        last_attempt_at: { type: string, format: date-time, nullable: true }
        failed_attempts:
          type: integer
          nullable: true
          description: |
            How many attempts this delivery lost, over its whole life. The four
            fields above describe the **last** attempt only, so on a delivery
            that finally went through they describe the attempt that worked —
            this is what says whether it went through first time or after three
            refusals. It is not `attempts` minus one: a replay puts `attempts`
            back to zero and leaves this count alone, so after a replay the two
            deliberately differ. `null` — a row from before we started counting.
        last_failure_at:
          type: string
          format: date-time
          nullable: true
          description: |
            When the most recent failed attempt was. `null` — none of them
            failed.
        last_failure_status:
          type: integer
          nullable: true
          description: |
            What the receiver answered on that attempt. `null` — it did not
            answer at all (timeout, DNS, dropped connection), the same
            distinction `response_status` makes. Read it together with
            `last_failure_at`: no moment there means nothing failed.
        last_failure_error:
          type: string
          nullable: true
          description: |
            What that failure was — `HTTP 500`, `Timeout: no answer within 5s`,
            `dns: …`. Present whenever `last_failure_at` is.
        next_retry_at:
          type: string
          format: date-time
          nullable: true
          description: |
            When the next attempt is due. `null` — none is: the delivery
            either succeeded or ran out of attempts.
        created_at:
          type: string
          format: date-time
          description: When the event was queued, not when it was last tried

    WebhookTestResult:
      type: object
      required:
        [delivery_id, event_id, event, delivered, response_status, error]
      properties:
        delivery_id:
          type: string
          description: The row this probe left in the delivery log
        event_id: { type: string, format: uuid }
        event: { type: string, const: webhook.test }
        delivered:
          type: boolean
          description: Whether the receiver answered 2xx
        response_status: { type: integer, nullable: true }
        error:
          type: string
          nullable: true
          description: What got in the way. `null` — nothing did.

    WebhookPayload:
      type: object
      properties:
        event: { $ref: "#/components/schemas/DeliveredWebhookEvent" }
        event_id:
          type: string
          format: uuid
          description: |
            Deduplication key, **stable across every retry** of this event —
            automatic ones and replays requested through
            `POST /webhooks/{id}/deliveries/{delivery_id}/retry` alike. Two
            requests carrying one `event_id` are one event; process the first
            and drop the rest.

            It is inside the signed body on purpose, and mirrored in the
            `X-NRG-Event-Id` header only for convenience: a deduplication key
            that travelled outside the signature could be altered in transit,
            and a receiver dropping duplicates by it would drop a real event.
        sent_at: { type: string, format: date-time }
        data: { type: object, additionalProperties: true }

    Error:
      type: object
      properties:
        error:
          type: object
          properties:
            code:
              type: string
              description: |
                `invalid_request` — the request body or parameters failed validation;
                `invalid_address` — the address is not a valid Tron address (`400`), or it is well-formed but cannot be used for what you asked — an unactivated wallet, a contract — in which case `details.reason` says which (`422`);
                `unauthorized` — the key is missing, invalid, or the request came from an IP outside the allowlist;
                `not_found` — the entity does not exist (the same code if it belongs to another client);
                `rate_limited` — too many requests: your key is fine, the pace is not. Wait `Retry-After` seconds;
                `too_many_auth_failures` — too many refused authorizations from this credential. Waiting will not fix it: check the key and its IP allowlist.

                This is the field to branch on. `message` is prose for a
                human reading a log, it is written in English, and it may be
                reworded at any time.
              # The enum is held equal to `ERROR_CODES` in `app/core/errors.py`
              # by `test_error_codes_match_spec`; `queue_session_active`,
              # `queue_session_closed` and `wallet_busy` are the three codes of
              # queue mode (`api-spec.md` §12.12), declared on the
              # `/queue-sessions` paths; `address_book_conflict` is the address
              # book's (§13), its case in `details.reason`.
              enum:
                - invalid_request
                - invalid_address
                - unauthorized
                - blacklisted_recipient
                - insufficient_balance
                - capacity_unavailable
                - order_not_cancelable
                - topup_request_not_cancelable
                - idempotency_conflict
                - maintenance_rule_conflict
                - queue_session_active
                - queue_session_closed
                - wallet_busy
                - address_book_conflict
                - not_found
                - rate_limited
                - too_many_auth_failures
                - internal_error
            message:
              type: string
              description: |
                Human-readable explanation, in English. Not for parsing —
                everything a program needs is in `code` and `details`.
              examples: ["Key not accepted"]
            details:
              type: object
              additionalProperties: true
              description: |
                Machine-readable specifics, shaped by `code`. Empty object
                when there is nothing to add.
              properties:
                errors:
                  type: array
                  description: |
                    Which fields failed validation, and why. Present on
                    `invalid_request` and `invalid_address` whenever the
                    request was rejected by schema validation — the most
                    frequently parsed error body in this API.
                  items: { $ref: "#/components/schemas/FieldError" }

    FieldError:
      type: object
      description: One failed field inside `details.errors`.
      required: [field, message, type]
      properties:
        field:
          type: string
          description: |
            Where the value came from and what it is called, joined by dots:
            the first segment is the part of the request (`body`, `query`,
            `path`, `header`), the rest is the path to the value inside it.
            Nested and indexed values keep their whole path
            (`body.transfers.0.to`).
          examples: ["query.range", "body.transfers.0.to"]
        message:
          type: string
          description: What is wrong with this value, in English.
          examples: ["Input should be '24h', '7d' or '30d'"]
        type:
          type: string
          description: |
            The validation rule that rejected it — Pydantic's error type,
            passed through unchanged. Stable enough to branch on for the
            common cases (`missing`, `int_parsing`, `literal_error`,
            `string_too_long`), and `invalid_address` for our own address
            check. Treat an unfamiliar value as "invalid".
          examples: ["literal_error", "missing", "invalid_address"]
