> ## Documentation Index
> Fetch the complete documentation index at: https://docs.darknyx.trade/llms.txt
> Use this file to discover all available pages before exploring further.

> Submit a hidden, fully-collateralized order, covering the request body, the cryptographic fields the SDK builds for you, and the response lifecycle.

# Place Order

<Info>
  **TL;DR**

  `POST /orders` submits a new order. The body carries the usual economic fields
  (symbol, side, type, amount, price) **plus** the cryptographic backing that makes
  the order private and self-custodial: the collateral-note commitment, a zero-knowledge
  input proof, a note opening, a signed contributory viewing key, the current boot
  session, and a trading-key signature over the canonical order intent. The
  opening is pinned indirectly through the signed note commitment. The **SDK builds and signs
  all of this** from your keys and a deposited note.
</Info>

Auth: `Authorization: Bearer <token>` **and** a trading-key signature in the body.

## How a Darknyx order differs

On a transparent venue, placing an order is just sending its economic fields. On
Darknyx an order is *fully collateralized by a specific note you already deposited*,
and it is *private*, so the request also carries:

* the **commitment** of the collateral note, and a secret **opening** of that
  note the in-enclave prover needs;
* a **zero-knowledge input proof** that the note exists in the on-chain tree and
  is yours to spend;
* a signed **X25519 viewing key** for private recovery data;
* the current 32-byte **boot session id**, so a signed order cannot be replayed
  into a restarted engine;
* an **Ed25519 signature** from your trading key over the canonical body, so the
  engine can attribute, and ultimately settle, the order to you without any
  per-order on-chain transaction;
* deterministic partial-fill continuation: the settlement circuit derives each
  change inner from the consumed input inner, so no pre-supplied pool is needed.

You do not assemble these by hand. The SDK takes your keys and a spendable note
and produces a ready-to-sign request. The full field reference is here so the
wire contract is unambiguous.

## Request body

### Economic fields

| Field           | Type    | Required    | Description                                                                                                                                                                                                |
| --------------- | ------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `symbol`        | string  | Yes         | Market id, e.g. `"SOL-USDC"`.                                                                                                                                                                              |
| `side`          | string  | Yes         | `"bid"` (buy base) or `"ask"` (sell base).                                                                                                                                                                 |
| `order_type`    | string  | Yes         | `"limit"`, `"ioc"`, or `"fok"`. See [Order Types](/documentation/trading-concepts/order-types).                                                                                                            |
| `amount`        | integer | Yes         | Order size in base units.                                                                                                                                                                                  |
| `price_limit`   | integer | Conditional | Worst acceptable price, in quote units per base. Required for a bid; an ask may use `0` to accept any clearing price.                                                                                      |
| `min_fill_size` | integer | No          | Reject fills smaller than this. Set equal to `amount` for all-or-none. Default `0` (any partial fill). See [Execution Attributes](/documentation/trading-concepts/execution-attributes).                   |
| `expiry_slot`   | integer | Yes         | Solana slot past which the order auto-expires. Bounded by the protocol's maximum order lifetime (currently 4,500 slots). See [Time in Force](/documentation/trading-concepts/time-in-force).               |
| `order_id`      | string  | Yes         | A client-chosen 16-byte id, hex. Must be unique and non-zero. The SDK can derive ids deterministically from your seed (`deriveOrderId`), so you can reconcile or recover your order set on a fresh device. |
| `arrival_nonce` | integer | Yes         | A strictly increasing u64 per trading key. Exact byte-identical idempotent retries are handled before this replay check.                                                                                   |

### Collateral, opening, and proof

| Field               | Type    | Required | Description                                                                                                                                                                                                                                                                          |
| ------------------- | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `note_commitment`   | string  | Yes      | 32-byte hex. The commitment of the collateral note backing this order. It is signed into the order and can back at most one live or settlement-pending order in this venue.                                                                                                          |
| `collateral_amount` | integer | No       | The value the collateral note actually carries, when it exceeds the order's nominal cost. Lets you point a large note at a small order and receive the surplus back as a change note. Omit for exact collateral.                                                                     |
| `owner_commitment`  | string  | Yes      | 32-byte hex. The collateral note's owner commitment, part of the secret opening the in-enclave prover re-derives the commitment from. This is the only note-bound owner identity an order carries, and the one settlement derives output notes back to. Held in enclave memory only. |
| `note_inner_hash`   | string  | Yes      | 32-byte hex. The note's amount-independent inner hash (an opening field that anchors both the commitment and unlinkable note-use tag).                                                                                                                                               |
| `merkle_root`       | string  | Yes      | 32-byte hex. The tree root the input proof was generated against. Checked against the venue's recent-root window **at intake** (`1010` if it has aged out) and against the on-chain root window again at settlement time.                                                            |
| `valid_input_proof` | string  | Yes      | 256-byte hex. The zero-knowledge proof that the collateral note is in the tree and spendable. **Verified at intake**, before the order is accepted — an invalid proof is refused with `1011` rather than booked. The on-chain program verifies it again at lock time.                |
| `tree_id`           | integer | No       | Merkle-tree shard containing the collateral note. Defaults to `0`. Intake rejects an out-of-range shard and checks the proof root against that shard's recent-root window, so a wrong shard is refused before booking.                                                               |

### Recovery and replay binding

| Field            | Type   | Required | Description                                                                                                                                                                                                                                                                                        |
| ---------------- | ------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `viewing_pubkey` | string | Yes      | 32-byte contributory X25519 public key derived by the SDK. It is signed in the canonical body. Low-order/non-contributory points are rejected before booking.                                                                                                                                      |
| `session_id`     | string | Yes      | 32-byte current `/info.boot_session_id`, signed in the canonical body. A CVM restart changes it and invalidates stale orders. Programmatic clients verify the same value in the transport-attestation manifest; a substituted value is rejected by intake rather than weakening replay protection. |

### Signature

| Field                   | Type   | Required | Description                                                                                                                                                                                                          |
| ----------------------- | ------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `trading_key`           | string | Yes      | 32-byte hex. The Ed25519 public key that owns this order.                                                                                                                                                            |
| `trading_key_signature` | string | Yes      | 64-byte hex. Ed25519 signature over the SHA-256 digest of the fixed canonical body. The current domain is `darknyx-order-v5`; it includes every economic field, `viewing_pubkey`, `session_id`, and `arrival_nonce`. |

## Example

```bash theme={null}
# In practice the SDK produces order.json from your keys + a spendable note.
curl -s -X POST "$GATEWAY/orders" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "symbol": "SOL-USDC",
    "side": "bid",
    "order_type": "limit",
    "amount": 10000000,
    "price_limit": 150000000,
    "min_fill_size": 0,
    "expiry_slot": 309490000,
    "order_id": "aa00000000000000000000000000000001",
    "note_commitment": "…",
    "arrival_nonce": 1,
    "trading_key": "…",
    "trading_key_signature": "…",
    "owner_commitment": "…",
    "note_inner_hash": "…",
    "merkle_root": "…",
    "valid_input_proof": "…",
    "viewing_pubkey": "…",
    "session_id": "…"
  }'
```

## Success response

```json theme={null}
{
  "order_id": "aa00000000000000000000000000000001",
  "status": "accepted",
  "arrival_slot": 309482113
}
```

Returned with `202 Accepted`.

| Field          | Type    | Description                                                            |
| -------------- | ------- | ---------------------------------------------------------------------- |
| `order_id`     | string  | The order's id (the one you supplied).                                 |
| `status`       | string  | `"accepted"` means the order passed verification and entered the book. |
| `arrival_slot` | integer | The slot the engine stamped on arrival; frozen for the order's life.   |

<Info>
  **Accepted is not filled**

  A `202` means the order passed signature and collateral verification and entered
  the book, **not** that it has filled. Track fills via
  [`GET /orders/{order_id}`](./get-order.mdx) or the
  [Orders Channel](../websocket/orders-channel.mdx).
</Info>

## Order status lifecycle

| Status                  | Description                                                                                                      |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `pending`               | Accepted and resting in the book.                                                                                |
| `pending_settlement`    | Reserved for a private match; no book quantity or fill is committed until Solana confirms it.                    |
| `partially_filled`      | Stream event emitted after a confirmed partial settlement; the derived continuation remains live.                |
| `fully_filled`          | Stream event emitted after the final confirmed quantity.                                                         |
| `settlement_failed`     | Terminal definitive rejection. Includes a reason and lock-expiry slot; submit a fresh signed order after unlock. |
| `expired` / `cancelled` | Terminal without a confirmed fill.                                                                               |

A market or fill-or-kill order that cannot execute in its arrival batch leaves the
book immediately rather than resting.

## Idempotency

`order_id` is your idempotency key. A retry that re-sends the **byte-identical**
signed order returns the original acceptance (`202`, same `order_id`) instead of
a conflict, so a network blip is safe to retry. Reusing an `order_id` for a
**different** order (any economic field changed) is a real conflict and returns
`409` (`code` 1201). Because order ids are client-chosen, pick a fresh one per
distinct order.

## Verification at intake

Every order is verified before it enters the book. A non-`202` response carries a
[structured error code](../getting-started/error-codes.mdx); the conditions:

| Check                                                                               | Status | Code |
| ----------------------------------------------------------------------------------- | ------ | ---- |
| Well-formed fields (hex widths, non-zero `order_id`)                                | `400`  | 1001 |
| Order amount meets the market minimum                                               | `400`  | 1004 |
| A bid has a positive price limit                                                    | `400`  | 1005 |
| The note opening re-derives the signed `note_commitment`                            | `400`  | 1006 |
| The collateral covers the order's nominal cost plus its own fee                     | `400`  | 1003 |
| Every non-zero price limit is a multiple of the market tick                         | `400`  | 1009 |
| The trading-key signature verifies over the canonical body                          | `403`  | 1102 |
| The viewing key is contributory                                                     | `400`  | 1008 |
| `expiry_slot` fits within the maximum on-chain lock lifetime                        | `400`  | 1007 |
| `expiry_slot` is in the future beyond the settlement buffer                         | `400`  | 1012 |
| The proof root is still in the venue's recent-root window                           | `400`  | 1010 |
| The VALID\_INPUT proof verifies against the declared commitment and collateral mint | `400`  | 1011 |
| The signed session matches this boot                                                | `409`  | 1205 |
| The `order_id` is not reused for a different order                                  | `409`  | 1201 |
| The nonce is strictly greater than the last accepted nonce for this trading key     | `409`  | 1202 |
| Per-account rate limit not exceeded                                                 | `429`  | 1401 |

Because the opening is checked against the *signed* commitment, the secret
opening fields are cryptographically pinned to your signature without being part
of the signed canonical body.

<Info>
  **Rate limits are weighted**

  Order management is rate-limited per account with a token bucket; cancels are
  cheap, place and modify cost more. A `429` includes a `Retry-After` header. For
  high-frequency management prefer the shared
  [`/v1/stream` session](../websocket/session-stream.mdx).
</Info>


## OpenAPI

````yaml api-reference/openapi/darknyx-public.yaml POST /orders
openapi: 3.1.0
info:
  title: Darknyx TEE API
  version: 4.1.0
  description: |
    Public + authenticated REST and WebSocket API for the Darknyx dark pool
    TEE matching layer. One attested endpoint may expose several independently
    routed spot markets. Pairs with the v2 on-chain custody program
    (vault, program ID `C63vKvysCzX55PKraas4Wc22ijqjGJQdPC1mrzCFVWZx`).
  contact:
    name: Darknyx engineering
  license:
    name: PolyForm Perimeter License 1.0.1
    url: https://polyformproject.org/licenses/perimeter/1.0.1
servers:
  - url: https://api.darknyx.example.com
    description: Mainnet placeholder; use the origin published with a deployment.
  - url: https://api.devnet.darknyx.example.com
    description: Devnet placeholder; use the origin published with a deployment.
security: []
tags:
  - name: auth
    description: OAuth2 client-credentials and bearer-token lifecycle.
  - name: attestation
    description: |
      Darknyx engine and transport attestation plus the deployment gateway's
      separate evidence bundle. Programmatic clients verify the certificate on
      their actual connection with `/transport-attestation` before any
      credential or sensitive write. `/evidences/*` describes surrounding
      ingress infrastructure and is not a substitute for the engine check.
  - name: info
    description: |
      Application/instance metadata, boot-session id, and settlement signers.
      Verify measured identity through `/attestation`, not self-reported fields.
  - name: instruments
    description: Public market metadata.
  - name: orders
    description: Place / cancel / modify / inspect orders.
  - name: system
    description: Public engine liveness + server time (GTT slot conversion).
  - name: account
    description: Per-account open orders and preferences. Balances remain client-derived.
  - name: tree
    description: >-
      Convenience Merkle-tree mirror; clients can verify the same state on
      Solana.
  - name: transparency
    description: Public solvency snapshot + engine identity + aggregate stats.
  - name: settlement
    description: Batch settlement status (TEE → L1 tx_signature lookup).
paths:
  /orders:
    post:
      tags:
        - orders
      summary: Place a new order.
      description: |
        Routes the signed symbol to one market book, checks the note opening,
        recent proof root, and VALID_INPUT proof before booking on a
        settlement-enabled venue, then reserves the collateral commitment
        inside this venue.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PlaceOrderRequest'
      responses:
        '202':
          description: Order accepted into the matching queue.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PlaceOrderResponse'
        '400':
          description: |
            Validation error, including malformed fields, off-tick price,
            opening mismatch, stale proof root (1010), invalid VALID_INPUT
            proof (1011), or an expired/settlement-unsafe expiry (1012).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          description: Missing / invalid / expired / revoked bearer token.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '403':
          description: Account suspended or trading-key signature invalid.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '409':
          description: |
            Conflict — the referenced note_commitment is already
            reserved by another live or settlement-pending order, the order id
            is in use, or a replay/session nonce is stale.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '429':
          description: Per-account order-operation limit exceeded. Includes Retry-After.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '503':
          description: >-
            New trading is paused because a required subsystem or finalized
            governance view is unavailable.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      security:
        - BearerAuth: []
components:
  schemas:
    PlaceOrderRequest:
      type: object
      description: |
        The canonical-order wire schema (`darknyx-order-v5` signature domain).
        All 32/64/16-byte fields are hex-encoded strings; all numeric fields are
        JSON integers (u64).
        The trading-key signature covers the canonical encoding of the
        economic fields, `viewing_pubkey`, `session_id`, and `arrival_nonce`;
        the opening fields (`owner_commitment`, `note_inner_hash`) are pinned
        indirectly because the matcher re-derives
        `note_commitment` from them and rejects a mismatch.
      required:
        - symbol
        - side
        - order_type
        - amount
        - price_limit
        - expiry_slot
        - order_id
        - note_commitment
        - arrival_nonce
        - trading_key
        - trading_key_signature
        - owner_commitment
        - note_inner_hash
        - merkle_root
        - valid_input_proof
        - viewing_pubkey
        - session_id
      properties:
        symbol:
          type: string
        side:
          type: string
          enum:
            - bid
            - ask
          description: '`bid` = buy base; `ask` = sell base.'
        order_type:
          type: string
          enum:
            - limit
            - ioc
            - fok
        amount:
          type: integer
          format: uint64
          description: Order size in base units.
        price_limit:
          type: integer
          format: uint64
          description: |
            Worst acceptable price, in quote units per base. Required for
            a bid (must be > 0); an ask may use `0` to accept any clearing
            price. Every non-zero value must be an integer multiple of the
            instrument's `tick_size`.
        min_fill_size:
          type: integer
          format: uint64
          description: |
            Optional (default 0). Reject fills smaller than this; set equal
            to `amount` for resting all-or-none.
        expiry_slot:
          type: integer
          format: uint64
          description: |
            Future Solana slot past which this order auto-expires. It must
            leave the matcher settlement buffer and is bounded by the protocol
            maximum (currently 4,500 slots) to prevent an unbounded
            collateral-lock window. Zero is not a GTC sentinel.
        order_id:
          type: string
          description: 16-byte client-chosen id, hex. Must be unique + non-zero.
        note_commitment:
          type: string
          description: |
            32-byte hex — Poseidon6 commitment to the collateral note this
            order is backed by. The opening and VALID_INPUT proof are checked
            at intake on a settlement-enabled venue. The commitment can reserve
            at most one live or settlement-pending order in this venue; the
            on-chain lock remains the final authority at settlement.
        arrival_nonce:
          type: integer
          format: uint64
          description: |
            Nonce bound into the signed canonical body. After exact-body
            idempotency handling, it must be strictly greater than every prior
            accepted nonce for the same trading key.
        trading_key:
          type: string
          description: 32-byte hex — the Ed25519 public key that owns this order.
        trading_key_signature:
          type: string
          description: |
            64-byte hex — Ed25519 signature over `sha256(canonical body)`
            from the trading key. Lets the TEE attribute the order to a
            specific key without a per-order on-chain tx.
        owner_commitment:
          type: string
          description: |
            32-byte hex — the collateral note's owner commitment
            `Poseidon2(DOMAIN_OWNER_V2=32, spending_key)`. Part of the
            input-note opening the in-TEE VALID_MATCH_BATCH prover needs
            (the circuit re-derives `note_commitment` from the opening).
            This is the only NOTE-BOUND owner identity an order carries, and
            the one settlement derives output notes back to. Verified against
            the signed `note_commitment` at intake. Held in enclave memory
            only.
        note_inner_hash:
          type: string
          description: |
            32-byte hex — the collateral note's amount-independent
            `inner_hash`, which anchors both its commitment and unlinkable
            note-use tag.
        merkle_root:
          type: string
          description: |
            32-byte hex — the merkle root the `valid_input_proof` was
            generated against. A settlement-enabled venue checks its recent-root
            mirror before accepting the order; `lock_note` checks the
            authoritative on-chain window again at settlement.
        valid_input_proof:
          type: string
          description: |
            256-byte hex (`pi_a ‖ pi_b ‖ pi_c`) — the per-note VALID_INPUT
            Groth16 proof that gates `lock_note`. The TEE cannot generate
            it (needs the spending key + merkle witness), so the client
            supplies it. A settlement-enabled venue verifies it at intake
            against `(merkle_root, note_use_tag, collateral mint)`, deriving
            the tag from the supplied commitment + private inner hash;
            on-chain `lock_note` verifies it again. Enqueue-only simulator /
            load-test deployments do not settle and may deliberately accept
            stub proofs.
        collateral_amount:
          type: integer
          format: uint64
          description: |
            Optional over-collateralization: the actual value the
            collateral note carries when it exceeds the order's nominal
            cost. Lets a large note back a small order; the surplus returns
            as a change note. Omit for exact collateral.
        tree_id:
          type: integer
          format: uint8
          default: 0
          description: |
            Merkle-tree shard containing the collateral note. Intake rejects an
            out-of-range shard and checks the proof root against this shard's
            recent-root window before booking.
        viewing_pubkey:
          type: string
          description: |
            Required 32-byte contributory X25519 viewing-encryption public key,
            hex (`deriveViewingEncKeypair().publicKey`). The TEE
            encrypts each fill's `(trade, change)` output amounts to it and
            writes the ciphertext on-chain, so exact and partial output notes
            remain recoverable after a CVM redeploy. It is signed; low-order
            encodings that yield an all-zero shared secret are rejected.
        session_id:
          type: string
          pattern: ^[0-9a-fA-F]{64}$
          description: |
            Required 32-byte boot session id from `GET /info`, hex, bound into
            the signature. A stale session is rejected even when every other
            field and signature is valid. Programmatic clients confirm that the
            value matches the boot session bound by `/transport-attestation`;
            a substituted value causes rejection rather than stale-session
            acceptance.
    PlaceOrderResponse:
      type: object
      required:
        - order_id
        - status
        - arrival_slot
      properties:
        order_id:
          type: string
        status:
          type: string
          enum:
            - accepted
        arrival_slot:
          type: integer
          format: uint64
    Error:
      type: object
      description: |
        The error envelope. Every non-2xx response renders as this shape, with
        the mapped HTTP status. Success responses are NOT enveloped (their typed
        body is returned directly). Every response — success and error — carries
        an `x-request-id` header for correlation with server logs.
      required:
        - code
        - message
      properties:
        code:
          type: integer
          description: |
            Stable numeric error code. Ranges: 1000–1099 request validation,
            1100–1199 auth, 1200–1299 conflict, 1300–1399 not found, 1400–1499
            rate limit, 5000+ server. See the Error Codes reference.

            One exception to the ranges: `1402` is returned with HTTP 503, not
            429. It signals that credential verification is momentarily at
            capacity and was refused rather than queued. Branch on the numeric
            code rather than inferring the status from its range.
          example: 1102
        message:
          type: string
          example: trading_key_signature does not verify against the canonical body
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: |
        Short-lived (≤ 1h) bearer token from POST /auth/token.

        Expiry is EXACT — there is no grace period past `expires_in`, on REST
        or on the streaming transport. Refresh on a margin.

        A structurally valid, unexpired token is still refused when it has been
        revoked (401), when the operator has invalidated the tokens the account
        was holding (401), or when the account is suspended (403). Suspension
        also blocks issuing a new one, so re-authenticating does not clear it.

````