# Track orders

Follow an order with the SDK until it ends, look it up later by any of its transactions, and keep your records right with webhooks. It is for developers building a progress screen, an activity list or a ledger.

Every route reports one `state`, from nine values; branch on `state` and keep `rawStatus` for support. The meaning of each: [Order states](https://maxy.co/docs/order-states).

## Watch an order

`orders.watch` yields the order each time its state or `btcTxId` changes, and stops at a final state or at `refundable`, where nothing more happens without the user. It listens to `GET /orders/{id}/events/stream` and falls back to polling from 1 second, backing off to 5. In a browser it opens the stream with a ticket, so a publishable key works.

```ts
import { createMaxyClient } from 'maxy-labs/core';

const maxy = createMaxyClient(); // reads MAXY_API_KEY

for await (const status of maxy.orders.watch(orderId, { chainId: 8453 })) {
  console.log(status.state, status.rawStatus, status.btcTxId);
}
// pending SANDBOX_PENDING null
// in_progress SANDBOX_FILLING null
// completed SANDBOX_COMPLETED 53414e44424f58…

const { events } = await maxy.orders.events(orderId); // each state with its time
const found = await maxy.status.byTxHash(escrowTxHash); // any transaction of the order
console.log(events.map((e) => e.state), found.state); // [ 'pending', 'in_progress', 'completed' ] completed
```

`orderId` is the one `POST /orders` answered, and `escrowTxHash` the escrow transaction's hash. Pass the paying chain as `chainId`, and for a Solana or coin-to-coin order its `route` too, as `GET /status` takes them. Watching gives up after 30 minutes by default (`maxWatchMs`) and throws `TimeoutError`, while the order carries on. `orders.resume(orderId)` follows it again from any process, and `.done()` answers its last state.

| Call | Route | Use it for |
| --- | --- | --- |
| `orders.get(id, { chainId })` | `GET /orders/{id}` | One read of where it is |
| `orders.events(id)` | `GET /orders/{id}/events` | Its history, each state with its time |
| `status.byTxHash(hash)` | `GET /status?txHash=` | An order found from any of its transactions, EVM or Bitcoin |
| `orders.list({ from, to, state })`, `orders.iterate` | `GET /orders` | The orders placed with your key, newest first |

A brand-new order id reads `pending`, never `404`. The flow helpers report the same changes through `onProgress`: keep the `orderId` it gives you, and pass `resume: { orderId }` to pick up after a reload ([Flow helpers](https://maxy.co/docs/flow-helpers)).

## Webhooks for your records

A screen stops watching when the user closes it. Webhooks do not: Maxy sends your server one signed `order.updated` event per change of `state` or `btcTxId`, for orders placed with your key. `webhooks.create(url)` registers an HTTPS endpoint and answers its signing secret, once; `orders.follow` adds an order placed another way. Delivery is at least once, so process each event `id` once.

In your endpoint, check the signature on the raw body before you trust the event. `constructEvent` does it from a web `Request`, and throws `WebhookSignatureError` on a bad or stale signature. `handleOnce` runs your handler only for an event id you have not seen.

```ts
import { constructEvent, handleOnce } from 'maxy-labs/server';

// alreadyProcessed(id) and saveEvent(event) are yours: saveEvent stores event.id with event.data.
export async function POST(req: Request): Promise<Response> {
  let event;
  try {
    event = await constructEvent(req, process.env.MAXY_WEBHOOK_SECRET!);
  } catch {
    return new Response('bad signature', { status: 400 });
  }
  await handleOnce(event, alreadyProcessed, saveEvent);
  return new Response(null, { status: 204 });
}
```

Answer `2xx` within 10 seconds; otherwise Maxy retries. Event fields, retries and the published test vector: [Webhooks](https://maxy.co/docs/webhooks).

## When an order stops

| `state` | Do |
| --- | --- |
| `completed` | Show `btcTxId` as a link to any Bitcoin explorer |
| `refundable` | Offer the refund from the user's wallet: [When it fails](https://maxy.co/docs/when-it-fails) |
| `expired`, `failed` | Read `rawStatus` and `failureReason`, and send Maxy the order id and hashes |

In the sandbox an order walks by itself, and `sandboxControls.advance` moves it on at once: [Test your integration](https://maxy.co/docs/test-your-integration).

---
Source: https://maxy.co/docs/track-orders (Maxy Docs › SDK › Using the SDK)
