Per-endpoint reference for the OFFER-HUB order API — create, list, get, reserve, cancel, and milestone completion — with real DTO fields, valid state transitions, error codes, idempotency behavior, and cURL plus TypeScript SDK examples.
An OFFER-HUB order is the lifecycle root of a marketplace transaction: it records the buyer, the seller, the amount, and the work, and every money movement in the escrow flow is driven by its status. Five endpoints drive an order from creation up to the point where escrow takes over, and two more track delivery against the order's milestones.
All seven handlers live in OrdersController (apps/api/src/modules/orders/orders.controller.ts) and delegate to OrdersService (apps/api/src/modules/orders/orders.service.ts). With the global /api/v1 prefix set in apps/api/src/main.ts, the paths above are the full routes.
Note
The other four routes on the same controller are documented on their own pages, because they are the money-moving steps: POST /api/v1/orders/{id}/escrow and POST /api/v1/orders/{id}/escrow/fund in Escrow Endpoints, and release / refund / dispute under /orders/{orderId}/resolution/* in Resolution Endpoints. This page is the lifecycle up to funding and the milestone bookkeeping insideIN_PROGRESS. Field lists here were transcribed from the orchestrator behavior recorded in Orders SDK Reference (apps/api/src/modules/orders/dto/create-order.dto.ts, apps/api/src/modules/orders/dto/cancel-order.dto.ts, packages/sdk/src/resources/orders.ts), the Data Model Prisma tables, and the API Reference overview.
Common behavior
Authentication and scope
OrdersController declares no guards and no scopes — there is no @UseGuards(ApiKeyGuard, ScopeGuard) and no @Scopes(...) on it (see the same finding for its escrow handlers in Escrow Endpoints). These routes are therefore not authenticated and not scope-gated in the current Orchestrator.
Documentation table
Aspect
Value on these routes
Source
Authentication
None enforced (no ApiKeyGuard)
apps/api/src/modules/orders/orders.controller.ts
Required scope
None (no ScopeGuard / @Scopes)
apps/api/src/modules/orders/orders.controller.ts
Rate limiting
Yes — global RateLimitGuard via APP_GUARD, 100 requests per 60-second window
The examples below send Authorization: Bearer … anyway, because every other reference in these docs does, and because a future release may attach ApiKeyGuard to this controller. Today the header is ignored by these seven routes. The scope model that does exist (read, write, support — see API Key Scopes) is enforced on other modules, not here.
Request validation
The global ValidationPipe runs with whitelist: true, forbidNonWhitelisted: true, and transform: true (apps/api/src/main.ts), so on the two endpoints that bind a DTO:
Unknown body properties are rejected with 400 VALIDATION_ERROR, not silently dropped.
A malformed amount ("100", "100.5", 100, "$100.00") fails the same way — amounts are decimal strings with exactly two places. See Amounts and currencies.
GET routes bind no body, and reserve / completeMilestone bind no DTO either, so the pipe has nothing to reject there.
Success status codes
None of the four POST handlers here (create, reserve, cancel, completeMilestone) declares @HttpCode, so NestJS applies its default 201 Created; the three GET handlers return 200 OK. That matches the escrow pair (Escrow Endpoints) and differs from the resolution endpoints, which set 200 explicitly except dispute.
ResponseInterceptor (apps/api/src/common/interceptors/response.interceptor.ts) wraps the handler's { success, data } payload — isAlreadyWrapped only skips wrapping when a meta key is present or the payload has exactly one key — so a successful single-resource call looks like this on the wire:
Errors use the single-level envelope from GlobalExceptionFilter (apps/api/src/common/filters/global-exception.filter.ts): { "error": { "code", "message", "details?" } }.
Warning
details is not a fixed shape. For validation failures the error catalog and this page use details.fields — an array of { field, message } — while Resolution Endpoints shows details.validationErrors, a flat array of message strings. Read both, and never assume details keys exist: INSUFFICIENT_FUNDS carries { available, requested }, INVALID_STATE carries the current state, and several codes carry no details at all.
Tip
The TypeScript SDK's HTTP client returns the parsed JSON body typed as the resource, so with this envelope the order actually sits one level deeper. Every SDK example on this page unwraps it the same way the escrow and resolution examples do: const order = (result as any).data?.data ?? result.
Idempotency
Danger
None of the seven endpoints on this page honors the Idempotency-Key header.IdempotencyGuard, IdempotencyInterceptor, and @IdempotencyTtl() exist (apps/api/src/common/guards/idempotency.guard.ts, apps/api/src/common/interceptors/idempotency.interceptor.ts, apps/api/src/common/decorators/idempotency-ttl.decorator.ts) but are not attached to OrdersController, so a key sent to /orders* is ignored — including the POST /orders example in Idempotency and the sdk.withIdempotencyKey(...) helper in the Orders Guide, which therefore set a header nothing reads here.
Retries are made safe by the state machine instead: POST /orders has no replay protection at all (each retry creates a new ord_ row — deduplicate with the unique clientOrderRef), while every state-changing sub-route rejects a replay with 400 INVALID_STATE once the order has left its required state. See Known behavior for the documents that still claim otherwise.
Amounts and currencies
Documentation table
Rule
Detail
amount is a string
Decimal string with exactly two places ("2500.00"). Numbers, "2500", "2500.5", and anything with a currency symbol are rejected.
currency defaults to "USD"
Omitting it on create stores "USD"; the value is copied onto the escrow row.
Settlement is USDC
The escrow leg moves USDC on Stellar regardless of the label, and only USDC is supported for balances today — see Multi-Currency. XLM and other codes in the overview tables are roadmap items.
Amount is stored as-is
order.amount is the source of truth for reserve, escrow creation, and funding; none of those endpoints accept an amount.
Order and milestone state transitions
Mermaid
Rendering diagram…
Order state machine — every edge is an entry in ORDER_TRANSITIONS
Documentation table
Endpoint
Order before
Order after
POST /orders
— (new row)
ORDER_CREATED
POST /orders/{id}/reserve
ORDER_CREATED
FUNDS_RESERVED
POST /orders/{id}/cancel
ORDER_CREATED or FUNDS_RESERVED
CLOSED (finalStatus: "CANCELED")
POST /orders/{id}/escrow
FUNDS_RESERVED
ESCROW_CREATING → ESCROW_FUNDING
POST /orders/{id}/escrow/fund
ESCROW_FUNDING
IN_PROGRESS (escrow FUNDED)
POST /orders/{id}/milestones/{ref}/complete
IN_PROGRESS
IN_PROGRESS — milestone becomes COMPLETED
Transitions are enforced by OrderStateMachine.assertTransition(from → to) (packages/shared/src/utils), whose table lives with the enum in packages/shared/src/enums/order-status.enum.ts. Milestones do not advance the order machine: a milestone moves only its own MilestoneStatus (OPEN → COMPLETED), and release is a separate call that requires every milestone to be COMPLETED — see Resolution Endpoints.
POST /api/v1/orders
Creates the order row and, optionally, its milestones. OrdersService.createOrder validates the DTO, resolves both parties, checks that the milestone amounts sum to the order amount, and writes the orders row in ORDER_CREATED. No funds move and no contract is deployed by this call.
Request body
Validated against CreateOrderDto (apps/api/src/modules/orders/dto/create-order.dto.ts). Property names are camelCase, the same casing the response uses.
Create order request body
Name
Type
Required
Description
buyerId
string
Yes
Internal buyer user ID with the usr_ prefix. The buyer pays and signs the escrow transactions.
sellerId
string
Yes
Internal seller user ID with the usr_ prefix. The seller receives released funds and signs milestone completion.
amount
string
Yes
Decimal string with exactly two places, e.g. "100.00". Rejected as INVALID_AMOUNT when malformed.
title
string
Yes
Human-readable order title. Also used as the escrow contract title.
currency
string
No
Currency code. Defaults to "USD" when omitted.
Default: "USD"
description
string
No
Free-form scope text, nullable on the Order model.
clientOrderRef
string | null
No
Your own order reference. The column is unique, so reuse is the practical way to make creation idempotent.
Nullable
metadata
Record<string, any>
No
Arbitrary JSON. metadata.platformFee overrides the default 5% platform fee at escrow time.
Default: null
milestones
MilestoneInput[]
No
Sub-deliverables created with the order. When present, the amounts must sum exactly to amount.
ref
string
Yes
Marketplace milestone reference. Stored as milestoneRef and used in the /milestones/{milestoneRef}/complete path.
title
string
No
Milestone title stored on the Milestone row. The SDK input type names this field description.
amount
string
No
Decimal string with two places. Milestone amounts must sum to the order amount when milestones are sent.
Warning
Field naming: the REST body is camelCase here, as in every response example (buyerId, clientOrderRef) and in the Orders Guide cURL samples. The field tables in the Orders SDK Reference are written in snake_case (buyer_id, seller_id, client_order_ref) and name the milestone field description rather than title. With forbidNonWhitelisted: true the wrong casing is not forgiven — it returns 400 VALIDATION_ERROR — so confirm against apps/api/src/modules/orders/dto/create-order.dto.ts before you ship, and do not mix the two spellings in one body.
Preconditions
Both buyerId and sellerId resolve to existing users — otherwise 404 ORDER_NOT_FOUND.
buyerId and sellerId differ — sending the same user twice is 400 INVALID_REQUEST.
amount matches the decimal-string format — otherwise 400 INVALID_AMOUNT.
When milestones are present, their amounts sum exactly to amount; otherwise the request is rejected before anything is written.
clientOrderRef, when sent, is not already used by another order (unique column).
Response
201 The created order in ORDER_CREATED, with escrow: null and its milestones as OPEN.
Create order response
Create order response fields
Name
Type
Required
Description
data
object
Yes
Standard envelope added by ResponseInterceptor.
data.success
boolean
Yes
Always true on a successful call.
data.data
object
Yes
The created order (OrderWithRelations).
data.data.id
string
Yes
Order ID with the ord_ prefix, generated server-side.
data.data.clientOrderRef
string | null
No
Your reference, echoed back.
Nullable
data.data.buyerId
string
Yes
Buyer user ID.
data.data.sellerId
string
Yes
Seller user ID.
data.data.amount
string
Yes
Order amount as a decimal string with two places.
data.data.currency
string
Yes
Currency code; USD when you omitted it.
data.data.status
string
Yes
Always ORDER_CREATED — nothing has moved yet.
One of: ORDER_CREATED
data.data.title
string
Yes
Order title.
data.data.description
string | null
No
Order description.
Nullable
data.data.metadata
object | null
No
Free-form JSON, stored as sent.
Nullable
data.data.escrow
object | null
No
Null until POST /orders/{id}/escrow creates the row.
Nullable
id
string
Yes
Escrow ID with the esc_ prefix.
trustlessContractId
string | null
No
Deployed Stellar contract address; null when the deployment did not return one.
Nullable
status
string
Yes
Escrow lifecycle status.
One of: CREATINGCREATEDFUNDINGFUNDEDRELEASINGRELEASEDREFUNDINGREFUNDEDDISPUTED
fundedAt
string | null
No
ISO 8601 funding timestamp.
Nullable
data.data.milestones
Milestone[]
Yes
Milestones created with the order; every one starts as OPEN. Empty array when you sent none.
id
string
Yes
Milestone ID (Prisma CUID).
milestoneRef
string
Yes
The ref you supplied; this is the path value for the complete endpoint.
title
string
Yes
Milestone title.
amount
string
Yes
Milestone amount as a decimal string.
status
string
Yes
Milestone status.
One of: OPENCOMPLETED
data.data.createdAt
string
Yes
ISO 8601 creation timestamp.
data.data.updatedAt
string
Yes
ISO 8601 update timestamp.
meta
object
Yes
Added by ResponseInterceptor: the correlation ID and a server timestamp.
meta.requestId
string
Yes
Your X-Request-ID, or the UUID v4 the server generated when you sent none.
A required field is missing, a field has the wrong type or casing, or the body carries an unknown property. details lists the field messages.
400
INVALID_REQUEST
buyerId and sellerId are the same user.
400
INVALID_AMOUNT
amount is not a two-decimal string, or the milestone amounts do not sum to it. The error catalog calls the same failure INVALID_AMOUNT_FORMAT (docs/guides/errors-troubleshooting.md).
404
ORDER_NOT_FOUND
The buyer or seller user ID does not exist — the orders module reports a missing party with the order code, not USER_NOT_FOUND (apps/api/src/modules/orders/exceptions/orders.exceptions.ts).
A duplicate clientOrderRef violates the unique column (docs/guides/orders.md), so treat that reference as your creation idempotency key rather than a retry mechanism.
# No money moves here: the order starts in ORDER_CREATED.# Milestone amounts must add up to the order amount.curl -X POST "http://localhost:4000/api/v1/orders" \-H "Authorization: Bearer ohk_live_xxxxxxxxxxxxxxxxxxxxxxxx" \-H "Content-Type: application/json" \-H "X-Request-ID: req_1ab90c" \-d '{ "buyerId": "usr_buyer123", "sellerId": "usr_seller456", "amount": "5000.00", "currency": "USD", "title": "Mobile App Development", "description": "Design, build and ship a customer app", "clientOrderRef": "REQ-1001", "milestones": [ { "ref": "design", "title": "UI/UX Design", "amount": "1000.00" }, { "ref": "backend", "title": "Backend Development", "amount": "2000.00" }, { "ref": "frontend", "title": "Frontend Development", "amount": "1500.00" }, { "ref": "testing", "title": "Testing & Launch", "amount": "500.00" } ]}'
import { OfferHubSDK } from "@offerhub/sdk";const sdk = new OfferHubSDK({apiUrl: "https://your-orchestrator.example.com",apiKey: "ohk_live_xxxxxxxxxxxxxxxxxxxxxxxx",});// The SDK input type is documented with snake_case keys and a// description field on milestones — see the naming warning above.const result = await sdk.orders.create({buyer_id: "usr_buyer123",seller_id: "usr_seller456",amount: "5000.00",title: "Mobile App Development",client_order_ref: "REQ-1001",milestones: [ { ref: "design", description: "UI/UX Design", amount: "1000.00" }, { ref: "backend", description: "Backend Development", amount: "2000.00" }, { ref: "frontend", description: "Frontend Development", amount: "1500.00" }, { ref: "testing", description: "Testing & Launch", amount: "500.00" },],});const order = (result as any).data?.data ?? result;console.log(order.id, order.status); // "ord_xyz789" "ORDER_CREATED"// Next steps in the lifecycle:await sdk.orders.reserve(order.id); // FUNDS_RESERVEDawait sdk.orders.createEscrow(order.id); // ESCROW_FUNDINGawait sdk.orders.fundEscrow(order.id); // IN_PROGRESS
GET /api/v1/orders
Lists orders newest first, with cursor pagination and role and status filters. OrdersController.listOrders parses the query and OrdersService.listOrders returns one page plus a cursor.
Query parameters
All parameters are optional. Filter keys on this endpoint are snake_case; see Filters. limit and cursor behave as described in Pagination.
List orders query parameters
Name
Type
Required
Description
buyer_id
string
No
Return orders where this user is the buyer.
seller_id
string
No
Return orders where this user is the seller. Sending both buyer_id and seller_id returns orders matching either one.
status
OrderStatus
No
Filter by one status. An unknown value is ignored rather than filtered on.
One of: ORDER_CREATEDFUNDS_RESERVEDESCROW_CREATINGESCROW_FUNDINGESCROW_FUNDEDIN_PROGRESSRELEASE_REQUESTEDRELEASEDREFUND_REQUESTEDREFUNDEDDISPUTEDCLOSED
limit
number
No
Items per page. Values above 100 are capped at 100; a missing or non-numeric value falls back to 20.
Default: 20
cursor
string
No
The nextCursor from the previous page (an order ID, e.g. ord_abc123). Omit it for the first page.
Note
This list is cursor-based, not offset-based. There is no page, pageSize, sort, search, or date-range parameter on this endpoint. The controller reads only the five keys above.
Response
200 One page of orders, newest first. The controller returns { success, data, hasMore, nextCursor }, and ResponseInterceptor wraps it, so the page info sits inside the outer data.
List orders response
List orders response fields
Name
Type
Required
Description
data
object
Yes
The controller payload, wrapped by ResponseInterceptor.
success
boolean
Yes
Always true on a 2xx.
data
Order[]
Yes
The page of orders. Each row includes its escrow (or null) and milestones relations.
hasMore
boolean
Yes
True when another page exists.
nextCursor
string
No
Present only when hasMore is true. Pass it as cursor on the next request.
meta.requestId
string
Yes
Your X-Request-ID, or the UUID v4 the server generated when you sent none.
This endpoint defines no endpoint-specific errors. Query values are parsed leniently: a non-numeric limit falls back to 20, and an unknown status is ignored.
Note
An empty match is a 200 with data.data: [] and data.hasMore: false, not a 404. The SDK reference lists 400 for a status outside the OrderStatus enum, but the controller ignores an unknown status instead of rejecting it. Treat a mistyped status as "filter not applied" and validate the value client-side.
Examples
# First page of in-progress orders for one buyercurl "http://localhost:4000/api/v1/orders?status=IN_PROGRESS&buyer_id=usr_buyer123&limit=20" \-H "Authorization: Bearer ohk_live_xxxxxxxxxxxxxxxxxxxxxxxx"# Next page: the cursor is data.nextCursor from the previous responsecurl "http://localhost:4000/api/v1/orders?status=IN_PROGRESS&buyer_id=usr_buyer123&limit=20&cursor=ord_abc123" \-H "Authorization: Bearer ohk_live_xxxxxxxxxxxxxxxxxxxxxxxx"
import { OfferHubSDK } from "@offerhub/sdk";const sdk = new OfferHubSDK({apiUrl: "https://your-orchestrator.example.com",apiKey: "ohk_live_xxxxxxxxxxxxxxxxxxxxxxxx",});const page = await sdk.orders.list({ status: "IN_PROGRESS", limit: 20 });// The SDK result is already unwrapped for you: data, hasMore, nextCursor.for (const order of page.data) {console.log(order.id, order.status, order.amount);}if (page.hasMore) {const next = await sdk.orders.list({ status: "IN_PROGRESS", limit: 20, cursor: page.nextCursor,});console.log(next.data.length);}
GET /api/v1/orders/:id
Fetches one order. OrdersService.getOrder loads the order by ID and includes its escrow and milestones relations.
Path parameters
Path parameters
Name
Type
Required
Description
id
string
Yes
Order ID with the ord_ prefix, e.g. ord_xyz789. Read via @Param('id').
Response
200 The full order resource — the shape every other endpoint on this page returns.
Get order response
Get order response fields
Name
Type
Required
Description
data
object
Yes
Standard envelope added by ResponseInterceptor.
data.success
boolean
Yes
Always true on a successful call.
data.data
object
Yes
The order, with escrow and milestones included (OrderWithRelations).
data.data.id
string
Yes
Order ID.
data.data.clientOrderRef
string | null
No
Your reference, or null.
Nullable
data.data.amount
string
Yes
Order amount as a decimal string.
data.data.currency
string
Yes
Currency code.
data.data.status
string
Yes
Current order status.
One of: ORDER_CREATEDFUNDS_RESERVEDESCROW_CREATINGESCROW_FUNDINGESCROW_FUNDEDIN_PROGRESSRELEASE_REQUESTEDRELEASEDREFUND_REQUESTEDREFUNDEDDISPUTEDCLOSED
data.data.title
string
Yes
Order title.
data.data.description
string | null
No
Order description.
Nullable
data.data.metadata
object | null
No
Free-form JSON as stored.
Nullable
data.data.escrow
object | null
No
The escrow row, or null before POST /orders/{id}/escrow.
Nullable
data.data.escrow.trustlessContractId
string | null
No
Stellar contract address of the escrow.
Nullable
data.data.escrow.status
string
Yes
Escrow lifecycle status; FUNDED once the money is on-chain.
One of: CREATINGCREATEDFUNDINGFUNDEDRELEASINGRELEASEDREFUNDINGREFUNDEDDISPUTED
data.data.escrow.terms
object | null
No
e.g. { milestones_required: true }; null when the order has no milestones.
Nullable
data.data.escrow.fundedAt
string | null
No
ISO 8601 funding timestamp.
Nullable
data.data.milestones
Milestone[]
Yes
Milestones ordered by creation time; empty when the order has none.
data.data.dispute
object | null
No
Not populated — see the note in Known behavior below.
Nullable
meta
object
Yes
Added by ResponseInterceptor: the correlation ID and a server timestamp.
import { OfferHubSDK } from "@offerhub/sdk";const sdk = new OfferHubSDK({apiUrl: "https://your-orchestrator.example.com",apiKey: "ohk_live_xxxxxxxxxxxxxxxxxxxxxxxx",});const result = await sdk.orders.get("ord_xyz789");const order = (result as any).data?.data ?? result;console.log(order.status); // "IN_PROGRESS"console.log(order.escrow?.status); // "FUNDED"console.log(order.milestones.map((m: any) => m.status)); // ["COMPLETED", "OPEN"]
POST /api/v1/orders/:id/reserve
Moves order.amount from the buyer's available balance to reserved, so the money cannot be spent on another order while the escrow is being set up. This is the mandatory step before escrow creation.
Path parameters
Path parameters
Name
Type
Required
Description
id
string
Yes
Order ID with the ord_ prefix.
Tip
Send no body. The amount is always read from order.amount and the currency from order.currency — exactly as for the escrow pair, which binds no @Body() at all (orders.controller.ts, Escrow Endpoints). The {"amount": "80.00"} body in the internal walkthrough docs/guides/orders.md and the two-argument sdk.orders.reserve(orderId, { amount }) form in docs/guides/errors-troubleshooting.md are not the shape the SDK reference documents; do not rely on a body being read.
Preconditions
The order exists — otherwise 404 ORDER_NOT_FOUND.
Order status is ORDER_CREATED — otherwise 400 INVALID_STATE (InvalidOrderStateException).
The buyer has an active payment account and an available balance covering order.amount — otherwise the reservation fails and nothing moves.
The order is not ORDER_CREATED — this is what a replayed reserve returns.
404
ORDER_NOT_FOUND
Unknown order ID.
409
FUNDS_ALREADY_RESERVED
The catalog's dedicated code for reserving twice (docs/guides/errors-troubleshooting.md). In practice the state machine usually rejects the retry with INVALID_STATE first — handle both.
422
INSUFFICIENT_FUNDS
Buyer available balance is below order.amount; details reports available and requested. The SDK reference lists this as 402 and the error catalog as 422 — branch on error.code, not the number.
json
{ "error": { "code": "INSUFFICIENT_FUNDS", "message": "Available balance is less than requested amount", "details": { "available": "1200.00", "requested": "5000.00" } }}
Examples
# No request body: the amount comes from the order.curl -X POST "http://localhost:4000/api/v1/orders/ord_xyz789/reserve" \-H "Authorization: Bearer ohk_live_xxxxxxxxxxxxxxxxxxxxxxxx" \-H "X-Request-ID: req_1ab92e"
import {OfferHubSDK,InsufficientFundsError,InvalidTransitionError,} from "@offerhub/sdk";const sdk = new OfferHubSDK({apiUrl: "https://your-orchestrator.example.com",apiKey: "ohk_live_xxxxxxxxxxxxxxxxxxxxxxxx",});try {const result = await sdk.orders.reserve("ord_xyz789");const order = (result as any).data?.data ?? result;console.log(order.status); // "FUNDS_RESERVED"} catch (error) {if (error instanceof InsufficientFundsError) { // Ask the buyer to top up — see /docs/guide/deposits} else if (error instanceof InvalidTransitionError) { // Already reserved (or later): treat the retry as a no-op}throw error;}
POST /api/v1/orders/:id/cancel
Cancels an order that has not reached escrow. The order goes straight to CLOSED with finalStatus: "CANCELED" — there is no CANCELED member in OrderStatus. If funds were reserved, they return to the buyer's available balance in the same transaction. This is an off-chain, instant operation: no Trustless Work call is made.
Free text recorded on the audit entry and in the order.canceled event payload. Omit the body entirely when you have nothing to record.
Warning
The body shape is inconsistent across the internal walkthroughs: docs/guides/orders.md sends { "canceledBy": "BUYER", "reason": "..." } and Escrow Flows sends { "requestedBy": "usr_seller456", "reason": "..." }, while the SDK reference documents only { reason?: string }. reason is the field every version agrees on — send that, and treat canceledBy / requestedBy as unverified. Because the pipe runs with forbidNonWhitelisted: true, a field the DTO does not declare is a 400 VALIDATION_ERROR, not a no-op.
Preconditions
The order exists — otherwise 404 ORDER_NOT_FOUND.
Order status is ORDER_CREATEDorFUNDS_RESERVED — the only cancellable states. Once the order is at ESCROW_CREATING or later, cancellation is refused and you must use refund or dispute instead (Resolution Endpoints).
CLOSED — the terminal state. There is no CANCELED status; the reason is carried in the audit entry and the order.canceled event.
One of: CLOSED
data.data.finalStatus
string | null
No
Recorded as CANCELED by the cancel flow in the internal walkthrough (docs/guides/orders.md). Not a column on the Order model — read status plus the audit trail if you need to distinguish a cancel from a release.
One of: CANCELEDNullable
data.data.escrow
object | null
No
Null for a canceled order — an escrow row can only exist from ESCROW_CREATING onward, and those states are not cancellable.
Nullable
data.data.milestones
Milestone[]
Yes
Milestones, still OPEN. Cancelling does not complete or delete them.
data.data.updatedAt
string
Yes
ISO 8601 timestamp of the cancellation.
meta
object
Yes
Added by ResponseInterceptor: the correlation ID and a server timestamp.
The body carries an unknown property or a non-string reason.
400
INVALID_STATE
The order is past FUNDS_RESERVED — escrow already started.
404
ORDER_NOT_FOUND
Unknown order ID.
json
{ "error": { "code": "INVALID_STATE", "message": "Cannot cancel order ord_xyz789 in state ESCROW_FUNDING" }}
Examples
curl -X POST "http://localhost:4000/api/v1/orders/ord_xyz789/cancel" \-H "Authorization: Bearer ohk_live_xxxxxxxxxxxxxxxxxxxxxxxx" \-H "Content-Type: application/json" \-H "X-Request-ID: req_1ab93f" \-d '{ "reason": "Buyer changed mind before escrow"}'
import { OfferHubSDK } from "@offerhub/sdk";const sdk = new OfferHubSDK({apiUrl: "https://your-orchestrator.example.com",apiKey: "ohk_live_xxxxxxxxxxxxxxxxxxxxxxxx",});// reason is optional: sdk.orders.cancel(orderId, data?)const result = await sdk.orders.cancel("ord_xyz789", {reason: "Buyer changed mind before escrow",});const order = (result as any).data?.data ?? result;console.log(order.status); // "CLOSED"// Reserved funds are returned to the buyer automatically:const balance = await sdk.balance.get("usr_buyer123");console.log(balance.available, balance.reserved);
GET /api/v1/orders/:id/milestones
Lists the milestones of one order, ordered by creation time. Milestones belong to their parent order and share its escrow — they are not separate orders, and this route returns only that order's rows.
Path parameters
Path parameters
Name
Type
Required
Description
id
string
Yes
Order ID with the ord_ prefix.
Note
No query parameters are supported here — no filters, no pagination. The list is the order's own milestone rows, so it is bounded by what you sent on POST /orders.
Response
200 The milestone array.
Milestones list response
Milestones list response fields
Name
Type
Required
Description
data
object
Yes
Standard envelope added by ResponseInterceptor.
success
boolean
Yes
Always true on a successful call.
data
Milestone[]
Yes
Milestones ordered by creation time; an empty array when the order was created without any.
data.data[].id
string
Yes
Milestone ID (Prisma CUID). Use milestoneRef, not this, in the complete path.
data.data[].orderId
string
Yes
Parent order ID.
data.data[].milestoneRef
string
Yes
The marketplace reference supplied at creation — the {milestoneRef} path value.
data.data[].title
string
Yes
Milestone title.
data.data[].amount
string
Yes
Milestone amount as a decimal string.
data.data[].status
string
Yes
Milestone status.
One of: OPENCOMPLETED
data.data[].createdAt
string
Yes
ISO 8601 creation timestamp.
meta
object
Yes
Added by ResponseInterceptor: the correlation ID and a server timestamp.
import { OfferHubSDK } from "@offerhub/sdk";const sdk = new OfferHubSDK({apiUrl: "https://your-orchestrator.example.com",apiKey: "ohk_live_xxxxxxxxxxxxxxxxxxxxxxxx",});const result = await sdk.orders.getMilestones("ord_xyz789");const milestones = (result as any).data?.data ?? result;const open = milestones.filter((m: any) => m.status === "OPEN");console.log(milestones.length, open.length); // 4 3// Release is only allowed once every milestone is COMPLETED:console.log(open.length === 0);
POST /api/v1/orders/:id/milestones/:milestoneRef/complete
Marks one milestone COMPLETED. This is a bookkeeping write on the order's milestone row — it moves no money and makes no on-chain call. The on-chain milestone signature happens later, inside resolution/release, which refuses to run while any milestone is still OPEN.
Milestones only move from OPEN to COMPLETED; the Milestone state machine lists every INVALID_STATE case around them, including the release guard.
Path parameters
Path parameters
Name
Type
Required
Description
id
string
Yes
Order ID with the ord_ prefix.
milestoneRef
string
Yes
The ref supplied when the order was created, matched against Milestone.milestoneRef. Path segments are read with @Param('milestoneRef'); the overview table shows the same slot as {ref}. Use the milestoneRef value — it is the field name on the resource.
Tip
This endpoint has no request body, and the route binds no DTO — see the Orders Guide. Send no Content-Type: application/json with an empty object: with forbidNonWhitelisted: true an unexpected {} is not the risk, but any property you invent is a 400 VALIDATION_ERROR.
Preconditions
The order exists — otherwise 404 ORDER_NOT_FOUND.
Order status is IN_PROGRESS — otherwise 400 INVALID_STATE. Before funding the order is not in the work window; after release, refund, or dispute it never is again.
A milestone with that milestoneRef exists on this order — otherwise 404 MILESTONE_NOT_FOUND.
The milestone is not already COMPLETED — otherwise 400 INVALID_STATE, which is what makes a retry harmless.
Response
201 The completed milestone.
Milestone completion response
Milestone completion response fields
Name
Type
Required
Description
data
object
Yes
Standard envelope added by ResponseInterceptor.
data.success
boolean
Yes
Always true on a successful call.
data.data
object
Yes
The updated milestone.
id
string
Yes
Milestone ID (Prisma CUID).
orderId
string
Yes
Parent order ID.
milestoneRef
string
Yes
The reference you passed in the path.
title
string
Yes
Milestone title.
amount
string
Yes
Milestone amount as a decimal string.
status
string
Yes
COMPLETED after this call.
One of: COMPLETED
createdAt
string
Yes
ISO 8601 creation timestamp.
meta
object
Yes
Added by ResponseInterceptor: the correlation ID and a server timestamp.
Completing the last milestone does not settle the order. Once every milestone reads COMPLETED, call POST /api/v1/orders/{orderId}/resolution/release to move the money — see Resolution Endpoints.
Errors
Documentation table
HTTP
error.code
When
400
INVALID_STATE
Order is not IN_PROGRESS, or the milestone is already COMPLETED. Raised by InvalidOrderStateException as a BadRequestException; the shared ERROR_HTTP_STATUS catalog maps INVALID_STATE to 409, so branch on error.code.
404
ORDER_NOT_FOUND
Unknown order ID.
404
MILESTONE_NOT_FOUND
No milestone with that milestoneRef on the order — a wrong or renamed ref.
json
{ "error": { "code": "MILESTONE_NOT_FOUND", "message": "Milestone qa not found on order ord_xyz789" }}
Examples
# No request body. The order must be IN_PROGRESS.curl -X POST "http://localhost:4000/api/v1/orders/ord_xyz789/milestones/design/complete" \-H "Authorization: Bearer ohk_live_xxxxxxxxxxxxxxxxxxxxxxxx" \-H "X-Request-ID: req_1ab951"
import { OfferHubSDK, InvalidTransitionError } from "@offerhub/sdk";const sdk = new OfferHubSDK({apiUrl: "https://your-orchestrator.example.com",apiKey: "ohk_live_xxxxxxxxxxxxxxxxxxxxxxxx",});// sdk.orders.completeMilestone(orderId, milestoneRef)const result = await sdk.orders.completeMilestone("ord_xyz789", "design");const milestone = (result as any).data?.data ?? result;console.log(milestone.milestoneRef, milestone.status); // "design" "COMPLETED"// Complete the rest, then release — release rejects while any is OPEN.try {for (const ref of ["backend", "frontend", "testing"]) { await sdk.orders.completeMilestone("ord_xyz789", ref);}} catch (error) {if (error instanceof InvalidTransitionError) { console.warn("already completed or order not IN_PROGRESS", ref);} else { throw error;}}
Events emitted by this group
Every endpoint above publishes domain events to the SSE stream. Filtering is by exact event name, repeated per type (?types=order.created&types=order.closed&resources=Order) — types=order.* is only valid on the internal event bus, not on the public stream.
The milestone event is namespaced under escrow.*, not order.* — an order.milestone_completed event does not exist. Listing only the order event names on your types filter will never show milestone completions; add escrow.milestone_completed explicitly.
Error codes for this group
Every code below is defined once in packages/shared/src/constants/error-codes.ts and rendered by GlobalExceptionFilter.
Documentation table
Code
HTTP
Endpoints
Meaning
VALIDATION_ERROR
400
POST /orders, cancel
DTO validation failed; details lists the field messages.
INVALID_REQUEST
400
POST /orders
Buyer and seller are the same user.
INVALID_AMOUNT
400
POST /orders
Amount format invalid, or milestone amounts do not sum to the order amount.
INVALID_STATE
400
reserve, cancel, milestones/{ref}/complete
The order (or milestone) is not in the state this step requires.
ORDER_NOT_FOUND
404
all seven
Unknown orderId, or an unknown buyer/seller ID on create.
MILESTONE_NOT_FOUND
404
milestones/{ref}/complete
No milestone with that milestoneRef on the order.
INSUFFICIENT_FUNDS
422
reserve
Buyer's available balance is below the order amount.
FUNDS_ALREADY_RESERVED
409
reserve
The catalog's dedicated code for a second reserve; the state machine often answers INVALID_STATE first, so handle both.
RATE_LIMITED
429
all seven
Over the global 100 requests / 60 s window.
INTERNAL_ERROR
500
all seven
Database or provider failure outside the validated flow.
Known behavior
Danger
Idempotency is documented three ways. The guards and interceptors are genuinely not attached to OrdersController — the same finding the Escrow and Resolution pages record for the other handlers on those controllers — yet docs/guides/orders.md states that "all state-changing order endpoints accept an Idempotency-Key", and Escrow Flows advises always sending one when funding. Plan for the header being ignored: deduplicate creation with clientOrderRef and treat 400 INVALID_STATE as "already done".
Warning
order.dispute is never populated on read.OrdersService.getOrder includes only escrow and milestones, so the dispute relation on the response is undefined even when a dispute exists. Read disputes through GET /api/v1/disputes/{id} instead of the order payload — this is also why the "no active dispute" precondition on release and refund never fires from that field (Resolution Endpoints).
Warning
INVALID_STATE arrives as HTTP 400, not 422 or 409.InvalidOrderStateException extends BadRequestException, while the shared catalog's ERROR_HTTP_STATUS table maps the code to 409 and docs/guides/orders.md documents 409 INVALID_STATE for every rejected transition. Likewise INSUFFICIENT_FUNDS is 402 in the SDK reference and 422 in the overview catalog. Trust the status you receive and branch on error.code.
Note
Cancel and the milestone reference naming. Cancellation has no CANCELED status — the order becomes CLOSED, with finalStatus: "CANCELED" recorded by the internal walkthrough only. And the path slot for a milestone is written {ref} in the endpoint table and {milestoneRef} in the SDK reference; the field on the resource is milestoneRef, so that is the value you substitute.
Related
Escrow Endpoints — the next two steps: POST /orders/{id}/escrow and POST /orders/{id}/escrow/fund, with contract roles and signer identity
Resolution Endpoints — release, refund, and dispute, the three ways a funded order settles; release requires every milestone COMPLETED
API Reference overview — base URL, headers, error envelope, idempotency, pagination, and the full endpoint catalog
Orders SDK Reference — sdk.orders method-by-method reference, one row per endpoint on this page
Orders Guide — lifecycle narrative with cURL and SDK samples
Data Model — Order, Escrow, and Milestone columns and the enum tables
Events (SSE) — payload shapes for the events listed above
Escrow Flows and Deposits — money movement behind reserve, and how a buyer funds the balance it debits