openapi: 3.0.3

info:
  title: ChainForge API
  version: 1.4.0
  description: |
    The ChainForge REST API lets you read blockchain state, send transactions, deploy and call
    smart contracts, create tokens and receive event notifications.

    > ChainForge is a **fictional** product created for documentation practice. All hosts, keys,
    > addresses and identifiers are invented.

    ## Conventions
    - Requests and responses use UTF-8 **JSON**. Field names are `camelCase`.
    - **Amounts** are integers in the smallest unit (sparks for FORGE, token units for tokens),
      sent and returned as decimal **strings**. 1 FORGE = 10^18 sparks.
    - **Timestamps** are ISO 8601 in UTC, for example `2026-10-18T09:30:12Z`.
    - **Addresses** are 42-character hex strings starting with `0x`; **hashes** are 66 characters.
    - The credential's prefix selects the network: `cfk_live_` reaches Mainnet (chain ID 7700) and
      `cfk_test_` reaches the Ember testnet (chain ID 7701).

    ## Authentication
    Send a bearer token in the `Authorization` header: an API key or an OAuth 2.0 access token.
    Each endpoint lists the OAuth scope it needs.

    ## Finality and block selectors
    Many reads accept a `block` parameter: `latest` (default), `finalized`, `pending` (nonce queries
    only) or a block number. Use `finalized` for accounting and fulfilment; finalized data is never
    reversed (about 4 seconds after submission).

    ## Pagination
    List endpoints use cursor pagination: pass `limit` (1 to 100, default 25) and `cursor`. A
    response with `nextCursor: null` is the last page.

    ## Idempotency
    State-changing `POST` endpoints accept an `Idempotency-Key` header (8 to 64 characters). Reusing
    a key with the same body replays the original response for 24 hours; reusing it with a different
    body returns `409 idempotency_conflict`.

    ## Rate limits
    Free: 10 requests per second and 100,000 per day. Growth: 50 per second and 5,000,000 per day.
    `429` responses include `Retry-After`.

    ## Real-time interfaces
    WebSocket subscriptions (`wss://ws.chainforge.example/v1`) and webhook delivery payloads are
    described in the API Reference Guide. Webhook callbacks are modeled here under
    `POST /webhooks` using `callbacks`.
  termsOfService: https://chainforge.example/terms
  contact:
    name: ChainForge Developer Support
    email: developers@chainforge.example
    url: https://chainforge.example/support
  license:
    name: Apache 2.0
    url: https://www.apache.org/licenses/LICENSE-2.0.html

externalDocs:
  description: ChainForge Developer Guide and API Reference Guide
  url: https://docs.chainforge.example

servers:
  - url: https://api.chainforge.example/v1
    description: ChainForge API. The key prefix selects Mainnet (cfk_live_) or Ember (cfk_test_).
  - url: http://127.0.0.1:8545
    description: Local devnet (chain ID 7702)

tags:
  - name: Authentication
    description: Exchange OAuth client credentials for access tokens.
  - name: Status
    description: Network health, blocks and connectivity checks.
  - name: Accounts
    description: Register addresses and read balances, nonces and history.
  - name: Transactions
    description: Prepare, submit, track, speed up and cancel transactions.
  - name: Gas
    description: Estimate gas and fees.
  - name: Contracts
    description: Deploy, register, call, simulate and query smart contracts.
  - name: Tokens
    description: Create and read CFT-20 (fungible) and CFT-721 (non-fungible) tokens.
  - name: Webhooks
    description: Manage webhook endpoints, delivery history and signing secrets.
  - name: Usage
    description: Request, error and quota metrics for your project.

x-tagGroups:
  - name: Getting started
    tags: [Authentication, Status]
  - name: Core resources
    tags: [Accounts, Transactions, Gas]
  - name: Smart contracts and tokens
    tags: [Contracts, Tokens]
  - name: Events and operations
    tags: [Webhooks, Usage]

security:
  - bearerAuth: []

paths:
  # =========================================================================
  # AUTHENTICATION
  # =========================================================================
  /oauth/token:
    servers:
      - url: https://auth.chainforge.example
        description: OAuth token server (not the REST host)
    post:
      tags: [Authentication]
      operationId: createAccessToken
      summary: Request an OAuth access token
      description: |
        Exchanges OAuth client credentials for a short-lived access token (3,600 seconds) using the
        `client_credentials` grant. Send the token as a bearer token on API requests. Request a new
        token shortly before expiry and cache it in memory.

        This endpoint uses the standard OAuth 2.0 error format rather than the ChainForge error object.
      security: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              $ref: '#/components/schemas/OAuthTokenRequest'
            example:
              grant_type: client_credentials
              client_id: cfc_01JC8A5W2D
              client_secret: YOUR_CLIENT_SECRET
              scope: transactions:read transactions:write
      responses:
        '200':
          description: Token issued.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OAuthToken'
              example:
                access_token: eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.example
                token_type: Bearer
                expires_in: 3600
                scope: transactions:read transactions:write
        '400':
          description: Invalid request or scope not allowed for the client.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OAuthError'
              example:
                error: invalid_scope
                error_description: Scope 'admin' is not allowed for this client.
        '401':
          description: Client authentication failed.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OAuthError'
              example:
                error: invalid_client
                error_description: Client authentication failed.

  # =========================================================================
  # STATUS AND NETWORK
  # =========================================================================
  /status:
    get:
      tags: [Status]
      operationId: getStatus
      summary: Get network status
      description: |
        Returns the environment, network, latest block and API health for the credential's network.
        Compare `chainId` with the value you expect at application startup and refuse to run if they
        differ. This one check prevents most test-versus-production mistakes.

        Required scope: any valid credential.
      responses:
        '200':
          description: Current status.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Status'
              example:
                environment: test
                network: ember
                chainId: 7701
                latestBlock: 4820113
                finalizedBlock: 4820111
                apiVersion: v1
                status: operational
                time: '2026-10-18T09:30:12Z'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '503':
          $ref: '#/components/responses/ServiceUnavailable'

  /blocks/finalized:
    get:
      tags: [Status]
      operationId: getFinalizedBlock
      summary: Get the latest finalized block
      description: |
        Returns the most recent finalized block. Everything at or below this block number is permanent.
        Useful for "last processed block" bookkeeping.

        Required scope: any valid credential.
      responses:
        '200':
          description: The finalized block.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Block'
        '401':
          $ref: '#/components/responses/Unauthorized'

  /blocks/{blockId}:
    get:
      tags: [Status]
      operationId: getBlock
      summary: Get a block
      description: |
        Retrieves a block by number, by hash, or by the keywords `latest` and `finalized`.

        Required scope: any valid credential.
      parameters:
        - name: blockId
          in: path
          required: true
          description: A block number, a block hash, `latest` or `finalized`.
          schema:
            type: string
          examples:
            number:
              value: '4820141'
            keyword:
              value: latest
        - name: includeTransactions
          in: query
          description: When `true`, `transactions` contains full transaction objects instead of hashes.
          schema:
            type: boolean
            default: false
      responses:
        '200':
          description: The block.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Block'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'

  # =========================================================================
  # ACCOUNTS
  # =========================================================================
  /accounts:
    post:
      tags: [Accounts]
      operationId: registerAccount
      summary: Register an account
      description: |
        Registers an address with your project so the platform indexes its activity, can deliver
        `account.received` webhooks and stores your `metadata`. Registration is optional for reading
        balances. Registering an existing address updates its label and metadata and returns `200`.
        ChainForge never creates or stores private keys.

        Required scope: `transactions:write` (OAuth) or the `write` permission (API key).
      security:
        - bearerAuth: []
        - oauth2: [transactions:write]
      parameters:
        - $ref: '#/components/parameters/IdempotencyKeyOptional'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RegisterAccountRequest'
            example:
              address: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
              label: alice-test
              metadata:
                customerId: cust_1042
      responses:
        '200':
          description: An existing registration was updated.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RegisteredAccount'
        '201':
          description: Account registered.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RegisteredAccount'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'
        '429':
          $ref: '#/components/responses/TooManyRequests'

  /accounts/balances:
    get:
      tags: [Accounts]
      operationId: getBalances
      summary: Get balances for several accounts
      description: |
        Returns native balances for 1 to 50 addresses in one request. All balances are read at the
        same block, so the set is consistent. The response is not paginated. Rate-limit cost: 1
        request per 10 addresses, rounded up.

        Required scope: `accounts:read`.
      security:
        - bearerAuth: []
        - oauth2: [accounts:read]
      parameters:
        - name: addresses
          in: query
          required: true
          description: Comma-separated addresses, 1 to 50.
          schema:
            type: array
            minItems: 1
            maxItems: 50
            items:
              $ref: '#/components/schemas/Address'
          style: form
          explode: false
        - $ref: '#/components/parameters/Block'
      responses:
        '200':
          description: Balances at one block.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BalanceBatch'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '429':
          $ref: '#/components/responses/TooManyRequests'

  /accounts/{address}:
    get:
      tags: [Accounts]
      operationId: getAccount
      summary: Get an account
      description: |
        Returns an account's type, balance, nonce and (for contracts) code information. An address
        with no history is not an error: it returns `type: eoa`, `balance: "0"` and `nonce: 0`.

        Required scope: `accounts:read`.
      security:
        - bearerAuth: []
        - oauth2: [accounts:read]
      parameters:
        - $ref: '#/components/parameters/AddressPath'
        - $ref: '#/components/parameters/Block'
      responses:
        '200':
          description: The account.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Account'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'

  /accounts/{address}/balance:
    get:
      tags: [Accounts]
      operationId: getAccountBalance
      summary: Get an account's balance
      description: |
        Returns the native balance and nonce. Use `balance` (integer sparks as a string) for
        arithmetic and `balanceFormatted` for display only.

        Required scope: `accounts:read`.
      security:
        - bearerAuth: []
        - oauth2: [accounts:read]
      parameters:
        - $ref: '#/components/parameters/AddressPath'
        - $ref: '#/components/parameters/Block'
      responses:
        '200':
          description: The balance.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Balance'
              example:
                address: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
                balance: '94999937000000000000'
                balanceFormatted: '94.999937'
                symbol: tFORGE
                blockNumber: 4820141
                nonce: 1
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /accounts/{address}/nonce:
    get:
      tags: [Accounts]
      operationId: getAccountNonce
      summary: Get the next nonce
      description: |
        Returns the nonce to use for the account's next transaction. With `block=latest` or
        `finalized` it counts included transactions; with `block=pending` it also counts transactions
        waiting in the mempool, which is what you need to send several transactions in a row.

        Required scope: `accounts:read`.
      security:
        - bearerAuth: []
        - oauth2: [accounts:read]
      parameters:
        - $ref: '#/components/parameters/AddressPath'
        - name: block
          in: query
          description: Block selector. Supports `pending` in addition to the standard selectors.
          schema:
            type: string
            default: latest
      responses:
        '200':
          description: The nonce.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Nonce'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'

  /accounts/{address}/transactions:
    get:
      tags: [Accounts]
      operationId: listAccountTransactions
      summary: List an account's transactions
      description: |
        Lists transactions sent from or to an account, newest first, with cursor pagination.
        Transactions before the address was registered appear once indexing completes (usually
        within 5 minutes of the first request).

        Required scope: `accounts:read`.
      security:
        - bearerAuth: []
        - oauth2: [accounts:read]
      parameters:
        - $ref: '#/components/parameters/AddressPath'
        - name: status
          in: query
          description: Filter by transaction status.
          schema:
            $ref: '#/components/schemas/TransactionStatus'
        - name: direction
          in: query
          description: Filter by whether the account sent or received.
          schema:
            type: string
            enum: [sent, received, any]
            default: any
        - name: fromBlock
          in: query
          description: Earliest block (inclusive).
          schema:
            type: integer
            minimum: 0
        - name: toBlock
          in: query
          description: Latest block (inclusive).
          schema:
            type: integer
            minimum: 0
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: A page of transactions.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TransactionList'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'

  /accounts/{address}/nfts:
    get:
      tags: [Accounts, Tokens]
      operationId: listAccountNfts
      summary: List an account's NFTs
      description: |
        Lists the non-fungible tokens an address owns. Metadata lives off-chain and is cached by the
        platform: `metadataStatus` may be `pending`, `unreachable` or `invalid` even for a valid token.

        Required scope: `accounts:read`.
      security:
        - bearerAuth: []
        - oauth2: [accounts:read]
      parameters:
        - $ref: '#/components/parameters/AddressPath'
        - name: collection
          in: query
          description: Restrict to one or more collections (comma-separated, up to 10).
          schema:
            type: array
            maxItems: 10
            items:
              $ref: '#/components/schemas/Address'
          style: form
          explode: false
        - name: refreshMetadata
          in: query
          description: Re-fetch metadata for the returned tokens. Counts as 2 requests.
          schema:
            type: boolean
            default: false
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: A page of NFTs.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NftList'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'

  # =========================================================================
  # TRANSACTIONS
  # =========================================================================
  /transactions/prepare:
    post:
      tags: [Transactions]
      operationId: prepareTransaction
      summary: Prepare a transaction
      description: |
        Builds an unsigned transaction with the correct nonce, chain ID, gas limit and fee
        suggestions. Omitted fields are filled in automatically. The call has no effect on the chain.
        Sign `unsignedTransaction` (or `signingHash`) on your side, then submit it with
        `POST /transactions`. The API never receives a private key.

        Required scope: `transactions:write`.
      security:
        - bearerAuth: []
        - oauth2: [transactions:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PrepareTransactionRequest'
            example:
              from: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
              to: '0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF'
              value: '2000000000000000000'
              feeSpeed: normal
      responses:
        '200':
          description: The prepared transaction.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PreparedTransaction'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'
        '429':
          $ref: '#/components/responses/TooManyRequests'

  /transactions:
    post:
      tags: [Transactions]
      operationId: submitTransaction
      summary: Submit a signed transaction
      description: |
        Validates the signature, nonce, balance and fee, then broadcasts the transaction. Returns
        `202` once the transaction is accepted into the mempool, not when it is final. Track it with
        `GET /transactions/{id}`, a webhook or a subscription.

        Submitting identical signed bytes twice returns `409 already_known` with the existing
        transaction in `error.details.transaction`.

        Required scope: `transactions:write`.
      security:
        - bearerAuth: []
        - oauth2: [transactions:write]
      parameters:
        - $ref: '#/components/parameters/IdempotencyKeyRequired'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SubmitTransactionRequest'
            example:
              signedTransaction: 0x02f8730183...
              metadata:
                orderId: ord_8841
      responses:
        '202':
          description: Transaction accepted into the mempool.
          headers:
            Location:
              description: URL of the new transaction resource.
              schema:
                type: string
                format: uri
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Transaction'
              example:
                id: txn_01JC7X3M9Q
                hash: '0x9f3c5d8a1b7e44c2a09d3f6b8e1c2d4a5b6c7d8e9f00112233445566778899aa'
                status: pending
                from: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
                to: '0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF'
                value: '2000000000000000000'
                nonce: 1
                submittedAt: '2026-10-18T09:30:12Z'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'
        '429':
          $ref: '#/components/responses/TooManyRequests'

  /transactions/{id}:
    get:
      tags: [Transactions]
      operationId: getTransaction
      summary: Get a transaction
      description: |
        Retrieves a transaction by platform ID (`txn_...`) or by hash, with its status and receipt
        data. A `404` for an ID or hash created moments ago can be eventual consistency: retry for a
        few seconds.

        Required scope: `transactions:read`.
      security:
        - bearerAuth: []
        - oauth2: [transactions:read]
      parameters:
        - $ref: '#/components/parameters/TransactionId'
      responses:
        '200':
          description: The transaction.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Transaction'
              examples:
                finalized:
                  summary: A finalized transfer
                  value:
                    id: txn_01JC7X3M9Q
                    hash: '0x9f3c5d8a1b7e44c2a09d3f6b8e1c2d4a5b6c7d8e9f00112233445566778899aa'
                    status: finalized
                    from: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
                    to: '0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF'
                    value: '2000000000000000000'
                    nonce: 1
                    gasUsed: '21000'
                    effectiveGasPrice: '3000000000'
                    fee: '63000000000000'
                    blockNumber: 4820141
                    submittedAt: '2026-10-18T09:30:12Z'
                    includedAt: '2026-10-18T09:30:14Z'
                    finalizedAt: '2026-10-18T09:30:16Z'
                failed:
                  summary: A reverted contract call
                  value:
                    id: txn_01JC7Y9H4B
                    status: failed
                    revertReason: InsufficientPoints(available=250, required=10000)
                    gasUsed: '38211'
                    fee: '114633000000000'
                    blockNumber: 4821402
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'

  /transactions/{id}/speed-up:
    post:
      tags: [Transactions]
      operationId: speedUpTransaction
      summary: Speed up a pending transaction
      description: |
        Prepares a replacement with the same nonce, recipient, value and data and a fee at least 10
        percent higher. You sign and submit it with `POST /transactions`. Only `pending`
        transactions can be sped up.

        Required scope: `transactions:write`.
      security:
        - bearerAuth: []
        - oauth2: [transactions:write]
      parameters:
        - $ref: '#/components/parameters/TransactionId'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/FeeBumpRequest'
            example:
              feeSpeed: fast
      responses:
        '200':
          description: The prepared replacement.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PreparedTransaction'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /transactions/{id}/cancel:
    post:
      tags: [Transactions]
      operationId: cancelTransaction
      summary: Cancel a pending transaction
      description: |
        Prepares a zero-value transfer to the sender with the same nonce and a higher fee. If you
        sign and submit it and it is included first, the original can never execute. Cancellation is
        not guaranteed: if the original is included first, it still executes. Check the final status.

        Required scope: `transactions:write`.
      security:
        - bearerAuth: []
        - oauth2: [transactions:write]
      parameters:
        - $ref: '#/components/parameters/TransactionId'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CancelRequest'
      responses:
        '200':
          description: The prepared cancellation transaction.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PreparedTransaction'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'

  # =========================================================================
  # GAS
  # =========================================================================
  /gas/estimate:
    post:
      tags: [Gas]
      operationId: estimateGas
      summary: Estimate gas and fees
      description: |
        Executes the call against current state without committing it and returns the estimated gas
        plus fee suggestions for three speeds. If the call would revert the endpoint returns `422
        execution_reverted` with the reason, so you can pre-validate a call without spending gas.
        Add a 10 to 20 percent buffer to `gasLimit` for contract calls.

        Required scope: `transactions:read`.
      security:
        - bearerAuth: []
        - oauth2: [transactions:read]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GasEstimateRequest'
            example:
              from: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
              to: '0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF'
              value: '5000000000000000000'
      responses:
        '200':
          description: The estimate.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GasEstimate'
              example:
                gasLimit: '21000'
                baseFee: '2000000000'
                suggested:
                  slow:
                    maxFeePerGas: '3000000000'
                    maxPriorityFeePerGas: '500000000'
                    estimatedWaitSeconds: 12
                  normal:
                    maxFeePerGas: '5000000000'
                    maxPriorityFeePerGas: '1000000000'
                    estimatedWaitSeconds: 4
                  fast:
                    maxFeePerGas: '8000000000'
                    maxPriorityFeePerGas: '2500000000'
                    estimatedWaitSeconds: 2
                blockNumber: 4820141
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  # =========================================================================
  # CONTRACTS
  # =========================================================================
  /contracts:
    post:
      tags: [Contracts]
      operationId: deployContract
      summary: Prepare a contract deployment
      description: |
        Encodes constructor arguments, estimates gas and returns a prepared deployment transaction.
        Sign and submit it with `POST /transactions`. When it finalizes, the transaction record
        contains `contractAddress`. With `registerOnDeploy: true` the platform registers the ABI
        automatically.

        Required scope: `contracts:write`.
      security:
        - bearerAuth: []
        - oauth2: [contracts:write]
      parameters:
        - $ref: '#/components/parameters/IdempotencyKeyOptional'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DeployContractRequest'
      responses:
        '200':
          description: The deployment preparation.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeploymentPreparation'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /contracts/{address}:
    get:
      tags: [Contracts]
      operationId: getContract
      summary: Get a registered contract
      description: |
        Returns a registered contract's metadata, indexing status and (optionally) its ABI.

        Required scope: `contracts:read`.
      security:
        - bearerAuth: []
        - oauth2: [contracts:read]
      parameters:
        - $ref: '#/components/parameters/AddressPath'
        - name: includeAbi
          in: query
          description: Include the full ABI in the response.
          schema:
            type: boolean
            default: false
      responses:
        '200':
          description: The contract.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Contract'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'

  /contracts/{address}/register:
    post:
      tags: [Contracts]
      operationId: registerContract
      summary: Register a contract and its ABI
      description: |
        Registers an existing contract so the platform can decode calls, results, errors and events.
        Registering again with a new ABI replaces it (earlier versions are kept for decoding history).

        Required scope: `contracts:write`.
      security:
        - bearerAuth: []
        - oauth2: [contracts:write]
      parameters:
        - $ref: '#/components/parameters/AddressPath'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RegisterContractRequest'
      responses:
        '200':
          description: ABI replaced.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Contract'
        '201':
          description: Contract registered.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Contract'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'

  /contracts/{address}/call:
    post:
      tags: [Contracts]
      operationId: callContract
      summary: Call a read-only contract function
      description: |
        Executes a `view` or `pure` function and returns the decoded result. No transaction, gas or
        signature is involved. A function that changes state is rejected with `422
        function_not_readonly`. Give the full signature (for example `balanceOf(address)`) for
        overloaded functions.

        Required scope: `contracts:read`.
      security:
        - bearerAuth: []
        - oauth2: [contracts:read]
      parameters:
        - $ref: '#/components/parameters/AddressPath'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ContractCallRequest'
            example:
              function: balanceOf
              args:
                - '0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF'
              block: finalized
      responses:
        '200':
          description: The decoded result.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ContractCallResult'
              example:
                function: balanceOf
                result: '250'
                blockNumber: 4821390
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /contracts/{address}/simulate:
    post:
      tags: [Contracts]
      operationId: simulateContractCall
      summary: Simulate a state-changing call
      description: |
        Runs a function against current state without committing it and reports whether it would
        succeed, the gas it would use, the events it would emit and any revert reason. A call that
        would revert returns `200` with `success: false`, because the simulation itself worked.
        Rate-limit cost: 2 requests.

        Required scope: `contracts:read`.
      security:
        - bearerAuth: []
        - oauth2: [contracts:read]
      parameters:
        - $ref: '#/components/parameters/AddressPath'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SimulateRequest'
            example:
              function: transfer
              args:
                - '0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF'
                - '10000'
              from: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
      responses:
        '200':
          description: The simulation result.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SimulationResult'
              examples:
                succeeds:
                  value:
                    success: true
                    gasUsed: '51420'
                    result: true
                    blockNumber: 4821402
                reverts:
                  value:
                    success: false
                    revertReason: InsufficientPoints(available=250, required=10000)
                    gasUsed: '29110'
                    blockNumber: 4821402
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /contracts/{address}/events:
    get:
      tags: [Contracts]
      operationId: listContractEvents
      summary: Query contract events
      description: |
        Queries logs emitted by a registered contract, filtered by event name, block range and
        indexed arguments. Unlike most lists, results are ordered **oldest first** by default so you
        can replay in on-chain order; use `order=desc` for newest first. The pair
        (`transactionHash`, `logIndex`) is globally unique and is the right key for de-duplication.
        To filter on an indexed argument add `args.<name>=<value>` (for example `args.to=0x2B5A...`).
        Rate-limit cost: 2 requests when `limit` is above 50.

        Required scope: `contracts:read`.
      security:
        - bearerAuth: []
        - oauth2: [contracts:read]
      parameters:
        - $ref: '#/components/parameters/AddressPath'
        - name: event
          in: query
          description: One or more event names, comma-separated.
          schema:
            type: array
            items:
              type: string
          style: form
          explode: false
        - name: fromBlock
          in: query
          description: Start of range, inclusive. A block number, `latest` or `finalized`.
          schema:
            type: string
        - name: toBlock
          in: query
          description: End of range, inclusive.
          schema:
            type: string
            default: latest
        - name: finality
          in: query
          description: '`finalized` returns only final events; `included` also returns events from included blocks.'
          schema:
            type: string
            enum: [finalized, included]
            default: finalized
        - name: order
          in: query
          description: Sort order by position on chain.
          schema:
            type: string
            enum: [asc, desc]
            default: asc
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: A page of event logs.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/EventLogList'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  # =========================================================================
  # TOKENS
  # =========================================================================
  /tokens:
    post:
      tags: [Tokens]
      operationId: createToken
      summary: Prepare a token deployment
      description: |
        Prepares the deployment of a CFT-20 (fungible) or CFT-721 (non-fungible) token from an
        audited platform template. Sign and submit the returned transaction with
        `POST /transactions`. Feature flags are permanent once deployed. `initialSupply` is in the
        token's smallest unit: with 6 decimals, 1,000,000 tokens is `1000000000000`.

        Required scope: `contracts:write`.
      security:
        - bearerAuth: []
        - oauth2: [contracts:write]
      parameters:
        - $ref: '#/components/parameters/IdempotencyKeyRequired'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateTokenRequest'
            example:
              type: cft20
              name: Acme Dollar
              symbol: ACMD
              decimals: 6
              initialSupply: '1000000000000'
              maxSupply: '10000000000000'
              owner: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
              features:
                mintable: true
                burnable: true
                pausable: true
      responses:
        '200':
          description: The deployment preparation.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeploymentPreparation'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /tokens/{address}:
    get:
      tags: [Tokens]
      operationId: getToken
      summary: Get a token
      description: |
        Returns a token's standard, name, symbol, decimals, supply and features. Works for any CFT-20
        or CFT-721 contract on the network, even if it is not registered.

        Required scope: `contracts:read`.
      security:
        - bearerAuth: []
        - oauth2: [contracts:read]
      parameters:
        - $ref: '#/components/parameters/AddressPath'
        - $ref: '#/components/parameters/Block'
      responses:
        '200':
          description: The token.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Token'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'

  /tokens/{address}/balances/{holder}:
    get:
      tags: [Tokens]
      operationId: getTokenBalance
      summary: Get a holder's token balance
      description: |
        Returns how many units of a fungible token an address holds. For a CFT-721 collection,
        `balance` is the count of tokens owned; list them with `GET /accounts/{address}/nfts`.

        Required scope: `contracts:read`.
      security:
        - bearerAuth: []
        - oauth2: [contracts:read]
      parameters:
        - $ref: '#/components/parameters/AddressPath'
        - name: holder
          in: path
          required: true
          description: Address whose balance to read.
          schema:
            $ref: '#/components/schemas/Address'
        - $ref: '#/components/parameters/Block'
      responses:
        '200':
          description: The balance.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TokenBalance'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'

  # =========================================================================
  # WEBHOOKS
  # =========================================================================
  /webhooks:
    post:
      tags: [Webhooks]
      operationId: createWebhook
      summary: Create a webhook
      description: |
        Registers an HTTPS endpoint and chooses which events it receives. On creation the platform
        sends a `webhook.ping` to the URL, which must return `2xx` within 10 seconds. The response
        contains the signing `secret`, which is shown **only once**.

        Deliveries are at-least-once and signed (see `WebhookEvent` and the signature headers
        described under the callback below). A project can have up to 20 active webhooks (Free: 3).

        Required scope: `webhooks:manage`.
      security:
        - bearerAuth: []
        - oauth2: [webhooks:manage]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateWebhookRequest'
            example:
              url: https://shop.acme.example/hooks/chainforge
              description: Order payment notifications
              events:
                - transaction.finalized
                - transaction.failed
                - token.transfer
              filters:
                addresses:
                  - '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
                finality: finalized
      responses:
        '201':
          description: Webhook created. The `secret` appears only in this response.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebhookWithSecret'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'
      callbacks:
        webhookEvent:
          '{$request.body#/url}':
            post:
              summary: Event delivery
              description: |
                ChainForge sends this request to your endpoint when a subscribed event occurs.

                Respond with `2xx` within 10 seconds. Failed deliveries are retried up to 7 times
                (immediately, then after 30 s, 5 min, 30 min, 2 h, 6 h and 24 h).

                **Verify every request.** Headers: `X-ChainForge-Timestamp` (Unix seconds),
                `X-ChainForge-Signature` (`v1=<hex>`; two comma-separated values during a secret
                rotation), `X-ChainForge-Event-Id` and `X-ChainForge-Delivery-Attempt`. The signature is
                `HMAC-SHA256(secret, timestamp + "." + rawBody)` in hex. Reject timestamps more than 5
                minutes from your clock and compare in constant time.
              parameters:
                - name: X-ChainForge-Timestamp
                  in: header
                  required: true
                  description: Unix time in seconds when the request was signed.
                  schema:
                    type: integer
                - name: X-ChainForge-Signature
                  in: header
                  required: true
                  description: '`v1=` followed by the hex HMAC-SHA256 signature.'
                  schema:
                    type: string
              requestBody:
                required: true
                content:
                  application/json:
                    schema:
                      $ref: '#/components/schemas/WebhookEvent'
                    example:
                      id: evt_01JC9M7N2X
                      type: transaction.finalized
                      apiVersion: v1
                      createdAt: '2026-10-18T10:07:41Z'
                      network: ember
                      data:
                        id: txn_01JC9M6A1B
                        status: finalized
                        blockNumber: 4822095
              responses:
                '200':
                  description: Event accepted. Any `2xx` status counts as success.

    get:
      tags: [Webhooks]
      operationId: listWebhooks
      summary: List webhooks
      description: |
        Lists the webhook endpoints in your project. The signing `secret` is never included.

        Required scope: `webhooks:manage`.
      security:
        - bearerAuth: []
        - oauth2: [webhooks:manage]
      parameters:
        - name: enabled
          in: query
          description: Filter by enabled state.
          schema:
            type: boolean
        - name: event
          in: query
          description: Only webhooks subscribed to this event type.
          schema:
            $ref: '#/components/schemas/WebhookEventType'
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: A page of webhooks.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebhookList'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'

  /webhooks/{id}:
    parameters:
      - $ref: '#/components/parameters/WebhookId'
    get:
      tags: [Webhooks]
      operationId: getWebhook
      summary: Get a webhook
      description: |
        Retrieves one webhook endpoint, including its health.

        Required scope: `webhooks:manage`.
      security:
        - bearerAuth: []
        - oauth2: [webhooks:manage]
      responses:
        '200':
          description: The webhook.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Webhook'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
    patch:
      tags: [Webhooks]
      operationId: updateWebhook
      summary: Update a webhook
      description: |
        Updates the URL, events, filters, headers or enabled state. Send only the fields you want to
        change; `events`, `filters` and `headers`, when sent, replace the existing value. Changing
        `url` triggers a new verification ping. Setting `enabled` to `true` re-enables a webhook the
        platform disabled and resets its failure count.

        Required scope: `webhooks:manage`.
      security:
        - bearerAuth: []
        - oauth2: [webhooks:manage]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateWebhookRequest'
            example:
              enabled: false
      responses:
        '200':
          description: The updated webhook.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Webhook'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'
    delete:
      tags: [Webhooks]
      operationId: deleteWebhook
      summary: Delete a webhook
      description: |
        Permanently deletes the endpoint. Deliveries in progress are abandoned and history is kept for
        30 days but can no longer be redelivered. To pause delivery, disable the webhook instead.

        Required scope: `webhooks:manage`.
      security:
        - bearerAuth: []
        - oauth2: [webhooks:manage]
      responses:
        '204':
          description: Webhook deleted.
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'

  /webhooks/{id}/rotate-secret:
    post:
      tags: [Webhooks]
      operationId: rotateWebhookSecret
      summary: Rotate a webhook's signing secret
      description: |
        Issues a new signing secret. For 24 hours both secrets are valid and every delivery is signed
        with both, so you can switch without dropping events: deploy a server that accepts either
        secret, confirm deliveries verify with the new one, then remove the old one.

        Required scope: `webhooks:manage`.
      security:
        - bearerAuth: []
        - oauth2: [webhooks:manage]
      parameters:
        - $ref: '#/components/parameters/WebhookId'
      responses:
        '200':
          description: The new secret and the end of the overlap period.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebhookSecretRotation'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'

  /webhooks/{id}/deliveries:
    get:
      tags: [Webhooks]
      operationId: listWebhookDeliveries
      summary: List webhook deliveries
      description: |
        Lists delivery attempts with request and response details. History is kept for 30 days.

        Required scope: `webhooks:manage`.
      security:
        - bearerAuth: []
        - oauth2: [webhooks:manage]
      parameters:
        - $ref: '#/components/parameters/WebhookId'
        - name: status
          in: query
          description: Filter by delivery status.
          schema:
            type: string
            enum: [succeeded, failed, pending]
        - name: eventType
          in: query
          description: Filter by event type.
          schema:
            $ref: '#/components/schemas/WebhookEventType'
        - name: since
          in: query
          description: Earliest attempt time. Defaults to 30 days ago.
          schema:
            type: string
            format: date-time
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: A page of deliveries.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebhookDeliveryList'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'

  /webhooks/{id}/deliveries/{eventId}/redeliver:
    post:
      tags: [Webhooks]
      operationId: redeliverWebhookEvent
      summary: Redeliver an event
      description: |
        Sends a previous event again to the webhook's current URL. The redelivered request keeps the
        same event `id`, so an idempotent handler ignores it if already processed. It is signed with
        the secret(s) valid now, with a fresh timestamp. Events older than 30 days cannot be
        redelivered. Limit: 60 redeliveries per minute.

        Required scope: `webhooks:manage`.
      security:
        - bearerAuth: []
        - oauth2: [webhooks:manage]
      parameters:
        - $ref: '#/components/parameters/WebhookId'
        - name: eventId
          in: path
          required: true
          description: The event ID (`evt_...`).
          schema:
            type: string
      responses:
        '202':
          description: Redelivery scheduled.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RedeliveryAccepted'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/TooManyRequests'

  # =========================================================================
  # USAGE
  # =========================================================================
  /usage:
    get:
      tags: [Usage]
      operationId: getUsage
      summary: Get usage metrics
      description: |
        Returns request, error and quota usage for your project over a period. Figures update about
        once a minute. Use it to feed your own dashboards and alerts.

        Required scope: `admin`.
      security:
        - bearerAuth: []
        - oauth2: [admin]
      parameters:
        - name: from
          in: query
          description: Start of the period (inclusive). Defaults to 24 hours ago.
          schema:
            type: string
            format: date-time
        - name: to
          in: query
          description: End of the period (exclusive). Defaults to now.
          schema:
            type: string
            format: date-time
        - name: granularity
          in: query
          description: Bucket size. `minute` allows at most 6 hours, `hour` 31 days, `day` 366 days.
          schema:
            type: string
            enum: [minute, hour, day]
            default: hour
        - name: groupBy
          in: query
          description: Break each bucket down by API key, endpoint or status.
          schema:
            type: string
            enum: [key, endpoint, status]
        - name: keyId
          in: query
          description: Restrict to one API key (its ID, not its secret).
          schema:
            type: string
      responses:
        '200':
          description: Usage for the period.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Usage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'

components:
  # =========================================================================
  # SECURITY SCHEMES
  # =========================================================================
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: |
        An API key (`cfk_test_...` for Ember, `cfk_live_...` for Mainnet) or an OAuth access token,
        sent as `Authorization: Bearer <token>`. API keys carry a permission level (`read`, `write` or
        `admin`) chosen when the key is created. Use keys only from servers you control.
    oauth2:
      type: oauth2
      description: OAuth 2.0 client credentials flow for short-lived, narrowly scoped access tokens.
      flows:
        clientCredentials:
          tokenUrl: https://auth.chainforge.example/oauth/token
          scopes:
            accounts:read: Read accounts, balances, nonces, account transactions and NFTs.
            transactions:read: Read transactions and gas estimates.
            transactions:write: Prepare and submit transactions, speed up and cancel, register accounts.
            contracts:read: Read contracts and tokens, make read-only calls, simulate, query events.
            contracts:write: Deploy and register contracts, create tokens.
            webhooks:manage: Create, read, update and delete webhooks; redeliver events.
            admin: Read usage and manage project-level settings.

  # =========================================================================
  # PARAMETERS
  # =========================================================================
  parameters:
    AddressPath:
      name: address
      in: path
      required: true
      description: A 42-character hexadecimal address starting with `0x`.
      schema:
        $ref: '#/components/schemas/Address'
      example: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
    TransactionId:
      name: id
      in: path
      required: true
      description: A platform transaction ID (`txn_...`) or a transaction hash (`0x...`).
      schema:
        type: string
      example: txn_01JC7X3M9Q
    WebhookId:
      name: id
      in: path
      required: true
      description: The webhook ID (`wh_...`).
      schema:
        type: string
      example: wh_01JC9K4TQZ
    Block:
      name: block
      in: query
      description: |
        Which chain state to read: `latest` (default), `finalized` (never reversed), or a block
        number. Historical blocks older than 128 blocks need an archive-enabled plan.
      schema:
        $ref: '#/components/schemas/BlockSelector'
    Limit:
      name: limit
      in: query
      description: Number of items per page, from 1 to 100.
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 25
    Cursor:
      name: cursor
      in: query
      description: |
        Opaque cursor from the previous response's `nextCursor`. Valid for 24 hours and only with the
        same filters that produced it. Omit for the first page.
      schema:
        type: string
    IdempotencyKeyRequired:
      name: Idempotency-Key
      in: header
      required: true
      description: |
        A unique string (a UUID is recommended) identifying this logical operation. Retrying with the
        same key and body replays the original response; a different body returns `409`. Retained 24 hours.
      schema:
        type: string
        minLength: 8
        maxLength: 64
      example: 6f1d2c9a-3b7e-4d55-9a21-0e8c4b7a1f90
    IdempotencyKeyOptional:
      name: Idempotency-Key
      in: header
      required: false
      description: Recommended. A unique string (8 to 64 characters) that makes retries safe.
      schema:
        type: string
        minLength: 8
        maxLength: 64

  # =========================================================================
  # HEADERS
  # =========================================================================
  headers:
    Retry-After:
      description: Seconds to wait before retrying.
      schema:
        type: integer
        example: 2
    X-RateLimit-Limit:
      description: Requests per second allowed on your plan.
      schema:
        type: integer
        example: 10
    X-RateLimit-Remaining:
      description: Requests remaining in the current window.
      schema:
        type: integer
        example: 0
    X-RateLimit-Reset:
      description: Seconds until the window resets.
      schema:
        type: integer
        example: 1

  # =========================================================================
  # REUSABLE RESPONSES
  # =========================================================================
  responses:
    BadRequest:
      description: The request is malformed or a value has the wrong format (for example `validation_failed`, `invalid_address`, `invalid_amount`, `invalid_cursor`).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: validation_failed
              message: 2 fields failed validation.
              details:
                fields:
                  - field: to
                    issue: Not a valid address.
                  - field: value
                    issue: Must be a non-negative integer string.
              requestId: req_9ZQ2X4D
    Unauthorized:
      description: Credentials are missing, invalid or expired (`missing_credentials`, `invalid_api_key`, `token_expired`).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: invalid_api_key
              message: The API key is invalid or has been revoked.
              requestId: req_4HK8M2P
    Forbidden:
      description: The credential is valid but lacks the required scope or comes from a disallowed IP (`insufficient_scope`, `ip_not_allowed`).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: insufficient_scope
              message: This operation requires the 'transactions:write' scope.
              details:
                required: transactions:write
              requestId: req_6TQ1N8C
    NotFound:
      description: The resource does not exist or belongs to another project. For something created moments ago, retry for a few seconds.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: transaction_not_found
              message: No transaction matches this ID or hash.
              requestId: req_2WD5R7L
    Conflict:
      description: The request conflicts with current state (`already_known`, `idempotency_conflict`, `idempotency_in_progress`, `transaction_not_pending`, `rotation_in_progress`, `webhook_disabled`).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: idempotency_conflict
              message: This Idempotency-Key was already used with a different request body.
              requestId: req_8MV3B6X
    UnprocessableEntity:
      description: The request is well-formed but cannot be carried out, often because the call would revert (for example `execution_reverted`, `insufficient_funds`, `nonce_too_low`, `fee_too_low`, `wrong_network`).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: insufficient_funds
              message: The sender balance is too low to cover value plus maximum fee.
              details:
                required: '5063000000000000000'
                available: '4200000000000000000'
              requestId: req_5GT7M1K
    TooManyRequests:
      description: Rate limit exceeded. Wait `Retry-After` seconds, then retry with exponential backoff and jitter.
      headers:
        Retry-After:
          $ref: '#/components/headers/Retry-After'
        X-RateLimit-Limit:
          $ref: '#/components/headers/X-RateLimit-Limit'
        X-RateLimit-Remaining:
          $ref: '#/components/headers/X-RateLimit-Remaining'
        X-RateLimit-Reset:
          $ref: '#/components/headers/X-RateLimit-Reset'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: rate_limited
              message: Rate limit of 10 requests per second exceeded.
              requestId: req_7H2K9PQ
    ServiceUnavailable:
      description: Temporary overload or maintenance. Retry after `Retry-After`, if present.
      headers:
        Retry-After:
          $ref: '#/components/headers/Retry-After'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: service_unavailable
              message: The service is temporarily unavailable.
              requestId: req_1ZX9C4V

  # =========================================================================
  # SCHEMAS
  # =========================================================================
  schemas:
    # ---- Primitive types ----
    Address:
      type: string
      description: A 42-character hexadecimal address starting with `0x`. Accepted in any case; mixed case is checksum-validated. Responses use checksum casing.
      pattern: '^0x[0-9a-fA-F]{40}$'
      example: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
    Hash:
      type: string
      description: A 66-character hexadecimal hash starting with `0x`.
      pattern: '^0x[0-9a-fA-F]{64}$'
      example: '0x9f3c5d8a1b7e44c2a09d3f6b8e1c2d4a5b6c7d8e9f00112233445566778899aa'
    Hex:
      type: string
      description: Hexadecimal bytes starting with `0x`.
      pattern: '^0x([0-9a-fA-F]{2})*$'
      example: '0x'
    Uint256:
      type: string
      description: |
        A non-negative integer as a decimal string (up to 78 digits). Sent as a string to avoid
        precision loss. Amounts are in the smallest unit: 1 FORGE = 10^18 sparks.
      pattern: '^(0|[1-9][0-9]{0,77})$'
      example: '5000000000000000000'
    BlockSelector:
      type: string
      description: '`latest`, `finalized`, `pending` (nonce queries only), or a block number such as `4820141`.'
      default: latest
      example: finalized
    FeeSpeed:
      type: string
      description: Fee tier. `slow` is cheapest (about 12 s), `normal` is the default (about 4 s), `fast` is quickest (about 2 s).
      enum: [slow, normal, fast]
      default: normal
    TransactionStatus:
      type: string
      description: |
        Lifecycle state of a transaction.
        - `pending`: in the mempool
        - `included`: in a block that is not yet final
        - `finalized`: in a final block and succeeded (terminal)
        - `failed`: executed and reverted; the fee is still paid (terminal)
        - `dropped`: left the mempool without inclusion; no fee (terminal)
        - `replaced`: superseded by another transaction with the same nonce (terminal)
      enum: [pending, included, finalized, failed, dropped, replaced]
    Metadata:
      type: object
      description: Free-form string key-value pairs linking a record to your own data. Do not store secrets or personal data.
      additionalProperties:
        type: string
        maxLength: 256
      example:
        orderId: ord_8841

    # ---- OAuth ----
    OAuthTokenRequest:
      type: object
      required: [grant_type, client_id, client_secret]
      properties:
        grant_type:
          type: string
          enum: [client_credentials]
          description: Must be `client_credentials`.
        client_id:
          type: string
          description: Your OAuth client ID.
        client_secret:
          type: string
          format: password
          description: Your OAuth client secret.
        scope:
          type: string
          description: Space-separated scopes. If omitted, all scopes allowed for the client are granted.
    OAuthToken:
      type: object
      required: [access_token, token_type, expires_in]
      properties:
        access_token:
          type: string
          description: The bearer token (a signed JWT; treat it as opaque).
        token_type:
          type: string
          enum: [Bearer]
        expires_in:
          type: integer
          description: Lifetime in seconds (3600).
        scope:
          type: string
          description: The scopes granted, which may be fewer than requested.
    OAuthError:
      type: object
      required: [error]
      properties:
        error:
          type: string
          enum: [invalid_request, invalid_client, invalid_scope, unsupported_grant_type]
        error_description:
          type: string

    # ---- Status and blocks ----
    Status:
      type: object
      required: [environment, network, chainId, latestBlock, finalizedBlock, apiVersion, status, time]
      properties:
        environment:
          type: string
          enum: [test, live]
        network:
          type: string
          enum: [mainnet, ember, devnet]
        chainId:
          type: integer
          description: 7700 (Mainnet), 7701 (Ember) or 7702 (devnet).
        latestBlock:
          type: integer
          description: Most recent included block.
        finalizedBlock:
          type: integer
          description: Most recent finalized block.
        apiVersion:
          type: string
        status:
          type: string
          enum: [operational, degraded, maintenance]
        time:
          type: string
          format: date-time
          description: Server time in UTC. Compare with your clock to detect skew.
    Block:
      type: object
      required: [number, hash, parentHash, timestamp, proposer, transactionCount, transactions, gasUsed, gasLimit, baseFeePerGas, finalized]
      properties:
        number:
          type: integer
          description: Block height.
        hash:
          $ref: '#/components/schemas/Hash'
        parentHash:
          $ref: '#/components/schemas/Hash'
        timestamp:
          type: string
          format: date-time
        proposer:
          $ref: '#/components/schemas/Address'
        transactionCount:
          type: integer
        transactions:
          type: array
          description: Transaction hashes, or full objects when `includeTransactions=true`.
          items:
            oneOf:
              - $ref: '#/components/schemas/Hash'
              - $ref: '#/components/schemas/Transaction'
        gasUsed:
          $ref: '#/components/schemas/Uint256'
        gasLimit:
          $ref: '#/components/schemas/Uint256'
        baseFeePerGas:
          $ref: '#/components/schemas/Uint256'
        finalized:
          type: boolean
          description: Whether the block is final.

    # ---- Accounts ----
    RegisterAccountRequest:
      type: object
      required: [address]
      properties:
        address:
          $ref: '#/components/schemas/Address'
        label:
          type: string
          maxLength: 64
          description: Human-readable name.
        metadata:
          $ref: '#/components/schemas/Metadata'
    RegisteredAccount:
      type: object
      required: [address, type, createdAt, updatedAt]
      properties:
        address:
          $ref: '#/components/schemas/Address'
        label:
          type: string
        type:
          type: string
          enum: [eoa, contract]
        metadata:
          $ref: '#/components/schemas/Metadata'
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    Account:
      type: object
      required: [address, type, balance, nonce, registered, blockNumber]
      properties:
        address:
          $ref: '#/components/schemas/Address'
        type:
          type: string
          enum: [eoa, contract]
          description: '`eoa` is controlled by a private key; `contract` is controlled by code.'
        balance:
          $ref: '#/components/schemas/Uint256'
        nonce:
          type: integer
          description: Transactions sent (EOA) or contracts created (contract).
        registered:
          type: boolean
          description: Whether the address is registered with your project.
        label:
          type: string
          description: Present only for registered accounts.
        metadata:
          $ref: '#/components/schemas/Metadata'
        codeHash:
          $ref: '#/components/schemas/Hash'
        codeSize:
          type: integer
          description: Contracts only, in bytes.
        blockNumber:
          type: integer
          description: Block at which state was read.
    Balance:
      type: object
      required: [address, balance, balanceFormatted, symbol, blockNumber, nonce]
      properties:
        address:
          $ref: '#/components/schemas/Address'
        balance:
          $ref: '#/components/schemas/Uint256'
        balanceFormatted:
          type: string
          description: Decimal FORGE for display only. Never use it for arithmetic.
          example: '94.999937'
        symbol:
          type: string
          enum: [FORGE, tFORGE, dFORGE]
        blockNumber:
          type: integer
        nonce:
          type: integer
    BalanceBatch:
      type: object
      required: [blockNumber, data]
      properties:
        blockNumber:
          type: integer
          description: The single block all balances were read at.
        data:
          type: array
          items:
            type: object
            required: [address, balance]
            properties:
              address:
                $ref: '#/components/schemas/Address'
              balance:
                $ref: '#/components/schemas/Uint256'
    Nonce:
      type: object
      required: [address, nonce, block]
      properties:
        address:
          $ref: '#/components/schemas/Address'
        nonce:
          type: integer
        block:
          type: string
          description: The selector used.
          example: pending

    # ---- Transactions and gas ----
    PrepareTransactionRequest:
      type: object
      required: [from]
      properties:
        from:
          $ref: '#/components/schemas/Address'
        to:
          $ref: '#/components/schemas/Address'
        value:
          allOf:
            - $ref: '#/components/schemas/Uint256'
          default: '0'
        data:
          allOf:
            - $ref: '#/components/schemas/Hex'
          description: Encoded contract call or creation code. Default `0x`.
        nonce:
          type: integer
          minimum: 0
          description: Override the nonce. Default is the sender's `pending` nonce.
        gasLimit:
          $ref: '#/components/schemas/Uint256'
        feeSpeed:
          $ref: '#/components/schemas/FeeSpeed'
        maxFeePerGas:
          $ref: '#/components/schemas/Uint256'
        maxPriorityFeePerGas:
          $ref: '#/components/schemas/Uint256'
    PreparedTransaction:
      type: object
      required: [chainId, type, nonce, from, to, value, data, gasLimit, maxFeePerGas, maxPriorityFeePerGas, estimatedFee, maxFee, unsignedTransaction, signingHash, expiresAt]
      properties:
        chainId:
          type: integer
          description: Network the transaction is valid on.
        type:
          type: integer
          description: Transaction format (2 = fee-market transaction).
        nonce:
          type: integer
        from:
          $ref: '#/components/schemas/Address'
        to:
          type: string
          nullable: true
          description: Recipient or contract. `null` for a deployment.
        value:
          $ref: '#/components/schemas/Uint256'
        data:
          $ref: '#/components/schemas/Hex'
        gasLimit:
          $ref: '#/components/schemas/Uint256'
        maxFeePerGas:
          $ref: '#/components/schemas/Uint256'
        maxPriorityFeePerGas:
          $ref: '#/components/schemas/Uint256'
        estimatedFee:
          $ref: '#/components/schemas/Uint256'
        maxFee:
          $ref: '#/components/schemas/Uint256'
        unsignedTransaction:
          $ref: '#/components/schemas/Hex'
        signingHash:
          $ref: '#/components/schemas/Hash'
        expiresAt:
          type: string
          format: date-time
          description: After this time the fee suggestions are stale; prepare again.
    SubmitTransactionRequest:
      type: object
      required: [signedTransaction]
      properties:
        signedTransaction:
          allOf:
            - $ref: '#/components/schemas/Hex'
          description: The signed, encoded transaction, up to 128 KB.
        metadata:
          allOf:
            - $ref: '#/components/schemas/Metadata'
          description: Up to 8 key-value pairs stored with the transaction record.
    Transaction:
      type: object
      required: [id, hash, status, from, value, nonce]
      properties:
        id:
          type: string
          description: Platform ID (`txn_...`).
        hash:
          $ref: '#/components/schemas/Hash'
        status:
          $ref: '#/components/schemas/TransactionStatus'
        from:
          $ref: '#/components/schemas/Address'
        to:
          $ref: '#/components/schemas/Address'
        value:
          $ref: '#/components/schemas/Uint256'
        data:
          $ref: '#/components/schemas/Hex'
        nonce:
          type: integer
        gasLimit:
          $ref: '#/components/schemas/Uint256'
        maxFeePerGas:
          $ref: '#/components/schemas/Uint256'
        maxPriorityFeePerGas:
          $ref: '#/components/schemas/Uint256'
        gasUsed:
          $ref: '#/components/schemas/Uint256'
        effectiveGasPrice:
          $ref: '#/components/schemas/Uint256'
        fee:
          allOf:
            - $ref: '#/components/schemas/Uint256'
          description: '`gasUsed x effectiveGasPrice`. Present once included.'
        blockNumber:
          type: integer
        blockHash:
          $ref: '#/components/schemas/Hash'
        contractAddress:
          allOf:
            - $ref: '#/components/schemas/Address'
          description: For finalized deployments.
        revertReason:
          type: string
          description: For `failed` transactions; decoded when the contract's ABI is registered.
        replacedBy:
          type: string
          description: 'For `replaced`: the ID of the replacement transaction.'
        events:
          type: array
          items:
            $ref: '#/components/schemas/EventLog'
        metadata:
          $ref: '#/components/schemas/Metadata'
        submittedAt:
          type: string
          format: date-time
        includedAt:
          type: string
          format: date-time
        finalizedAt:
          type: string
          format: date-time
    TransactionList:
      type: object
      required: [data, nextCursor]
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/Transaction'
        nextCursor:
          type: string
          nullable: true
          description: Pass as `cursor` for the next page. `null` when there are no more pages.
    FeeBumpRequest:
      type: object
      properties:
        feeSpeed:
          type: string
          enum: [normal, fast]
          default: fast
        maxFeePerGas:
          allOf:
            - $ref: '#/components/schemas/Uint256'
          description: Must be at least 110 percent of the original.
        maxPriorityFeePerGas:
          allOf:
            - $ref: '#/components/schemas/Uint256'
          description: Must be at least 110 percent of the original.
    CancelRequest:
      type: object
      properties:
        feeSpeed:
          type: string
          enum: [normal, fast]
          default: fast
    GasEstimateRequest:
      type: object
      required: [from]
      properties:
        from:
          $ref: '#/components/schemas/Address'
        to:
          $ref: '#/components/schemas/Address'
        value:
          $ref: '#/components/schemas/Uint256'
        data:
          $ref: '#/components/schemas/Hex'
        block:
          $ref: '#/components/schemas/BlockSelector'
    FeeSuggestion:
      type: object
      required: [maxFeePerGas, maxPriorityFeePerGas, estimatedWaitSeconds]
      properties:
        maxFeePerGas:
          $ref: '#/components/schemas/Uint256'
        maxPriorityFeePerGas:
          $ref: '#/components/schemas/Uint256'
        estimatedWaitSeconds:
          type: integer
    GasEstimate:
      type: object
      required: [gasLimit, baseFee, suggested, blockNumber]
      properties:
        gasLimit:
          $ref: '#/components/schemas/Uint256'
        baseFee:
          $ref: '#/components/schemas/Uint256'
        suggested:
          type: object
          required: [slow, normal, fast]
          properties:
            slow:
              $ref: '#/components/schemas/FeeSuggestion'
            normal:
              $ref: '#/components/schemas/FeeSuggestion'
            fast:
              $ref: '#/components/schemas/FeeSuggestion'
        blockNumber:
          type: integer

    # ---- Contracts ----
    AbiItem:
      type: object
      description: One entry of a contract ABI (a function, event, error or constructor).
      required: [type]
      properties:
        type:
          type: string
          enum: [function, event, error, constructor, fallback, receive]
        name:
          type: string
        stateMutability:
          type: string
          enum: [pure, view, nonpayable, payable]
        inputs:
          type: array
          items:
            type: object
            properties:
              name:
                type: string
              type:
                type: string
              indexed:
                type: boolean
        outputs:
          type: array
          items:
            type: object
            properties:
              name:
                type: string
              type:
                type: string
      additionalProperties: true
    Abi:
      type: array
      description: The contract ABI, as produced by the Solidity compiler.
      items:
        $ref: '#/components/schemas/AbiItem'
    DeployContractRequest:
      type: object
      required: [from, bytecode, abi]
      properties:
        from:
          allOf:
            - $ref: '#/components/schemas/Address'
          description: The deployer.
        bytecode:
          allOf:
            - $ref: '#/components/schemas/Hex'
          description: Compiled creation bytecode, up to 256 KB.
        abi:
          $ref: '#/components/schemas/Abi'
        constructorArgs:
          type: array
          items: {}
          description: Constructor arguments, in order.
          default: []
        value:
          $ref: '#/components/schemas/Uint256'
        name:
          type: string
          maxLength: 64
        registerOnDeploy:
          type: boolean
          default: true
        feeSpeed:
          $ref: '#/components/schemas/FeeSpeed'
    DeploymentPreparation:
      type: object
      required: [deploymentId, predictedAddress, transaction]
      properties:
        deploymentId:
          type: string
          description: Platform ID (`dpl_...`) for tracking the deployment.
        predictedAddress:
          allOf:
            - $ref: '#/components/schemas/Address'
          description: The address the contract will have, valid only if you submit with this exact nonce.
        transaction:
          $ref: '#/components/schemas/PreparedTransaction'
    RegisterContractRequest:
      type: object
      required: [abi]
      properties:
        name:
          type: string
          maxLength: 64
        abi:
          $ref: '#/components/schemas/Abi'
        startBlock:
          type: integer
          description: Block to begin indexing events from. Default is the deployment block, if known.
    Contract:
      type: object
      required: [address, abiVersion, verified, indexing]
      properties:
        address:
          $ref: '#/components/schemas/Address'
        name:
          type: string
        abiVersion:
          type: integer
          description: Increments each time the ABI is replaced.
        deployedAt:
          type: string
          format: date-time
        deploymentTransaction:
          type: string
        verified:
          type: boolean
          description: Whether verified source code matches the deployed bytecode.
        indexing:
          type: object
          properties:
            status:
              type: string
              enum: [catching_up, synced]
            startBlock:
              type: integer
            lastIndexedBlock:
              type: integer
        abi:
          $ref: '#/components/schemas/Abi'
    ContractCallRequest:
      type: object
      required: [function]
      properties:
        function:
          type: string
          description: Function name, or the full signature for overloaded functions.
        args:
          type: array
          items: {}
          description: Arguments in order. Large integers must be strings.
        from:
          $ref: '#/components/schemas/Address'
        block:
          $ref: '#/components/schemas/BlockSelector'
    ContractCallResult:
      type: object
      required: [function, result, blockNumber]
      properties:
        function:
          type: string
        result:
          description: 'Decoded return value: a scalar, an array (several outputs) or an object (struct). Large integers are strings.'
        blockNumber:
          type: integer
    SimulateRequest:
      type: object
      required: [function, from]
      properties:
        function:
          type: string
        args:
          type: array
          items: {}
        from:
          allOf:
            - $ref: '#/components/schemas/Address'
          description: The simulated caller.
        value:
          $ref: '#/components/schemas/Uint256'
        block:
          $ref: '#/components/schemas/BlockSelector'
    SimulationResult:
      type: object
      required: [success, gasUsed, blockNumber]
      properties:
        success:
          type: boolean
          description: Whether the call would succeed.
        gasUsed:
          $ref: '#/components/schemas/Uint256'
        result:
          description: Return value, if successful.
        events:
          type: array
          description: Decoded events the call would emit.
          items:
            type: object
            properties:
              name:
                type: string
              args:
                type: object
                additionalProperties: true
        revertReason:
          type: string
          description: Why the call would revert, if unsuccessful.
        blockNumber:
          type: integer
    EventLog:
      type: object
      required: [address, blockNumber, blockHash, transactionHash, logIndex, finalized]
      properties:
        address:
          allOf:
            - $ref: '#/components/schemas/Address'
          description: The emitting contract.
        event:
          type: string
          description: Event name. Absent if the log cannot be decoded.
        args:
          type: object
          additionalProperties: true
          description: Decoded arguments.
        topics:
          type: array
          items:
            $ref: '#/components/schemas/Hash'
          description: Raw topics, present when the event is not decoded.
        data:
          $ref: '#/components/schemas/Hex'
        blockNumber:
          type: integer
        blockHash:
          $ref: '#/components/schemas/Hash'
        transactionHash:
          $ref: '#/components/schemas/Hash'
        logIndex:
          type: integer
          description: Position within the block. (`transactionHash`, `logIndex`) is globally unique.
        timestamp:
          type: string
          format: date-time
        finalized:
          type: boolean
        removed:
          type: boolean
          description: '`true` if retracted (WebSocket `included` subscriptions only).'
    EventLogList:
      type: object
      required: [data, nextCursor]
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/EventLog'
        nextCursor:
          type: string
          nullable: true

    # ---- Tokens ----
    CreateTokenRequest:
      type: object
      required: [type, name, symbol, owner]
      properties:
        type:
          type: string
          enum: [cft20, cft721]
          description: '`cft20` is fungible; `cft721` is non-fungible.'
        name:
          type: string
          minLength: 1
          maxLength: 64
        symbol:
          type: string
          minLength: 1
          maxLength: 11
        owner:
          allOf:
            - $ref: '#/components/schemas/Address'
          description: Account that will own and administer the token and sign the deployment.
        decimals:
          type: integer
          minimum: 0
          maximum: 18
          default: 18
          description: CFT-20 only.
        initialSupply:
          allOf:
            - $ref: '#/components/schemas/Uint256'
          description: CFT-20 only. Units minted to `owner`, in the smallest unit.
        maxSupply:
          allOf:
            - $ref: '#/components/schemas/Uint256'
          description: Hard cap that cannot be raised later. For CFT-721 it is a count of tokens.
        baseUri:
          type: string
          description: CFT-721 only. Prefix for token metadata URIs, such as `ipfs://bafy.../`.
        features:
          $ref: '#/components/schemas/TokenFeatures'
    TokenFeatures:
      type: object
      description: Permanent once deployed.
      properties:
        mintable:
          type: boolean
          default: false
          description: The owner can create new units.
        burnable:
          type: boolean
          default: false
          description: Holders can destroy their own units.
        pausable:
          type: boolean
          default: false
          description: The owner can freeze transfers.
        allowList:
          type: boolean
          default: false
          description: Restrict holders to an allow-list.
    Token:
      type: object
      required: [address, type, name, symbol, totalSupply, blockNumber]
      properties:
        address:
          $ref: '#/components/schemas/Address'
        type:
          type: string
          enum: [cft20, cft721]
        name:
          type: string
        symbol:
          type: string
        decimals:
          type: integer
          description: CFT-20 only.
        totalSupply:
          $ref: '#/components/schemas/Uint256'
        maxSupply:
          $ref: '#/components/schemas/Uint256'
        owner:
          $ref: '#/components/schemas/Address'
        features:
          $ref: '#/components/schemas/TokenFeatures'
        paused:
          type: boolean
        baseUri:
          type: string
        blockNumber:
          type: integer
    TokenBalance:
      type: object
      required: [token, holder, balance, blockNumber]
      properties:
        token:
          $ref: '#/components/schemas/Address'
        holder:
          $ref: '#/components/schemas/Address'
        balance:
          $ref: '#/components/schemas/Uint256'
        balanceFormatted:
          type: string
          description: Display value using the token's `decimals`. Not for arithmetic.
        symbol:
          type: string
        decimals:
          type: integer
        blockNumber:
          type: integer
    NftItem:
      type: object
      required: [collection, tokenId, tokenUri, metadataStatus]
      properties:
        collection:
          $ref: '#/components/schemas/Address'
        tokenId:
          type: string
        tokenUri:
          type: string
          description: Metadata location as stored on-chain.
        name:
          type: string
        description:
          type: string
        image:
          type: string
        attributes:
          type: array
          items:
            type: object
            properties:
              trait_type:
                type: string
              value: {}
        metadataStatus:
          type: string
          description: '`ok`, `pending` (not fetched yet), `unreachable` (host did not respond) or `invalid` (not valid JSON or too large).'
          enum: [ok, pending, unreachable, invalid]
    NftList:
      type: object
      required: [data, nextCursor]
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/NftItem'
        nextCursor:
          type: string
          nullable: true

    # ---- Webhooks ----
    WebhookEventType:
      type: string
      description: Type of event a webhook can receive.
      enum:
        - webhook.ping
        - transaction.pending
        - transaction.included
        - transaction.finalized
        - transaction.failed
        - transaction.dropped
        - account.received
        - token.transfer
        - contract.event
        - contract.deployed
    WebhookFilters:
      type: object
      description: Narrow which events are delivered. A filter that does not apply to an event type is ignored for it.
      properties:
        addresses:
          type: array
          items:
            $ref: '#/components/schemas/Address'
          description: Only events involving these addresses.
        contracts:
          type: array
          items:
            $ref: '#/components/schemas/Address'
          description: For `contract.event`, only these contracts.
        tokens:
          type: array
          items:
            $ref: '#/components/schemas/Address'
          description: For `token.transfer`, only these tokens.
        eventNames:
          type: array
          items:
            type: string
          description: For `contract.event`, only these event names.
        finality:
          type: string
          enum: [finalized, included]
          default: finalized
    CreateWebhookRequest:
      type: object
      required: [url, events]
      properties:
        url:
          type: string
          format: uri
          maxLength: 2048
          description: Public HTTPS URL.
        description:
          type: string
          maxLength: 256
        events:
          type: array
          minItems: 1
          items:
            type: string
          description: Event types to receive, or `["*"]` for all.
        filters:
          $ref: '#/components/schemas/WebhookFilters'
        enabled:
          type: boolean
          default: true
        headers:
          type: object
          maxProperties: 5
          additionalProperties:
            type: string
          description: Custom headers added to every delivery. Names beginning with `X-ChainForge-` are reserved.
    UpdateWebhookRequest:
      type: object
      description: Any subset of the creation fields.
      properties:
        url:
          type: string
          format: uri
          maxLength: 2048
        description:
          type: string
          maxLength: 256
        events:
          type: array
          items:
            type: string
        filters:
          $ref: '#/components/schemas/WebhookFilters'
        headers:
          type: object
          additionalProperties:
            type: string
        enabled:
          type: boolean
    Webhook:
      type: object
      required: [id, url, events, enabled, createdAt, updatedAt]
      properties:
        id:
          type: string
          example: wh_01JC9K4TQZ
        url:
          type: string
          format: uri
        description:
          type: string
        events:
          type: array
          items:
            type: string
        filters:
          $ref: '#/components/schemas/WebhookFilters'
        enabled:
          type: boolean
        health:
          type: object
          properties:
            status:
              type: string
              enum: [healthy, degraded, disabled]
            lastSuccessAt:
              type: string
              format: date-time
            lastFailureAt:
              type: string
              format: date-time
            consecutiveFailures:
              type: integer
        disabledReason:
          type: string
          description: Present when the platform disabled the webhook, for example `repeated_failures`.
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    WebhookWithSecret:
      allOf:
        - $ref: '#/components/schemas/Webhook'
        - type: object
          required: [secret]
          properties:
            secret:
              type: string
              description: Signing secret, shown only in this response. Store it immediately in a secrets manager.
              example: whsec_8f3b1c7d9e2a4b6c5d7e8f9a0b1c2d3e
    WebhookSecretRotation:
      type: object
      required: [id, secret, previousSecretExpiresAt]
      properties:
        id:
          type: string
        secret:
          type: string
          description: The new signing secret, shown only in this response.
        previousSecretExpiresAt:
          type: string
          format: date-time
          description: When the old secret stops being used (24 hours after rotation).
    WebhookList:
      type: object
      required: [data, nextCursor]
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/Webhook'
        nextCursor:
          type: string
          nullable: true
    WebhookEvent:
      type: object
      description: The envelope of every webhook delivery.
      required: [id, type, apiVersion, createdAt, network, data]
      properties:
        id:
          type: string
          description: Unique event ID (`evt_...`), constant across retries and redeliveries. Use it to de-duplicate.
        type:
          $ref: '#/components/schemas/WebhookEventType'
        apiVersion:
          type: string
        createdAt:
          type: string
          format: date-time
        network:
          type: string
          enum: [mainnet, ember, devnet]
        data:
          type: object
          additionalProperties: true
          description: |
            Event-specific payload: a Transaction for `transaction.*`; `{address, from, value,
            transactionHash, blockNumber, finalized}` for `account.received`; `{token, from, to, value
            or tokenId, transactionHash, logIndex, blockNumber, finalized}` for `token.transfer`; an
            EventLog for `contract.event`; `{deploymentId, contractAddress, deployer, transactionHash,
            blockNumber}` for `contract.deployed`.
    WebhookDeliveryAttempt:
      type: object
      properties:
        attempt:
          type: integer
        sentAt:
          type: string
          format: date-time
        responseStatus:
          type: integer
          nullable: true
          description: HTTP status your server returned, or `null` if none.
        durationMs:
          type: integer
        error:
          type: string
          nullable: true
          enum: [timeout, connection_refused, tls_error, dns_error]
    WebhookDelivery:
      type: object
      required: [eventId, eventType, status, attempts]
      properties:
        eventId:
          type: string
        eventType:
          $ref: '#/components/schemas/WebhookEventType'
        status:
          type: string
          enum: [succeeded, failed, pending]
        attempts:
          type: array
          items:
            $ref: '#/components/schemas/WebhookDeliveryAttempt'
        nextAttemptAt:
          type: string
          format: date-time
          nullable: true
    WebhookDeliveryList:
      type: object
      required: [data, nextCursor]
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/WebhookDelivery'
        nextCursor:
          type: string
          nullable: true
    RedeliveryAccepted:
      type: object
      properties:
        eventId:
          type: string
        status:
          type: string
          example: pending
        nextAttemptAt:
          type: string
          format: date-time

    # ---- Usage ----
    Usage:
      type: object
      required: [from, to, granularity, plan, limits, totals, series, quota]
      properties:
        from:
          type: string
          format: date-time
        to:
          type: string
          format: date-time
        granularity:
          type: string
          enum: [minute, hour, day]
        plan:
          type: string
          enum: [free, growth, enterprise]
        limits:
          type: object
          properties:
            requestsPerSecond:
              type: integer
            requestsPerDay:
              type: integer
            webSocketSubscriptions:
              type: integer
        totals:
          type: object
          properties:
            requests:
              type: integer
            errors:
              type: integer
              description: Responses with status 400 or above.
            rateLimited:
              type: integer
              description: Requests answered `429`.
            errorRate:
              type: number
              format: double
              minimum: 0
              maximum: 1
        series:
          type: array
          items:
            type: object
            properties:
              start:
                type: string
                format: date-time
              requests:
                type: integer
              errors:
                type: integer
              rateLimited:
                type: integer
              p95LatencyMs:
                type: integer
              group:
                type: string
                description: Present when `groupBy` is used (for example an endpoint such as `POST /transactions`).
        quota:
          type: object
          properties:
            dailyUsed:
              type: integer
            dailyRemaining:
              type: integer
            resetsAt:
              type: string
              format: date-time

    # ---- Errors ----
    ErrorCode:
      type: string
      description: |
        Stable machine-readable error code. Branch on this, never on `message`. New codes may be added
        within a version, so handle unknown values gracefully.
      enum:
        - missing_credentials
        - invalid_api_key
        - token_expired
        - insufficient_scope
        - ip_not_allowed
        - validation_failed
        - invalid_address
        - invalid_amount
        - invalid_block
        - invalid_block_id
        - invalid_block_range
        - block_range_too_large
        - invalid_cursor
        - invalid_status
        - invalid_event_type
        - invalid_time_range
        - too_many_addresses
        - invalid_signed_transaction
        - invalid_bytecode
        - invalid_abi
        - missing_idempotency_key
        - transaction_not_found
        - block_not_found
        - contract_not_found
        - contract_not_registered
        - token_not_found
        - webhook_not_found
        - delivery_not_found
        - already_known
        - idempotency_conflict
        - idempotency_in_progress
        - transaction_not_pending
        - rotation_in_progress
        - webhook_disabled
        - wrong_network
        - nonce_too_low
        - nonce_gap
        - insufficient_funds
        - fee_too_low
        - fee_bump_too_low
        - gas_limit_too_low
        - execution_reverted
        - state_unavailable
        - bytecode_too_large
        - constructor_args_mismatch
        - unknown_function
        - function_not_readonly
        - invalid_arguments
        - unknown_event
        - unknown_argument
        - not_a_token
        - invalid_decimals
        - initial_supply_exceeds_cap
        - feature_unsupported
        - metadata_too_large
        - account_limit_reached
        - webhook_unreachable
        - insecure_url
        - webhook_limit_reached
        - rate_limited
        - redelivery_rate_limited
        - internal_error
        - bad_gateway
        - service_unavailable
        - gateway_timeout
    Error:
      type: object
      required: [error]
      properties:
        error:
          type: object
          required: [code, message, requestId]
          properties:
            code:
              $ref: '#/components/schemas/ErrorCode'
            message:
              type: string
              description: Human-readable explanation. Wording may change; do not match on it.
            details:
              type: object
              additionalProperties: true
              description: |
                Structured data whose keys depend on `code`. For example `validation_failed` has
                `fields`, `insufficient_funds` has `required` and `available`, `execution_reverted`
                has `revertReason`, and `already_known` has `transaction`.
            requestId:
              type: string
              description: The request's unique ID. Include it when contacting support.
              example: req_5GT7M1K
            docUrl:
              type: string
              format: uri
              description: Link to the error's entry in the API Reference Guide.
