@polyester/sdk 0.34.1-devnet-20261106025831 → 0.35.0-devnet-20261107174905

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +21 -1
  2. package/README.md +12 -0
  3. package/dist/index.d.ts +2 -2
  4. package/dist/realtime/client.d.ts.map +1 -1
  5. package/dist/realtime/client.js +178 -29
  6. package/dist/realtime/client.js.map +1 -1
  7. package/dist/realtime/index.d.ts +2 -2
  8. package/dist/realtime/types.d.ts +21 -2
  9. package/dist/realtime/types.d.ts.map +1 -1
  10. package/dist/services/candles/candles.schemas.d.ts +10 -10
  11. package/dist/services/checkpoints/checkpoints.schemas.d.ts +8 -2
  12. package/dist/services/checkpoints/checkpoints.schemas.d.ts.map +1 -1
  13. package/dist/services/checkpoints/checkpoints.schemas.js +6 -0
  14. package/dist/services/checkpoints/checkpoints.schemas.js.map +1 -1
  15. package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
  16. package/dist/services/lifecycle/lifecycle.schemas.d.ts +79 -79
  17. package/dist/services/orderbook/orderbook.d.ts +1 -1
  18. package/dist/services/orderbook/orderbook.js +1 -1
  19. package/dist/services/orderbook/orderbook.js.map +1 -1
  20. package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
  21. package/dist/services/orders/orders-batch.schemas.d.ts +7 -7
  22. package/dist/services/orders/orders-output.schemas.d.ts +3 -3
  23. package/dist/services/orders/orders.d.ts +1 -1
  24. package/dist/services/orders/orders.js +1 -1
  25. package/dist/services/orders/orders.js.map +1 -1
  26. package/dist/services/rewards/rewards.d.ts +1 -1
  27. package/dist/services/rewards/rewards.js +1 -1
  28. package/dist/services/rewards/rewards.js.map +1 -1
  29. package/dist/services/rewards/rewards.schemas.d.ts +7 -0
  30. package/dist/services/rewards/rewards.schemas.d.ts.map +1 -1
  31. package/dist/services/rewards/rewards.schemas.js +8 -1
  32. package/dist/services/rewards/rewards.schemas.js.map +1 -1
  33. package/dist/services/subaccounts/subaccounts.d.ts +1 -1
  34. package/dist/services/subaccounts/subaccounts.js +1 -1
  35. package/dist/services/subaccounts/subaccounts.js.map +1 -1
  36. package/dist/services/subaccounts/subaccounts.schemas.d.ts +10 -1
  37. package/dist/services/subaccounts/subaccounts.schemas.d.ts.map +1 -1
  38. package/dist/services/subaccounts/subaccounts.schemas.js +8 -1
  39. package/dist/services/subaccounts/subaccounts.schemas.js.map +1 -1
  40. package/dist/services/trades/trades.schemas.d.ts +2 -2
  41. package/dist/services/triggers/triggers-output.schemas.d.ts +19 -19
  42. package/dist/shared/connect-error-mapping.d.ts.map +1 -1
  43. package/dist/shared/connect-error-mapping.js +5 -2
  44. package/dist/shared/connect-error-mapping.js.map +1 -1
  45. package/dist/shared/errors.d.ts +1 -1
  46. package/dist/shared/errors.d.ts.map +1 -1
  47. package/dist/shared/errors.js.map +1 -1
  48. package/dist/shared/subscription-errors.d.ts +2 -0
  49. package/dist/shared/subscription-errors.d.ts.map +1 -1
  50. package/dist/shared/subscription-errors.js.map +1 -1
  51. package/dist/shared/transports.js.map +1 -1
  52. package/package.json +1 -1
@@ -33,7 +33,7 @@ declare class OrderbookService {
33
33
  */
34
34
  subscribe(input: SubscribeOrderbookInput): () => void;
35
35
  /**
36
- * Creates a stateful order book subscription that first fetches a snapshot, buffers proto deltas from public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto, applies sequence-checked updates, and refetches on observed sequence gaps or reconnects. A snapshot whose book is not available fails with ServiceUnavailableError through onError and is retried; no event is emitted until a snapshot is available. The returned handle can unsubscribe or change local price bucket aggregation without reconnecting.
36
+ * Creates a stateful order book subscription that first fetches a snapshot, buffers proto deltas from public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto, applies sequence-checked updates, and refetches on observed sequence gaps or reconnects. A snapshot whose book is not available fails with ServiceUnavailableError through onError and is retried; no event is emitted until a snapshot is available. The snapshot is fetched once the channel opens, so a socket that cannot connect reports a retryable RealtimeError with type "transport" through onError instead, once per outage; onOpen follows when it recovers. The returned handle can unsubscribe or change local price bucket aggregation without reconnecting.
37
37
  *
38
38
  * `depth` is clamped to [1, 500] and rides the smallest published channel depth that covers it (see ORDERBOOK_WS_DEPTHS); levels are sliced back to the requested depth locally.
39
39
  *
@@ -50,7 +50,7 @@ var OrderbookService = class {
50
50
  return this.createSubscription(input).unsubscribe;
51
51
  }
52
52
  /**
53
- * Creates a stateful order book subscription that first fetches a snapshot, buffers proto deltas from public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto, applies sequence-checked updates, and refetches on observed sequence gaps or reconnects. A snapshot whose book is not available fails with ServiceUnavailableError through onError and is retried; no event is emitted until a snapshot is available. The returned handle can unsubscribe or change local price bucket aggregation without reconnecting.
53
+ * Creates a stateful order book subscription that first fetches a snapshot, buffers proto deltas from public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto, applies sequence-checked updates, and refetches on observed sequence gaps or reconnects. A snapshot whose book is not available fails with ServiceUnavailableError through onError and is retried; no event is emitted until a snapshot is available. The snapshot is fetched once the channel opens, so a socket that cannot connect reports a retryable RealtimeError with type "transport" through onError instead, once per outage; onOpen follows when it recovers. The returned handle can unsubscribe or change local price bucket aggregation without reconnecting.
54
54
  *
55
55
  * `depth` is clamped to [1, 500] and rides the smallest published channel depth that covers it (see ORDERBOOK_WS_DEPTHS); levels are sliced back to the requested depth locally.
56
56
  *
@@ -1 +1 @@
1
- {"version":3,"file":"orderbook.js","names":["#client","Proto.OrderbookService","#realtime","#scales","Proto.GetOrderBookResponseSchema","Proto.OrderBookDeltaSchema"],"sources":["../../../src/services/orderbook/orderbook.ts"],"sourcesContent":["import { create } from \"@bufbuild/protobuf\";\nimport * as Proto from \"../../gen/orderbook/v1/orderbook_pb.js\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport { publicationHandlerErrorContext } from \"../../shared/subscription-errors.js\";\nimport type { PolyesterRealtime } from \"../../realtime/types.js\";\nimport {\n snapshotThenStream,\n type SnapshotThenStreamSubscription,\n} from \"../../realtime/snapshot-then-stream.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport {\n toConnectCallOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport { decimalInputToScaled, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport {\n formatOrderbookLevel,\n GetOrderbookInputSchema,\n createOrderbookDataSchema,\n type OrderbookLevel,\n type OrderbookData,\n} from \"./orderbook.schemas.js\";\nimport { orderbookWsChannelDepth } from \"./orderbook.codecs.js\";\nimport { isResourceNotFoundError } from \"../../utils/errors.js\";\nimport { ServiceUnavailableError } from \"../../shared/errors.js\";\nimport type * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport type { PublicApiTransports } from \"../../shared/transports.js\";\n\ninterface SubscribeOrderbookInput extends BaseSubscribeInput<OrderbookData> {\n symbolId: number;\n depth?: number;\n bucket?: string | null;\n}\n\nexport interface OrderbookStreamHandlers extends BaseSubscribeInput<OrderbookData> {}\n\nexport interface OrderbookSubscription {\n unsubscribe: () => void;\n setBucket: (bucket: string | null | undefined) => void;\n}\n\nexport interface CreateOrderbookSubscriptionInput\n extends\n OrderbookStreamHandlers,\n Pick<SubscribeOrderbookInput, \"symbolId\" | \"depth\" | \"bucket\"> {}\n\ntype BookSide = Map<bigint, bigint>;\n\n/**\n * Reads spot order book snapshots and maintains realtime local order book state from public delta channels.\n */\nexport class OrderbookService {\n #client: Client<typeof Proto.OrderbookService>;\n #realtime: PolyesterRealtime;\n #scales: SdkScales;\n\n constructor(transports: PublicApiTransports, realtime: PolyesterRealtime, scales: SdkScales) {\n this.#client = createClient(Proto.OrderbookService, transports.publicApi);\n this.#realtime = realtime;\n this.#scales = scales;\n }\n\n /**\n * Fetches a spot order book depth snapshot for a symbol ID and requested depth, returning best bids and asks with the backend book sequence.\n * When `available` is false the book is being built or was invalidated: its levels are unknown, not empty, so read it again later instead of treating empty sides as no liquidity.\n */\n async get(\n input: v.InferInput<typeof GetOrderbookInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<OrderbookData> {\n const validated = parse(GetOrderbookInputSchema, input);\n await this.#scales.ready();\n const res = await this.#client.getOrderBook(\n { symbolId: validated.symbolId, depth: validated.protoDepth },\n toConnectCallOptions(options),\n );\n return parse(createOrderbookDataSchema(this.#scales, validated.symbolId), {\n symbolId: res.symbolId,\n depth: validated.depth,\n bookSeq: res.bookSeq,\n available: isBookAvailable(res),\n bids: res.bids,\n asks: res.asks,\n });\n }\n\n /**\n * Subscribes to the managed order book stream for a symbol ID and forwards reconstructed snapshots to onEvent. This is a convenience wrapper around createSubscription().unsubscribe.\n */\n subscribe(input: SubscribeOrderbookInput): () => void {\n return this.createSubscription(input).unsubscribe;\n }\n\n /**\n * Creates a stateful order book subscription that first fetches a snapshot, buffers proto deltas from public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto, applies sequence-checked updates, and refetches on observed sequence gaps or reconnects. A snapshot whose book is not available fails with ServiceUnavailableError through onError and is retried; no event is emitted until a snapshot is available. The returned handle can unsubscribe or change local price bucket aggregation without reconnecting.\n *\n * `depth` is clamped to [1, 500] and rides the smallest published channel depth that covers it (see ORDERBOOK_WS_DEPTHS); levels are sliced back to the requested depth locally.\n *\n * Refetching is driven by observed sequence gaps and reconnect events only. A feed that stays subscribed but stops publishing is indistinguishable from a quiet market, so it does not trigger onError or a refetch. Callers that must detect a stalled book need their own idle watchdog plus a REST refetch.\n */\n createSubscription(input: CreateOrderbookSubscriptionInput): OrderbookSubscription {\n const { symbolId } = parse(GetOrderbookInputSchema, {\n symbolId: input.symbolId,\n depth: input.depth,\n });\n const requestedDepth = Math.min(500, Math.max(1, Math.trunc(input.depth ?? 50)));\n const channelDepth = orderbookWsChannelDepth(requestedDepth);\n const channel = `public:spot:orderbook:deltas:depth:${channelDepth}:${symbolId}:proto`;\n\n const client = this.#client;\n const scales = this.#scales;\n let bidsMap: BookSide = new Map();\n let asksMap: BookSide = new Map();\n let currentBookSeq = 0n;\n let bucketTicks: bigint | null = null;\n let stream: SnapshotThenStreamSubscription | undefined;\n\n function levelsToMap(levels: Proto.PriceLevel[] | undefined): BookSide {\n const map: BookSide = new Map();\n for (const l of levels ?? []) {\n if (l.qtyScaled === 0n) continue;\n map.set(l.priceTicks, l.qtyScaled);\n }\n return map;\n }\n\n function applySideDelta(map: BookSide, levels: Proto.PriceLevel[] | undefined): void {\n for (const l of levels ?? []) {\n if (l.qtyScaled === 0n) map.delete(l.priceTicks);\n else map.set(l.priceTicks, l.qtyScaled);\n }\n }\n\n function sideToUI(map: BookSide, side: \"bids\" | \"asks\", limit: number): OrderbookLevel[] {\n const entries = Array.from(map.entries());\n entries.sort(([pa], [pb]) => {\n if (pa === pb) return 0;\n return side === \"bids\" ? (pa > pb ? -1 : 1) : pa < pb ? -1 : 1;\n });\n return entries\n .slice(0, limit)\n .map(([priceTicks, qtyScaled]) =>\n formatOrderbookLevel({ priceTicks, qtyScaled }, scales, symbolId),\n );\n }\n\n function sideToUIBucketed(\n map: BookSide,\n side: \"bids\" | \"asks\",\n limit: number,\n bucket: bigint | null,\n ): OrderbookLevel[] {\n if (!bucket || bucket <= 0n) return sideToUI(map, side, limit);\n\n const agg: BookSide = new Map();\n for (const [priceTicks, qtyScaled] of map.entries()) {\n if (qtyScaled <= 0n) continue;\n const bucketFloor = (priceTicks / bucket) * bucket;\n const bucketPrice =\n side === \"asks\" && bucketFloor !== priceTicks\n ? bucketFloor + bucket\n : bucketFloor;\n agg.set(bucketPrice, (agg.get(bucketPrice) ?? 0n) + qtyScaled);\n }\n return sideToUI(agg, side, limit);\n }\n\n function emit(): void {\n try {\n input.onEvent({\n symbolId,\n depth: requestedDepth,\n bookSeq: currentBookSeq.toString(),\n available: true,\n bids: sideToUIBucketed(bidsMap, \"bids\", requestedDepth, bucketTicks),\n asks: sideToUIBucketed(asksMap, \"asks\", requestedDepth, bucketTicks),\n });\n } catch (error) {\n input.onError?.(publicationHandlerErrorContext(channel, error));\n }\n }\n\n function setBucket(bucket: string | null | undefined): void {\n if (!bucket) {\n bucketTicks = null;\n } else {\n try {\n bucketTicks = decimalInputToScaled(\"bucket\", bucket, scales.price());\n } catch {\n bucketTicks = null;\n }\n }\n if (stream?.isReady()) emit();\n }\n\n async function inputServiceFetch(): Promise<Proto.GetOrderBookResponse> {\n await scales.ready();\n const validated = parse(GetOrderbookInputSchema, {\n symbolId,\n depth: channelDepth,\n });\n let res: Proto.GetOrderBookResponse;\n try {\n res = await client.getOrderBook({\n symbolId: validated.symbolId,\n depth: validated.protoDepth,\n });\n } catch (error: unknown) {\n if (!isResourceNotFoundError(error)) throw error;\n\n return create(Proto.GetOrderBookResponseSchema, {\n symbolId,\n bookSeq: 0n,\n available: true,\n bids: [],\n asks: [],\n });\n }\n // An unavailable book's levels are unknown, not empty: fail the snapshot so it is retried.\n if (!isBookAvailable(res)) {\n throw new ServiceUnavailableError(\n `Order book for symbol ${symbolId} is not available yet`,\n );\n }\n return res;\n }\n\n function handleDelta(delta: Proto.OrderBookDelta): boolean {\n if (delta.bookSeqEnd <= currentBookSeq) return true;\n\n if (delta.reset) {\n bidsMap.clear();\n asksMap.clear();\n currentBookSeq = 0n;\n }\n\n if (currentBookSeq !== 0n && delta.bookSeqStart > currentBookSeq + 1n) {\n stream?.refreshSnapshot();\n return false;\n }\n\n applySideDelta(bidsMap, delta.bids);\n applySideDelta(asksMap, delta.asks);\n\n currentBookSeq = delta.bookSeqEnd > currentBookSeq ? delta.bookSeqEnd : currentBookSeq;\n emit();\n return true;\n }\n\n setBucket(input.bucket);\n stream = snapshotThenStream({\n realtime: this.#realtime,\n channel,\n schema: Proto.OrderBookDeltaSchema,\n maxBufferedPublications: 200,\n snapshotErrorLog: \"Failed to fetch orderbook\",\n snapshotRetry: { maxAttempts: 3, delayMs: 1_000 },\n fetchSnapshot: inputServiceFetch,\n readPublication: (delta) => [delta],\n applySnapshot: (snapshot, bufferedDeltas) => {\n bidsMap = levelsToMap(snapshot.bids);\n asksMap = levelsToMap(snapshot.asks);\n currentBookSeq = snapshot.bookSeq;\n emit();\n for (const delta of bufferedDeltas) {\n if (stream?.isDisposed()) return;\n if (!handleDelta(delta)) return;\n }\n },\n applyLivePublications: (deltas) => {\n for (const delta of deltas) {\n if (stream?.isDisposed()) return;\n if (!handleDelta(delta)) return;\n }\n },\n onOpen: input.onOpen,\n onClose: input.onClose,\n onError: input.onError,\n });\n\n function dispose(): void {\n stream?.unsubscribe();\n }\n\n return { unsubscribe: dispose, setBucket };\n }\n}\n\n/**\n * Whether a snapshot's levels are the book. A snapshot carrying levels is current even with\n * `available` false, which is how servers that predate the field encode every snapshot.\n */\nfunction isBookAvailable(res: Proto.GetOrderBookResponse): boolean {\n return res.available || res.bids.length > 0 || res.asks.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoDA,IAAa,mBAAb,MAA8B;CAC1B;CACA;CACA;CAEA,YAAY,YAAiC,UAA6B,QAAmB;EACzF,KAAKA,UAAU,aAAaC,oBAAwB,WAAW,SAAS;EACxE,KAAKC,YAAY;EACjB,KAAKC,UAAU;CACnB;;;;;CAMA,MAAM,IACF,OACA,SACsB;EACtB,MAAM,YAAY,MAAM,yBAAyB,KAAK;EACtD,MAAM,KAAKA,QAAQ,MAAM;EACzB,MAAM,MAAM,MAAM,KAAKH,QAAQ,aAC3B;GAAE,UAAU,UAAU;GAAU,OAAO,UAAU;EAAW,GAC5D,qBAAqB,OAAO,CAChC;EACA,OAAO,MAAM,0BAA0B,KAAKG,SAAS,UAAU,QAAQ,GAAG;GACtE,UAAU,IAAI;GACd,OAAO,UAAU;GACjB,SAAS,IAAI;GACb,WAAW,gBAAgB,GAAG;GAC9B,MAAM,IAAI;GACV,MAAM,IAAI;EACd,CAAC;CACL;;;;CAKA,UAAU,OAA4C;EAClD,OAAO,KAAK,mBAAmB,KAAK,CAAC,CAAC;CAC1C;;;;;;;;CASA,mBAAmB,OAAgE;EAC/E,MAAM,EAAE,aAAa,MAAM,yBAAyB;GAChD,UAAU,MAAM;GAChB,O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OrderbookService","#realtime","#scales","Proto.GetOrderBookResponseSchema","Proto.OrderBookDeltaSchema"],"sources":["../../../src/services/orderbook/orderbook.ts"],"sourcesContent":["import { create } from \"@bufbuild/protobuf\";\nimport * as Proto from \"../../gen/orderbook/v1/orderbook_pb.js\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport { publicationHandlerErrorContext } from \"../../shared/subscription-errors.js\";\nimport type { PolyesterRealtime } from \"../../realtime/types.js\";\nimport {\n snapshotThenStream,\n type SnapshotThenStreamSubscription,\n} from \"../../realtime/snapshot-then-stream.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport {\n toConnectCallOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport { decimalInputToScaled, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport {\n formatOrderbookLevel,\n GetOrderbookInputSchema,\n createOrderbookDataSchema,\n type OrderbookLevel,\n type OrderbookData,\n} from \"./orderbook.schemas.js\";\nimport { orderbookWsChannelDepth } from \"./orderbook.codecs.js\";\nimport { isResourceNotFoundError } from \"../../utils/errors.js\";\nimport { ServiceUnavailableError } from \"../../shared/errors.js\";\nimport type * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport type { PublicApiTransports } from \"../../shared/transports.js\";\n\ninterface SubscribeOrderbookInput extends BaseSubscribeInput<OrderbookData> {\n symbolId: number;\n depth?: number;\n bucket?: string | null;\n}\n\nexport interface OrderbookStreamHandlers extends BaseSubscribeInput<OrderbookData> {}\n\nexport interface OrderbookSubscription {\n unsubscribe: () => void;\n setBucket: (bucket: string | null | undefined) => void;\n}\n\nexport interface CreateOrderbookSubscriptionInput\n extends\n OrderbookStreamHandlers,\n Pick<SubscribeOrderbookInput, \"symbolId\" | \"depth\" | \"bucket\"> {}\n\ntype BookSide = Map<bigint, bigint>;\n\n/**\n * Reads spot order book snapshots and maintains realtime local order book state from public delta channels.\n */\nexport class OrderbookService {\n #client: Client<typeof Proto.OrderbookService>;\n #realtime: PolyesterRealtime;\n #scales: SdkScales;\n\n constructor(transports: PublicApiTransports, realtime: PolyesterRealtime, scales: SdkScales) {\n this.#client = createClient(Proto.OrderbookService, transports.publicApi);\n this.#realtime = realtime;\n this.#scales = scales;\n }\n\n /**\n * Fetches a spot order book depth snapshot for a symbol ID and requested depth, returning best bids and asks with the backend book sequence.\n * When `available` is false the book is being built or was invalidated: its levels are unknown, not empty, so read it again later instead of treating empty sides as no liquidity.\n */\n async get(\n input: v.InferInput<typeof GetOrderbookInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<OrderbookData> {\n const validated = parse(GetOrderbookInputSchema, input);\n await this.#scales.ready();\n const res = await this.#client.getOrderBook(\n { symbolId: validated.symbolId, depth: validated.protoDepth },\n toConnectCallOptions(options),\n );\n return parse(createOrderbookDataSchema(this.#scales, validated.symbolId), {\n symbolId: res.symbolId,\n depth: validated.depth,\n bookSeq: res.bookSeq,\n available: isBookAvailable(res),\n bids: res.bids,\n asks: res.asks,\n });\n }\n\n /**\n * Subscribes to the managed order book stream for a symbol ID and forwards reconstructed snapshots to onEvent. This is a convenience wrapper around createSubscription().unsubscribe.\n */\n subscribe(input: SubscribeOrderbookInput): () => void {\n return this.createSubscription(input).unsubscribe;\n }\n\n /**\n * Creates a stateful order book subscription that first fetches a snapshot, buffers proto deltas from public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto, applies sequence-checked updates, and refetches on observed sequence gaps or reconnects. A snapshot whose book is not available fails with ServiceUnavailableError through onError and is retried; no event is emitted until a snapshot is available. The snapshot is fetched once the channel opens, so a socket that cannot connect reports a retryable RealtimeError with type \"transport\" through onError instead, once per outage; onOpen follows when it recovers. The returned handle can unsubscribe or change local price bucket aggregation without reconnecting.\n *\n * `depth` is clamped to [1, 500] and rides the smallest published channel depth that covers it (see ORDERBOOK_WS_DEPTHS); levels are sliced back to the requested depth locally.\n *\n * Refetching is driven by observed sequence gaps and reconnect events only. A feed that stays subscribed but stops publishing is indistinguishable from a quiet market, so it does not trigger onError or a refetch. Callers that must detect a stalled book need their own idle watchdog plus a REST refetch.\n */\n createSubscription(input: CreateOrderbookSubscriptionInput): OrderbookSubscription {\n const { symbolId } = parse(GetOrderbookInputSchema, {\n symbolId: input.symbolId,\n depth: input.depth,\n });\n const requestedDepth = Math.min(500, Math.max(1, Math.trunc(input.depth ?? 50)));\n const channelDepth = orderbookWsChannelDepth(requestedDepth);\n const channel = `public:spot:orderbook:deltas:depth:${channelDepth}:${symbolId}:proto`;\n\n const client = this.#client;\n const scales = this.#scales;\n let bidsMap: BookSide = new Map();\n let asksMap: BookSide = new Map();\n let currentBookSeq = 0n;\n let bucketTicks: bigint | null = null;\n let stream: SnapshotThenStreamSubscription | undefined;\n\n function levelsToMap(levels: Proto.PriceLevel[] | undefined): BookSide {\n const map: BookSide = new Map();\n for (const l of levels ?? []) {\n if (l.qtyScaled === 0n) continue;\n map.set(l.priceTicks, l.qtyScaled);\n }\n return map;\n }\n\n function applySideDelta(map: BookSide, levels: Proto.PriceLevel[] | undefined): void {\n for (const l of levels ?? []) {\n if (l.qtyScaled === 0n) map.delete(l.priceTicks);\n else map.set(l.priceTicks, l.qtyScaled);\n }\n }\n\n function sideToUI(map: BookSide, side: \"bids\" | \"asks\", limit: number): OrderbookLevel[] {\n const entries = Array.from(map.entries());\n entries.sort(([pa], [pb]) => {\n if (pa === pb) return 0;\n return side === \"bids\" ? (pa > pb ? -1 : 1) : pa < pb ? -1 : 1;\n });\n return entries\n .slice(0, limit)\n .map(([priceTicks, qtyScaled]) =>\n formatOrderbookLevel({ priceTicks, qtyScaled }, scales, symbolId),\n );\n }\n\n function sideToUIBucketed(\n map: BookSide,\n side: \"bids\" | \"asks\",\n limit: number,\n bucket: bigint | null,\n ): OrderbookLevel[] {\n if (!bucket || bucket <= 0n) return sideToUI(map, side, limit);\n\n const agg: BookSide = new Map();\n for (const [priceTicks, qtyScaled] of map.entries()) {\n if (qtyScaled <= 0n) continue;\n const bucketFloor = (priceTicks / bucket) * bucket;\n const bucketPrice =\n side === \"asks\" && bucketFloor !== priceTicks\n ? bucketFloor + bucket\n : bucketFloor;\n agg.set(bucketPrice, (agg.get(bucketPrice) ?? 0n) + qtyScaled);\n }\n return sideToUI(agg, side, limit);\n }\n\n function emit(): void {\n try {\n input.onEvent({\n symbolId,\n depth: requestedDepth,\n bookSeq: currentBookSeq.toString(),\n available: true,\n bids: sideToUIBucketed(bidsMap, \"bids\", requestedDepth, bucketTicks),\n asks: sideToUIBucketed(asksMap, \"asks\", requestedDepth, bucketTicks),\n });\n } catch (error) {\n input.onError?.(publicationHandlerErrorContext(channel, error));\n }\n }\n\n function setBucket(bucket: string | null | undefined): void {\n if (!bucket) {\n bucketTicks = null;\n } else {\n try {\n bucketTicks = decimalInputToScaled(\"bucket\", bucket, scales.price());\n } catch {\n bucketTicks = null;\n }\n }\n if (stream?.isReady()) emit();\n }\n\n async function inputServiceFetch(): Promise<Proto.GetOrderBookResponse> {\n await scales.ready();\n const validated = parse(GetOrderbookInputSchema, {\n symbolId,\n depth: channelDepth,\n });\n let res: Proto.GetOrderBookResponse;\n try {\n res = await client.getOrderBook({\n symbolId: validated.symbolId,\n depth: validated.protoDepth,\n });\n } catch (error: unknown) {\n if (!isResourceNotFoundError(error)) throw error;\n\n return create(Proto.GetOrderBookResponseSchema, {\n symbolId,\n bookSeq: 0n,\n available: true,\n bids: [],\n asks: [],\n });\n }\n // An unavailable book's levels are unknown, not empty: fail the snapshot so it is retried.\n if (!isBookAvailable(res)) {\n throw new ServiceUnavailableError(\n `Order book for symbol ${symbolId} is not available yet`,\n );\n }\n return res;\n }\n\n function handleDelta(delta: Proto.OrderBookDelta): boolean {\n if (delta.bookSeqEnd <= currentBookSeq) return true;\n\n if (delta.reset) {\n bidsMap.clear();\n asksMap.clear();\n currentBookSeq = 0n;\n }\n\n if (currentBookSeq !== 0n && delta.bookSeqStart > currentBookSeq + 1n) {\n stream?.refreshSnapshot();\n return false;\n }\n\n applySideDelta(bidsMap, delta.bids);\n applySideDelta(asksMap, delta.asks);\n\n currentBookSeq = delta.bookSeqEnd > currentBookSeq ? delta.bookSeqEnd : currentBookSeq;\n emit();\n return true;\n }\n\n setBucket(input.bucket);\n stream = snapshotThenStream({\n realtime: this.#realtime,\n channel,\n schema: Proto.OrderBookDeltaSchema,\n maxBufferedPublications: 200,\n snapshotErrorLog: \"Failed to fetch orderbook\",\n snapshotRetry: { maxAttempts: 3, delayMs: 1_000 },\n fetchSnapshot: inputServiceFetch,\n readPublication: (delta) => [delta],\n applySnapshot: (snapshot, bufferedDeltas) => {\n bidsMap = levelsToMap(snapshot.bids);\n asksMap = levelsToMap(snapshot.asks);\n currentBookSeq = snapshot.bookSeq;\n emit();\n for (const delta of bufferedDeltas) {\n if (stream?.isDisposed()) return;\n if (!handleDelta(delta)) return;\n }\n },\n applyLivePublications: (deltas) => {\n for (const delta of deltas) {\n if (stream?.isDisposed()) return;\n if (!handleDelta(delta)) return;\n }\n },\n onOpen: input.onOpen,\n onClose: input.onClose,\n onError: input.onError,\n });\n\n function dispose(): void {\n stream?.unsubscribe();\n }\n\n return { unsubscribe: dispose, setBucket };\n }\n}\n\n/**\n * Whether a snapshot's levels are the book. A snapshot carrying levels is current even with\n * `available` false, which is how servers that predate the field encode every snapshot.\n */\nfunction isBookAvailable(res: Proto.GetOrderBookResponse): boolean {\n return res.available || res.bids.length > 0 || res.asks.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoDA,IAAa,mBAAb,MAA8B;CAC1B;CACA;CACA;CAEA,YAAY,YAAiC,UAA6B,QAAmB;EACzF,KAAKA,UAAU,aAAaC,oBAAwB,WAAW,SAAS;EACxE,KAAKC,YAAY;EACjB,KAAKC,UAAU;CACnB;;;;;CAMA,MAAM,IACF,OACA,SACsB;EACtB,MAAM,YAAY,MAAM,yBAAyB,KAAK;EACtD,MAAM,KAAKA,QAAQ,MAAM;EACzB,MAAM,MAAM,MAAM,KAAKH,QAAQ,aAC3B;GAAE,UAAU,UAAU;GAAU,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AAM,SAAS,QAAQ;KACxB,IAAI,QAAQ,WAAW,GAAG;KAC1B,IAAI,CAAC,YAAY,KAAK,GAAG;IAC7B;GACJ;GACA,QAAQ,MAAM;GACd,SAAS,MAAM;GACf,SAAS,MAAM;EACnB,CAAC;EAED,SAAS,UAAgB;GACrB,QAAQ,YAAY;EACxB;EAEA,OAAO;GAAE,aAAa;GAAS;EAAU;CAC7C;AACJ;;;;;AAMA,SAAS,gBAAgB,KAA0C;CAC/D,OAAO,IAAI,aAAa,IAAI,KAAK,SAAS,KAAK,IAAI,KAAK,SAAS;AACrE"}
@@ -10,7 +10,7 @@ declare const GetOrderbookInputSchema: v.SchemaWithPipe<readonly [v.ObjectSchema
10
10
  depth: number;
11
11
  }, {
12
12
  symbolId: number;
13
- depth: 1 | 5 | 10 | 20 | 100 | 500 | 1000 | 200 | 50;
13
+ depth: 1 | 5 | 10 | 20 | 100 | 500 | 200 | 1000 | 50;
14
14
  protoDepth: Depth;
15
15
  }>]>;
16
16
  type GetOrderbookInput = v.InferInput<typeof GetOrderbookInputSchema>;
@@ -3754,7 +3754,7 @@ declare const GetBatchReplaceStatusResultSchema: v.SchemaWithPipe<readonly [v.Ob
3754
3754
  readonly admissionStatus: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "rejected" | "admitted" | "partially_admitted">]>;
3755
3755
  readonly items: v.ArraySchema<v.SchemaWithPipe<readonly [v.ObjectSchema<{
3756
3756
  readonly itemIndex: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
3757
- readonly phase: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "terminal" | "working" | "rejected" | "admitted">]>;
3757
+ readonly phase: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "working" | "rejected" | "terminal" | "admitted">]>;
3758
3758
  readonly oldOrderId: v.SchemaWithPipe<readonly [v.OptionalSchema<v.BigintSchema<undefined>, undefined>, v.TransformAction<bigint | undefined, string | undefined>]>;
3759
3759
  readonly replacementOrderId: v.SchemaWithPipe<readonly [v.OptionalSchema<v.BigintSchema<undefined>, undefined>, v.TransformAction<bigint | undefined, string | undefined>]>;
3760
3760
  readonly actionTaken: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "AMENDED" | "REPLACED">]>;
@@ -3763,7 +3763,7 @@ declare const GetBatchReplaceStatusResultSchema: v.SchemaWithPipe<readonly [v.Ob
3763
3763
  readonly updatedTsNs: v.BigintSchema<undefined>;
3764
3764
  }, undefined>, v.TransformAction<{
3765
3765
  itemIndex: number;
3766
- phase: "unspecified" | "terminal" | "working" | "rejected" | "admitted";
3766
+ phase: "unspecified" | "working" | "rejected" | "terminal" | "admitted";
3767
3767
  oldOrderId?: string | undefined;
3768
3768
  replacementOrderId?: string | undefined;
3769
3769
  actionTaken: "unspecified" | "AMENDED" | "REPLACED";
@@ -3775,7 +3775,7 @@ declare const GetBatchReplaceStatusResultSchema: v.SchemaWithPipe<readonly [v.Ob
3775
3775
  updatedTs: number;
3776
3776
  updatedTsNs: string;
3777
3777
  itemIndex: number;
3778
- phase: "unspecified" | "terminal" | "working" | "rejected" | "admitted";
3778
+ phase: "unspecified" | "working" | "rejected" | "terminal" | "admitted";
3779
3779
  oldOrderId?: string | undefined;
3780
3780
  replacementOrderId?: string | undefined;
3781
3781
  actionTaken: "unspecified" | "AMENDED" | "REPLACED";
@@ -3793,7 +3793,7 @@ declare const GetBatchReplaceStatusResultSchema: v.SchemaWithPipe<readonly [v.Ob
3793
3793
  updatedTs: number;
3794
3794
  updatedTsNs: string;
3795
3795
  itemIndex: number;
3796
- phase: "unspecified" | "terminal" | "working" | "rejected" | "admitted";
3796
+ phase: "unspecified" | "working" | "rejected" | "terminal" | "admitted";
3797
3797
  oldOrderId?: string | undefined;
3798
3798
  replacementOrderId?: string | undefined;
3799
3799
  actionTaken: "unspecified" | "AMENDED" | "REPLACED";
@@ -3811,7 +3811,7 @@ declare const GetBatchReplaceStatusResultSchema: v.SchemaWithPipe<readonly [v.Ob
3811
3811
  updatedTs: number;
3812
3812
  updatedTsNs: string;
3813
3813
  itemIndex: number;
3814
- phase: "unspecified" | "terminal" | "working" | "rejected" | "admitted";
3814
+ phase: "unspecified" | "working" | "rejected" | "terminal" | "admitted";
3815
3815
  oldOrderId?: string | undefined;
3816
3816
  replacementOrderId?: string | undefined;
3817
3817
  actionTaken: "unspecified" | "AMENDED" | "REPLACED";
@@ -3829,7 +3829,7 @@ declare const GetBatchReplaceStatusResultSchema: v.SchemaWithPipe<readonly [v.Ob
3829
3829
  updatedTs: number;
3830
3830
  updatedTsNs: string;
3831
3831
  itemIndex: number;
3832
- phase: "unspecified" | "terminal" | "working" | "rejected" | "admitted";
3832
+ phase: "unspecified" | "working" | "rejected" | "terminal" | "admitted";
3833
3833
  oldOrderId?: string | undefined;
3834
3834
  replacementOrderId?: string | undefined;
3835
3835
  actionTaken: "unspecified" | "AMENDED" | "REPLACED";
@@ -3851,7 +3851,7 @@ declare const GetBatchReplaceStatusResultSchema: v.SchemaWithPipe<readonly [v.Ob
3851
3851
  updatedTs: number;
3852
3852
  updatedTsNs: string;
3853
3853
  itemIndex: number;
3854
- phase: "unspecified" | "terminal" | "working" | "rejected" | "admitted";
3854
+ phase: "unspecified" | "working" | "rejected" | "terminal" | "admitted";
3855
3855
  oldOrderId?: string | undefined;
3856
3856
  replacementOrderId?: string | undefined;
3857
3857
  actionTaken: "unspecified" | "AMENDED" | "REPLACED";
@@ -365,7 +365,7 @@ declare function createOrderSchema(scales: SdkScales): v.SchemaWithPipe<readonly
365
365
  symbolId: number;
366
366
  clientOrderId: string;
367
367
  status: "unspecified" | "canceled" | "pending" | "pending_cancel" | "working" | "filled" | "rejected" | "partial";
368
- side: "unspecified" | "buy" | "sell";
368
+ side: "buy" | "sell" | "unspecified";
369
369
  orderType: "unspecified" | "limit" | "market";
370
370
  timeInForce: "unspecified" | "GTC" | "IOC" | "FOK" | "GTD";
371
371
  selfTradePreventionMode: "unspecified" | "expire_taker" | "expire_maker" | "expire_both";
@@ -786,7 +786,7 @@ declare function createOrderDetailsSchema(scales: SdkScales): v.ObjectSchema<{
786
786
  symbolId: number;
787
787
  clientOrderId: string;
788
788
  status: "unspecified" | "canceled" | "pending" | "pending_cancel" | "working" | "filled" | "rejected" | "partial";
789
- side: "unspecified" | "buy" | "sell";
789
+ side: "buy" | "sell" | "unspecified";
790
790
  orderType: "unspecified" | "limit" | "market";
791
791
  timeInForce: "unspecified" | "GTC" | "IOC" | "FOK" | "GTD";
792
792
  selfTradePreventionMode: "unspecified" | "expire_taker" | "expire_maker" | "expire_both";
@@ -863,7 +863,7 @@ declare function createOrderDetailsSchema(scales: SdkScales): v.ObjectSchema<{
863
863
  referralShare?: string | undefined;
864
864
  orderId: string;
865
865
  symbolId: number;
866
- sideLabel: "unspecified" | "buy" | "sell";
866
+ sideLabel: "buy" | "sell" | "unspecified";
867
867
  liquidityLabel: "maker" | "taker";
868
868
  feeAsset: "unspecified" | "quote" | "base";
869
869
  qty: string;
@@ -62,7 +62,7 @@ declare class OrdersService {
62
62
  */
63
63
  create(input: NewOrderInput, options?: PolyesterMutationOptions): Promise<CreateOrderResult>;
64
64
  /**
65
- * Places 1–20 spot orders in one best-effort request. Results preserve item order and report admission as accepted or rejected; accepted orders still require lifecycle reconciliation. requestId is the idempotency boundary for the ordered batch and is generated when omitted; supply and reuse it when an ambiguous batch may be retried. The same payload and account-scoped requestId replay the original results and timestamp for 60 seconds from acceptance; a different payload during that window returns CONFLICT_IDEMPOTENCY_KEY_REUSE. Per-item clientOrderId values are optional correlation identifiers and must be unique when supplied.
65
+ * Places 1–20 spot orders in one best-effort request. Results preserve item order and report admission as accepted or rejected; accepted orders still require lifecycle reconciliation. requestId is the idempotency boundary for the ordered batch and is generated when omitted; supply and reuse it when an ambiguous batch may be retried. Reusing the account-scoped requestId with the same payload within 15 minutes returns each decided item's original result and result time and retries items still unresolved, never admitting an item twice; a different payload during that window returns CONFLICT_IDEMPOTENCY_KEY_REUSE. After 15 minutes the ID is free and a repeat can place its orders again, so read the items back instead of repeating an older batch. Per-item clientOrderId values are optional correlation identifiers and must be unique when supplied.
66
66
  */
67
67
  batchCreate(input: BatchCreateOrdersInput, options?: PolyesterMutationOptions): Promise<BatchCreateOrdersResult>;
68
68
  /**
@@ -115,7 +115,7 @@ var OrdersService = class {
115
115
  return parse(createCreateOrderResultSchema(this.#scales, validatedInput.order.symbolId), res);
116
116
  }
117
117
  /**
118
- * Places 1–20 spot orders in one best-effort request. Results preserve item order and report admission as accepted or rejected; accepted orders still require lifecycle reconciliation. requestId is the idempotency boundary for the ordered batch and is generated when omitted; supply and reuse it when an ambiguous batch may be retried. The same payload and account-scoped requestId replay the original results and timestamp for 60 seconds from acceptance; a different payload during that window returns CONFLICT_IDEMPOTENCY_KEY_REUSE. Per-item clientOrderId values are optional correlation identifiers and must be unique when supplied.
118
+ * Places 1–20 spot orders in one best-effort request. Results preserve item order and report admission as accepted or rejected; accepted orders still require lifecycle reconciliation. requestId is the idempotency boundary for the ordered batch and is generated when omitted; supply and reuse it when an ambiguous batch may be retried. Reusing the account-scoped requestId with the same payload within 15 minutes returns each decided item's original result and result time and retries items still unresolved, never admitting an item twice; a different payload during that window returns CONFLICT_IDEMPOTENCY_KEY_REUSE. After 15 minutes the ID is free and a repeat can place its orders again, so read the items back instead of repeating an older batch. Per-item clientOrderId values are optional correlation identifiers and must be unique when supplied.
119
119
  */
120
120
  async batchCreate(input, options) {
121
121
  await this.#scales.ready();
@@ -1 +1 @@
1
- {"version":3,"file":"orders.js","names":["#readClient","ProtoRead.OrdersReadService","#writeClient","ProtoWrite.OrdersService","#realtime","#resolver","#scales","#orderDetailsSchema","#newOrderInputSchema","#modifyOrderInputSchema","#batchCreateOrdersInputSchema"],"sources":["../../../src/services/orders/orders.ts"],"sourcesContent":["import * as ProtoRead from \"../../gen/orders/v1/orders_read_pb.js\";\nimport * as ProtoWrite from \"../../gen/orders/v1/orders_pb.js\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport type * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport { type SubaccountResolver, resolveAccountScopedInput } from \"../subaccount-resolver.js\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport type { PolyesterRealtime } from \"../../realtime/types.js\";\nimport { connectReadyGated } from \"../../realtime/ready-gated-subscription.js\";\nimport type { PrivateOrdersEvent } from \"../../realtime/private-orders.js\";\nimport { deliverBatch } from \"../../shared/subscription-errors.js\";\nimport { formatId, idToBigInt } from \"../../utils/base58-id.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport type { SdkScales } from \"../../shared/decimal-surface.js\";\nimport { toPolyesterError } from \"../../shared/connect-error-mapping.js\";\nimport { loadErrorDetailDecoders } from \"../../shared/error-detail.js\";\nimport { ConfigurationError, PolyesterError } from \"../../shared/errors.js\";\nimport type { AuthApiTransports } from \"../../shared/transports.js\";\nimport { formatConnectError, isResourceNotFoundError } from \"../../utils/errors.js\";\nimport {\n OpenOrdersInputSchema,\n OrderHistoryInputSchema,\n type NewOrderInput,\n createNewOrderInputSchema,\n CancelOrderInputSchema,\n CancelOrderResultSchema,\n type CancelOrderResult,\n CancelAllOrdersInputSchema,\n CancelAllOrdersResponseSchema,\n type CancelAllOrdersResponse,\n type Order,\n GetOrderDetailsInputSchema,\n createCreateOrderResultSchema,\n createPreviewOrderResultSchema,\n type PreviewOrderResult,\n type ModifyOrderInput,\n assertKnownModifyOrderInputKeys,\n createModifyOrderInputSchema,\n ModifyOrderResultSchema,\n type CreateOrderResult,\n type ModifyOrderResult,\n type OrderDetails,\n formatOrder,\n createOrderDetailsSchema,\n CancelAllAfterInputSchema,\n CancelAllAfterResultSchema,\n type CancelAllAfterInput,\n type CancelAllAfterResult,\n BatchCancelOrdersInputSchema,\n BatchCancelOrdersResultSchema,\n type BatchCancelOrdersInput,\n type BatchCancelOrdersResult,\n createBatchCreateOrdersResultSchema,\n type BatchCreateOrdersInput,\n type BatchCreateOrdersResult,\n BatchReplaceOrdersResultSchema,\n type BatchReplaceOrdersInput,\n type BatchReplaceOrdersResult,\n GetBatchReplaceStatusInputSchema,\n GetBatchReplaceStatusResultSchema,\n type GetBatchReplaceStatusInput,\n type GetBatchReplaceStatusResult,\n assertKnownBatchReplaceOrderItemInputKeys,\n createBatchCreateOrdersInputSchema,\n createBatchReplaceOrdersInputSchema,\n} from \"./orders.schemas.js\";\n\nfunction hasKnownOrderSymbol(scales: SdkScales, order: { symbolId: number }): boolean {\n try {\n scales.baseQty(order.symbolId);\n return true;\n } catch {\n return false;\n }\n}\n\nconst MISCLASSIFIED_ORDER_NOT_FOUND_MESSAGE = \"order not found\";\n\nfunction isOrderNotFoundError(error: unknown): boolean {\n const mapped = toPolyesterError(error);\n return (\n isResourceNotFoundError(error) ||\n (mapped instanceof PolyesterError &&\n mapped.detail?.service === \"orders\" &&\n mapped.detail.code === \"NOT_FOUND\") ||\n formatConnectError(error, \"\").toLowerCase() === MISCLASSIFIED_ORDER_NOT_FOUND_MESSAGE\n );\n}\n\nexport interface SubscribeOrdersInput extends BaseSubscribeInput<Order> {\n /** The account's base58 public ID, the root account's or a sub-account's. */\n accountId: string;\n /**\n * The account's full live view: open orders, orders not yet on the book, and\n * recently ended orders. Sent when the subscription starts and whenever the\n * server replaces its state; replace local order state with it. When omitted,\n * each snapshot order goes to `onEvent` instead.\n */\n onSnapshot?: (orders: Order[]) => void;\n /**\n * Orders that left the live view and remain only in history. Not cancellations.\n * Without `onSnapshot`, also the orders a resync snapshot no longer contains.\n */\n onRemoved?: (orderIds: string[]) => void;\n /**\n * `true` while the account's live view is behind; `false` once it caught up.\n * `orderIds`, when set, names the only orders whose rows show an earlier state;\n * the rest of the view is current. A later call replaces the earlier one.\n */\n onStale?: (stale: boolean, orderIds?: string[]) => void;\n}\n\nfunction createMutationRequestId(): string {\n const crypto = globalThis.crypto;\n if (crypto?.randomUUID) return crypto.randomUUID();\n\n if (crypto?.getRandomValues) {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n }\n\n throw new ConfigurationError(\n \"Secure request ID generation requires crypto.randomUUID or crypto.getRandomValues.\",\n );\n}\n\nfunction assertBatchResultCount(operation: string, requested: number, returned: number): void {\n if (requested !== returned) {\n throw new Error(\n `${operation} returned ${returned} results for ${requested} requested items.`,\n );\n }\n}\n\n/**\n * Manages account-scoped spot orders across read, write, and realtime order update surfaces.\n */\nexport class OrdersService {\n #readClient: Client<typeof ProtoRead.OrdersReadService>;\n #writeClient: Client<typeof ProtoWrite.OrdersService>;\n #realtime: PolyesterRealtime;\n #resolver?: SubaccountResolver;\n #scales: SdkScales;\n #orderDetailsSchema: ReturnType<typeof createOrderDetailsSchema>;\n #newOrderInputSchema: ReturnType<typeof createNewOrderInputSchema>;\n #modifyOrderInputSchema: ReturnType<typeof createModifyOrderInputSchema>;\n #batchCreateOrdersInputSchema: ReturnType<typeof createBatchCreateOrdersInputSchema>;\n\n constructor(\n transports: AuthApiTransports,\n realtime: PolyesterRealtime,\n resolver: SubaccountResolver | undefined,\n scales: SdkScales,\n ) {\n this.#readClient = createClient(ProtoRead.OrdersReadService, transports.authApi);\n this.#writeClient = createClient(ProtoWrite.OrdersService, transports.authApi);\n this.#realtime = realtime;\n this.#resolver = resolver;\n this.#scales = scales;\n this.#orderDetailsSchema = createOrderDetailsSchema(scales);\n this.#newOrderInputSchema = createNewOrderInputSchema(scales);\n this.#modifyOrderInputSchema = createModifyOrderInputSchema(scales);\n this.#batchCreateOrdersInputSchema = createBatchCreateOrdersInputSchema(scales);\n }\n\n /**\n * Returns open orders for the resolved root account or subaccount, with optional symbol IDs, trigger ID, side, pagination, and attached-risk inclusion filters. Results are paginated with a server-determined page size: a single call is not the full set of open orders — keep calling with the returned nextPageToken until it is empty.\n */\n async listOpen(\n input: v.InferInput<typeof OpenOrdersInputSchema> = {},\n options?: PolyesterRequestOptions,\n ): Promise<{ orders: Order[]; nextPageToken: string }> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(OpenOrdersInputSchema, resolved);\n const res = await this.#readClient.getOpenOrders(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n return {\n orders: res.orders\n .filter((order) => hasKnownOrderSymbol(this.#scales, order))\n .map((order) => formatOrder(this.#scales, order)),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Returns historical orders for the resolved account scope, supporting symbol IDs, trigger ID, side, status, time range, pagination, and attached-risk filters. A page may hold fewer orders than requested, or none: keep calling with the returned nextPageToken until it is empty.\n */\n async listHistory(\n input: v.InferInput<typeof OrderHistoryInputSchema> = {},\n options?: PolyesterRequestOptions,\n ): Promise<{ orders: Order[]; nextPageToken: string }> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(OrderHistoryInputSchema, resolved);\n const res = await this.#readClient.getOrderHistory(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n return {\n orders: res.orders\n .filter((order) => hasKnownOrderSymbol(this.#scales, order))\n .map((order) => formatOrder(this.#scales, order)),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Evaluates one complete order intent against current market, policy, risk, and balance state without creating an order, reserving funds, or claiming its client order ID.\n */\n async preview(\n input: NewOrderInput,\n options?: PolyesterRequestOptions,\n ): Promise<PreviewOrderResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const request = parse(this.#newOrderInputSchema, resolved);\n const response = await this.#writeClient.previewOrder(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n return parse(\n createPreviewOrderResultSchema(this.#scales, request.order.symbolId),\n response,\n );\n }\n\n /**\n * Places a spot order with an explicit market-IOC, limit-GTC, limit-IOC, or limit-FOK execution policy and optional attached risk controls. clientOrderId is an account-scoped correlation, lookup, and cancellation identifier. Reuse while retained returns CONFLICT_DUPLICATE_CLIENT_ORDER_ID, including after rejection or completion; it does not replay the earlier result. After an ambiguous timeout, reconcile through get using clientOrderId; an immediate lookup miss does not prove admission failed. Without clientOrderId, the outcome may remain unknown.\n */\n async create(\n input: NewOrderInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateOrderResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(this.#newOrderInputSchema, resolved);\n const requestPayload = removeUndefined(validatedInput);\n const res = await this.#writeClient.createOrder(\n requestPayload,\n toConnectCallOptions(options),\n );\n return parse(\n createCreateOrderResultSchema(this.#scales, validatedInput.order.symbolId),\n res,\n );\n }\n\n /**\n * Places 1–20 spot orders in one best-effort request. Results preserve item order and report admission as accepted or rejected; accepted orders still require lifecycle reconciliation. requestId is the idempotency boundary for the ordered batch and is generated when omitted; supply and reuse it when an ambiguous batch may be retried. The same payload and account-scoped requestId replay the original results and timestamp for 60 seconds from acceptance; a different payload during that window returns CONFLICT_IDEMPOTENCY_KEY_REUSE. Per-item clientOrderId values are optional correlation identifiers and must be unique when supplied.\n */\n async batchCreate(\n input: BatchCreateOrdersInput,\n options?: PolyesterMutationOptions,\n ): Promise<BatchCreateOrdersResult> {\n await this.#scales.ready();\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(this.#batchCreateOrdersInputSchema, resolved);\n const response = await this.#writeClient.batchCreateOrders(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n const result = parse(\n createBatchCreateOrdersResultSchema(\n this.#scales,\n request.items.map((item) => item.symbolId),\n ),\n response,\n );\n assertBatchResultCount(\"batchCreate\", input.items.length, result.results.length);\n return result;\n }\n\n /**\n * Requests cancellation of one order in the resolved account scope by order id or client order id, with optional symbol routing. The response acknowledges the cancellation request, not the order's final lifecycle state; reconcile through order reads or realtime before releasing local state. A missing target remains a {@link ResourceNotFoundError}; callers performing desired-state cleanup may treat that error as success when the order could already have filled or left the book.\n */\n async cancel(\n input: v.InferInput<typeof CancelOrderInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<CancelOrderResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n\n const validated = parse(CancelOrderInputSchema, resolved);\n\n const res = await this.#writeClient.cancelOrder(\n {\n key: validated.key,\n symbolId: validated.symbolId,\n subaccountId: validated.subaccountId,\n },\n toConnectCallOptions(options),\n );\n return parse(CancelOrderResultSchema, res);\n }\n\n /**\n * Cancels 1–50 explicit orders in one best-effort request. Results preserve item order and acknowledge cancellation admission rather than final order state. Supply a stable requestId when an ambiguous batch may be retried.\n */\n async batchCancel(\n input: BatchCancelOrdersInput,\n options?: PolyesterMutationOptions,\n ): Promise<BatchCancelOrdersResult> {\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(BatchCancelOrdersInputSchema, resolved);\n const response = await this.#writeClient.batchCancelOrders(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n const result = parse(BatchCancelOrdersResultSchema, response);\n assertBatchResultCount(\"batchCancel\", input.items.length, result.results.length);\n return result;\n }\n\n /**\n * Applies a price, quantity, client id, or attached-risk patch to one open order. The symbol ID routes policy checks and quantity scaling. A requestId is generated when omitted; provide a stable value when retrying the same logical modification.\n */\n async modify(\n input: ModifyOrderInput,\n options?: PolyesterMutationOptions,\n ): Promise<ModifyOrderResult> {\n await this.#scales.ready();\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n assertKnownModifyOrderInputKeys(resolved);\n const validated = parse(this.#modifyOrderInputSchema, resolved);\n const res = await this.#writeClient.modifyOrder(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(ModifyOrderResultSchema, res);\n }\n\n /**\n * Replaces 1–50 same-symbol orders and returns an index-stable durable admission receipt. Reuse requestId only when retrying the same logical batch; use the returned batchRequestId for later status reads. An AMENDED actionTaken is cancel-only with no successor; keep tracking oldOrderId until its terminal state is confirmed.\n */\n async batchReplace(\n input: BatchReplaceOrdersInput,\n options?: PolyesterMutationOptions,\n ): Promise<BatchReplaceOrdersResult> {\n await this.#scales.ready();\n for (const item of input.items) {\n assertKnownBatchReplaceOrderItemInputKeys(item);\n }\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(createBatchReplaceOrdersInputSchema(this.#scales), resolved);\n const response = await this.#writeClient.batchReplaceOrders(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n const result = parse(BatchReplaceOrdersResultSchema, response);\n assertBatchResultCount(\"batchReplace\", input.items.length, result.results.length);\n return result;\n }\n\n /**\n * Reads the durable per-item execution status for a batch replacement receipt. For cancel-only AMENDED items, orderStatus describes oldOrderId and replacementOrderId is undefined.\n */\n async getBatchReplaceStatus(\n input: GetBatchReplaceStatusInput,\n options?: PolyesterRequestOptions,\n ): Promise<GetBatchReplaceStatusResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const request = parse(GetBatchReplaceStatusInputSchema, resolved);\n const response = await this.#readClient.getBatchReplaceStatus(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n return parse(GetBatchReplaceStatusResultSchema, response);\n }\n\n /**\n * Cancels all matching open orders for the resolved account scope, optionally narrowed by up to 100 symbol IDs and side, with dry-run preview. A requestId is generated when omitted; reuse it with the same criteria for retries. Completed results are retained for at least two minutes; use a fresh key for each new cancellation.\n * `canceledOrders` lists up to 200 of the orders whose cancellation was requested, oldest first; `truncated` is true when `totalCanceled` counts more. Read each order's final state from `orders.subscribe` or the order reads.\n * A retry with the same requestId and criteria returns the original counts with `listingStatus: \"not_retained_read_open_orders\"` and an empty `canceledOrders`, which does not mean nothing was canceled; read open orders instead.\n */\n async cancelAll(\n input: v.InferInput<typeof CancelAllOrdersInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<CancelAllOrdersResponse> {\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const validated = parse(CancelAllOrdersInputSchema, resolved);\n const res = await this.#writeClient.cancelAllOrders(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(CancelAllOrdersResponseSchema, res);\n }\n\n /**\n * Arms, refreshes, or disables the account dead-man switch, optionally scoped by symbol ID and side. timeoutSec 0 disables it; 10–120 arms it. An armed switch returns its recorded `effectiveScope`. Generate a new requestId for each deliberate heartbeat, but reuse the same ID when retrying one ambiguous heartbeat.\n */\n async cancelAllAfter(\n input: CancelAllAfterInput,\n options?: PolyesterMutationOptions,\n ): Promise<CancelAllAfterResult> {\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(CancelAllAfterInputSchema, resolved);\n const response = await this.#writeClient.cancelAllAfter(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n return parse(CancelAllAfterResultSchema, response);\n }\n\n /**\n * Fetches one physical order and a bounded page of lineage executions through its generation.\n * Pass nextPageToken as pageToken with the same orderId to continue; deduplicate transfers by txId.\n * Set includeExecutionHistory to false for state-only polling, omitting limit and pageToken.\n * Execution pages are eventually consistent and need not reconcile with cumulative order quantities.\n * `executionsComplete` is true once the trades across every page add up to the filled quantity; while false, read again for the rest.\n * Returns null when the requested order is not found.\n */\n async getDetails(\n input: v.InferInput<typeof GetOrderDetailsInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<OrderDetails | null> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(GetOrderDetailsInputSchema, resolved);\n let res: ProtoRead.GetOrderResponse;\n try {\n res = await this.#readClient.getOrder(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n } catch (error) {\n // Injected transports skip SDK error mapping, so load the detail decoder here.\n await loadErrorDetailDecoders(error);\n if (isOrderNotFoundError(error)) return null;\n throw error;\n }\n if (!res.order) return null;\n return parse(this.#orderDetailsSchema, res);\n }\n\n /**\n * Streams an account's orders over the private WebSocket until the returned unsubscribe\n * function is called. Each changed order arrives complete through `onEvent`; keep the\n * copy with the higher `version`, since equal versions are identical. Gaps, expired\n * tokens, and reconnects resume from the last applied position automatically.\n * Throws ValidationError when `accountId` is not a base58 public ID.\n */\n subscribe(input: SubscribeOrdersInput): () => void {\n idToBigInt(input.accountId, \"accountId\");\n const channel = `private:spot:orders:${input.accountId}`;\n const onError = input.onError;\n const known = (orders: ProtoRead.Order[]) =>\n orders.filter((o) => hasKnownOrderSymbol(this.#scales, o));\n // Order IDs in the live view, so a snapshot can report orders that left it while\n // their removal was not delivered (a resync after an expired cursor).\n const live = new Set<bigint>();\n return connectReadyGated<PrivateOrdersEvent>(\n {\n channel,\n ready: () => this.#scales.ready(),\n onPublication: (event) => {\n if (event.type === \"stale\") {\n input.onStale?.(\n event.stale,\n event.orderIds?.map((id) => formatId(id)),\n );\n return;\n }\n if (event.type === \"snapshot\") {\n const ids = new Set(event.orders.map((o) => o.orderId));\n const removed = [...live].filter((id) => !ids.has(id));\n live.clear();\n for (const id of ids) live.add(id);\n if (input.onSnapshot) {\n input.onSnapshot(\n known(event.orders).map((o) => formatOrder(this.#scales, o)),\n );\n return;\n }\n deliverBatch(\n channel,\n known(event.orders),\n (o) => input.onEvent(formatOrder(this.#scales, o)),\n onError,\n );\n if (removed.length > 0)\n input.onRemoved?.(removed.map((id) => formatId(id)));\n return;\n }\n const { unit } = event;\n for (const o of unit.orders) live.add(o.orderId);\n for (const id of unit.removedOrderIds) live.delete(id);\n deliverBatch(\n channel,\n known(unit.orders),\n (o) => input.onEvent(formatOrder(this.#scales, o)),\n onError,\n );\n if (unit.removedOrderIds.length > 0) {\n input.onRemoved?.(unit.removedOrderIds.map((id) => formatId(id)));\n }\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError,\n },\n (handlers) =>\n this.#realtime.connectPrivateOrders({\n accountId: input.accountId,\n onEvent: handlers.onPublication,\n onConnected: handlers.onConnected,\n onDisconnected: handlers.onDisconnected,\n onError: handlers.onError,\n }),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwEA,SAAS,oBAAoB,QAAmB,OAAsC;CAClF,IAAI;EACA,OAAO,QAAQ,MAAM,QAAQ;EAC7B,OAAO;CACX,QAAQ;EACJ,OAAO;CACX;AACJ;AAEA,MAAM,wCAAwC;AAE9C,SAAS,qBAAqB,OAAyB;CACnD,MAAM,SAAS,iBAAiB,KAAK;CACrC,OACI,wBAAwB,KAAK,KAC5B,kBAAkB,kBACf,OAAO,QAAQ,YAAY,YAC3B,OAAO,OAAO,SAAS,eAC3B,mBAAmB,OAAO,EAAE,CAAC,CAAC,YAAY,MAAM;AAExD;AAyBA,SAAS,0BAAkC;CACvC,MAAM,SAAS,WAAW;CAC1B,IAAI,QAAQ,YAAY,OAAO,OAAO,WAAW;CAEjD,IAAI,QAAQ,iBAAiB;EACzB,MAAM,wBAAQ,IAAI,WAAW,EAAE;EAC/B,OAAO,gBAAgB,KAAK;EAC5B,OAAO,MAAM,KAAK,QAAQ,SAAS,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;CAClF;CAEA,MAAM,IAAI,mBACN,oFACJ;AACJ;AAEA,SAAS,uBAAuB,WAAmB,WAAmB,UAAwB;CAC1F,IAAI,cAAc,UACd,MAAM,IAAI,MACN,GAAG,UAAU,YAAY,SAAS,eAAe,UAAU,kBAC/D;AAER;;;;AAKA,IAAa,gBAAb,MAA2B;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YACI,YACA,UACA,UACA,QACF;EACE,KAAKA,cAAc,aAAaC,mBAA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,MAAM,KAAK,MAAM,IAChB,MAAM,MAAM,QAAQ,YAAY,KAAKA,SAAS,CAAC,CAAC,GACjD,OACJ;IACA,IAAI,KAAK,gBAAgB,SAAS,GAC9B,MAAM,YAAY,KAAK,gBAAgB,KAAK,OAAO,SAAS,EAAE,CAAC,CAAC;GAExE;GACA,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC;EACJ,IACC,aACG,KAAKF,UAAU,qBAAqB;GAChC,WAAW,MAAM;GACjB,SAAS,SAAS;GAClB,aAAa,SAAS;GACtB,gBAAgB,SAAS;GACzB,SAAS,SAAS;EACtB,CAAC,CACT;CACJ;AACJ"}
1
+ {"version":3,"file":"orders.js","names":["#readClient","ProtoRead.OrdersReadService","#writeClient","ProtoWrite.OrdersService","#realtime","#resolver","#scales","#orderDetailsSchema","#newOrderInputSchema","#modifyOrderInputSchema","#batchCreateOrdersInputSchema"],"sources":["../../../src/services/orders/orders.ts"],"sourcesContent":["import * as ProtoRead from \"../../gen/orders/v1/orders_read_pb.js\";\nimport * as ProtoWrite from \"../../gen/orders/v1/orders_pb.js\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport type * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport { type SubaccountResolver, resolveAccountScopedInput } from \"../subaccount-resolver.js\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport type { PolyesterRealtime } from \"../../realtime/types.js\";\nimport { connectReadyGated } from \"../../realtime/ready-gated-subscription.js\";\nimport type { PrivateOrdersEvent } from \"../../realtime/private-orders.js\";\nimport { deliverBatch } from \"../../shared/subscription-errors.js\";\nimport { formatId, idToBigInt } from \"../../utils/base58-id.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport type { SdkScales } from \"../../shared/decimal-surface.js\";\nimport { toPolyesterError } from \"../../shared/connect-error-mapping.js\";\nimport { loadErrorDetailDecoders } from \"../../shared/error-detail.js\";\nimport { ConfigurationError, PolyesterError } from \"../../shared/errors.js\";\nimport type { AuthApiTransports } from \"../../shared/transports.js\";\nimport { formatConnectError, isResourceNotFoundError } from \"../../utils/errors.js\";\nimport {\n OpenOrdersInputSchema,\n OrderHistoryInputSchema,\n type NewOrderInput,\n createNewOrderInputSchema,\n CancelOrderInputSchema,\n CancelOrderResultSchema,\n type CancelOrderResult,\n CancelAllOrdersInputSchema,\n CancelAllOrdersResponseSchema,\n type CancelAllOrdersResponse,\n type Order,\n GetOrderDetailsInputSchema,\n createCreateOrderResultSchema,\n createPreviewOrderResultSchema,\n type PreviewOrderResult,\n type ModifyOrderInput,\n assertKnownModifyOrderInputKeys,\n createModifyOrderInputSchema,\n ModifyOrderResultSchema,\n type CreateOrderResult,\n type ModifyOrderResult,\n type OrderDetails,\n formatOrder,\n createOrderDetailsSchema,\n CancelAllAfterInputSchema,\n CancelAllAfterResultSchema,\n type CancelAllAfterInput,\n type CancelAllAfterResult,\n BatchCancelOrdersInputSchema,\n BatchCancelOrdersResultSchema,\n type BatchCancelOrdersInput,\n type BatchCancelOrdersResult,\n createBatchCreateOrdersResultSchema,\n type BatchCreateOrdersInput,\n type BatchCreateOrdersResult,\n BatchReplaceOrdersResultSchema,\n type BatchReplaceOrdersInput,\n type BatchReplaceOrdersResult,\n GetBatchReplaceStatusInputSchema,\n GetBatchReplaceStatusResultSchema,\n type GetBatchReplaceStatusInput,\n type GetBatchReplaceStatusResult,\n assertKnownBatchReplaceOrderItemInputKeys,\n createBatchCreateOrdersInputSchema,\n createBatchReplaceOrdersInputSchema,\n} from \"./orders.schemas.js\";\n\nfunction hasKnownOrderSymbol(scales: SdkScales, order: { symbolId: number }): boolean {\n try {\n scales.baseQty(order.symbolId);\n return true;\n } catch {\n return false;\n }\n}\n\nconst MISCLASSIFIED_ORDER_NOT_FOUND_MESSAGE = \"order not found\";\n\nfunction isOrderNotFoundError(error: unknown): boolean {\n const mapped = toPolyesterError(error);\n return (\n isResourceNotFoundError(error) ||\n (mapped instanceof PolyesterError &&\n mapped.detail?.service === \"orders\" &&\n mapped.detail.code === \"NOT_FOUND\") ||\n formatConnectError(error, \"\").toLowerCase() === MISCLASSIFIED_ORDER_NOT_FOUND_MESSAGE\n );\n}\n\nexport interface SubscribeOrdersInput extends BaseSubscribeInput<Order> {\n /** The account's base58 public ID, the root account's or a sub-account's. */\n accountId: string;\n /**\n * The account's full live view: open orders, orders not yet on the book, and\n * recently ended orders. Sent when the subscription starts and whenever the\n * server replaces its state; replace local order state with it. When omitted,\n * each snapshot order goes to `onEvent` instead.\n */\n onSnapshot?: (orders: Order[]) => void;\n /**\n * Orders that left the live view and remain only in history. Not cancellations.\n * Without `onSnapshot`, also the orders a resync snapshot no longer contains.\n */\n onRemoved?: (orderIds: string[]) => void;\n /**\n * `true` while the account's live view is behind; `false` once it caught up.\n * `orderIds`, when set, names the only orders whose rows show an earlier state;\n * the rest of the view is current. A later call replaces the earlier one.\n */\n onStale?: (stale: boolean, orderIds?: string[]) => void;\n}\n\nfunction createMutationRequestId(): string {\n const crypto = globalThis.crypto;\n if (crypto?.randomUUID) return crypto.randomUUID();\n\n if (crypto?.getRandomValues) {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n }\n\n throw new ConfigurationError(\n \"Secure request ID generation requires crypto.randomUUID or crypto.getRandomValues.\",\n );\n}\n\nfunction assertBatchResultCount(operation: string, requested: number, returned: number): void {\n if (requested !== returned) {\n throw new Error(\n `${operation} returned ${returned} results for ${requested} requested items.`,\n );\n }\n}\n\n/**\n * Manages account-scoped spot orders across read, write, and realtime order update surfaces.\n */\nexport class OrdersService {\n #readClient: Client<typeof ProtoRead.OrdersReadService>;\n #writeClient: Client<typeof ProtoWrite.OrdersService>;\n #realtime: PolyesterRealtime;\n #resolver?: SubaccountResolver;\n #scales: SdkScales;\n #orderDetailsSchema: ReturnType<typeof createOrderDetailsSchema>;\n #newOrderInputSchema: ReturnType<typeof createNewOrderInputSchema>;\n #modifyOrderInputSchema: ReturnType<typeof createModifyOrderInputSchema>;\n #batchCreateOrdersInputSchema: ReturnType<typeof createBatchCreateOrdersInputSchema>;\n\n constructor(\n transports: AuthApiTransports,\n realtime: PolyesterRealtime,\n resolver: SubaccountResolver | undefined,\n scales: SdkScales,\n ) {\n this.#readClient = createClient(ProtoRead.OrdersReadService, transports.authApi);\n this.#writeClient = createClient(ProtoWrite.OrdersService, transports.authApi);\n this.#realtime = realtime;\n this.#resolver = resolver;\n this.#scales = scales;\n this.#orderDetailsSchema = createOrderDetailsSchema(scales);\n this.#newOrderInputSchema = createNewOrderInputSchema(scales);\n this.#modifyOrderInputSchema = createModifyOrderInputSchema(scales);\n this.#batchCreateOrdersInputSchema = createBatchCreateOrdersInputSchema(scales);\n }\n\n /**\n * Returns open orders for the resolved root account or subaccount, with optional symbol IDs, trigger ID, side, pagination, and attached-risk inclusion filters. Results are paginated with a server-determined page size: a single call is not the full set of open orders — keep calling with the returned nextPageToken until it is empty.\n */\n async listOpen(\n input: v.InferInput<typeof OpenOrdersInputSchema> = {},\n options?: PolyesterRequestOptions,\n ): Promise<{ orders: Order[]; nextPageToken: string }> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(OpenOrdersInputSchema, resolved);\n const res = await this.#readClient.getOpenOrders(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n return {\n orders: res.orders\n .filter((order) => hasKnownOrderSymbol(this.#scales, order))\n .map((order) => formatOrder(this.#scales, order)),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Returns historical orders for the resolved account scope, supporting symbol IDs, trigger ID, side, status, time range, pagination, and attached-risk filters. A page may hold fewer orders than requested, or none: keep calling with the returned nextPageToken until it is empty.\n */\n async listHistory(\n input: v.InferInput<typeof OrderHistoryInputSchema> = {},\n options?: PolyesterRequestOptions,\n ): Promise<{ orders: Order[]; nextPageToken: string }> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(OrderHistoryInputSchema, resolved);\n const res = await this.#readClient.getOrderHistory(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n return {\n orders: res.orders\n .filter((order) => hasKnownOrderSymbol(this.#scales, order))\n .map((order) => formatOrder(this.#scales, order)),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Evaluates one complete order intent against current market, policy, risk, and balance state without creating an order, reserving funds, or claiming its client order ID.\n */\n async preview(\n input: NewOrderInput,\n options?: PolyesterRequestOptions,\n ): Promise<PreviewOrderResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const request = parse(this.#newOrderInputSchema, resolved);\n const response = await this.#writeClient.previewOrder(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n return parse(\n createPreviewOrderResultSchema(this.#scales, request.order.symbolId),\n response,\n );\n }\n\n /**\n * Places a spot order with an explicit market-IOC, limit-GTC, limit-IOC, or limit-FOK execution policy and optional attached risk controls. clientOrderId is an account-scoped correlation, lookup, and cancellation identifier. Reuse while retained returns CONFLICT_DUPLICATE_CLIENT_ORDER_ID, including after rejection or completion; it does not replay the earlier result. After an ambiguous timeout, reconcile through get using clientOrderId; an immediate lookup miss does not prove admission failed. Without clientOrderId, the outcome may remain unknown.\n */\n async create(\n input: NewOrderInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateOrderResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(this.#newOrderInputSchema, resolved);\n const requestPayload = removeUndefined(validatedInput);\n const res = await this.#writeClient.createOrder(\n requestPayload,\n toConnectCallOptions(options),\n );\n return parse(\n createCreateOrderResultSchema(this.#scales, validatedInput.order.symbolId),\n res,\n );\n }\n\n /**\n * Places 1–20 spot orders in one best-effort request. Results preserve item order and report admission as accepted or rejected; accepted orders still require lifecycle reconciliation. requestId is the idempotency boundary for the ordered batch and is generated when omitted; supply and reuse it when an ambiguous batch may be retried. Reusing the account-scoped requestId with the same payload within 15 minutes returns each decided item's original result and result time and retries items still unresolved, never admitting an item twice; a different payload during that window returns CONFLICT_IDEMPOTENCY_KEY_REUSE. After 15 minutes the ID is free and a repeat can place its orders again, so read the items back instead of repeating an older batch. Per-item clientOrderId values are optional correlation identifiers and must be unique when supplied.\n */\n async batchCreate(\n input: BatchCreateOrdersInput,\n options?: PolyesterMutationOptions,\n ): Promise<BatchCreateOrdersResult> {\n await this.#scales.ready();\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(this.#batchCreateOrdersInputSchema, resolved);\n const response = await this.#writeClient.batchCreateOrders(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n const result = parse(\n createBatchCreateOrdersResultSchema(\n this.#scales,\n request.items.map((item) => item.symbolId),\n ),\n response,\n );\n assertBatchResultCount(\"batchCreate\", input.items.length, result.results.length);\n return result;\n }\n\n /**\n * Requests cancellation of one order in the resolved account scope by order id or client order id, with optional symbol routing. The response acknowledges the cancellation request, not the order's final lifecycle state; reconcile through order reads or realtime before releasing local state. A missing target remains a {@link ResourceNotFoundError}; callers performing desired-state cleanup may treat that error as success when the order could already have filled or left the book.\n */\n async cancel(\n input: v.InferInput<typeof CancelOrderInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<CancelOrderResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n\n const validated = parse(CancelOrderInputSchema, resolved);\n\n const res = await this.#writeClient.cancelOrder(\n {\n key: validated.key,\n symbolId: validated.symbolId,\n subaccountId: validated.subaccountId,\n },\n toConnectCallOptions(options),\n );\n return parse(CancelOrderResultSchema, res);\n }\n\n /**\n * Cancels 1–50 explicit orders in one best-effort request. Results preserve item order and acknowledge cancellation admission rather than final order state. Supply a stable requestId when an ambiguous batch may be retried.\n */\n async batchCancel(\n input: BatchCancelOrdersInput,\n options?: PolyesterMutationOptions,\n ): Promise<BatchCancelOrdersResult> {\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(BatchCancelOrdersInputSchema, resolved);\n const response = await this.#writeClient.batchCancelOrders(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n const result = parse(BatchCancelOrdersResultSchema, response);\n assertBatchResultCount(\"batchCancel\", input.items.length, result.results.length);\n return result;\n }\n\n /**\n * Applies a price, quantity, client id, or attached-risk patch to one open order. The symbol ID routes policy checks and quantity scaling. A requestId is generated when omitted; provide a stable value when retrying the same logical modification.\n */\n async modify(\n input: ModifyOrderInput,\n options?: PolyesterMutationOptions,\n ): Promise<ModifyOrderResult> {\n await this.#scales.ready();\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n assertKnownModifyOrderInputKeys(resolved);\n const validated = parse(this.#modifyOrderInputSchema, resolved);\n const res = await this.#writeClient.modifyOrder(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(ModifyOrderResultSchema, res);\n }\n\n /**\n * Replaces 1–50 same-symbol orders and returns an index-stable durable admission receipt. Reuse requestId only when retrying the same logical batch; use the returned batchRequestId for later status reads. An AMENDED actionTaken is cancel-only with no successor; keep tracking oldOrderId until its terminal state is confirmed.\n */\n async batchReplace(\n input: BatchReplaceOrdersInput,\n options?: PolyesterMutationOptions,\n ): Promise<BatchReplaceOrdersResult> {\n await this.#scales.ready();\n for (const item of input.items) {\n assertKnownBatchReplaceOrderItemInputKeys(item);\n }\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(createBatchReplaceOrdersInputSchema(this.#scales), resolved);\n const response = await this.#writeClient.batchReplaceOrders(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n const result = parse(BatchReplaceOrdersResultSchema, response);\n assertBatchResultCount(\"batchReplace\", input.items.length, result.results.length);\n return result;\n }\n\n /**\n * Reads the durable per-item execution status for a batch replacement receipt. For cancel-only AMENDED items, orderStatus describes oldOrderId and replacementOrderId is undefined.\n */\n async getBatchReplaceStatus(\n input: GetBatchReplaceStatusInput,\n options?: PolyesterRequestOptions,\n ): Promise<GetBatchReplaceStatusResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const request = parse(GetBatchReplaceStatusInputSchema, resolved);\n const response = await this.#readClient.getBatchReplaceStatus(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n return parse(GetBatchReplaceStatusResultSchema, response);\n }\n\n /**\n * Cancels all matching open orders for the resolved account scope, optionally narrowed by up to 100 symbol IDs and side, with dry-run preview. A requestId is generated when omitted; reuse it with the same criteria for retries. Completed results are retained for at least two minutes; use a fresh key for each new cancellation.\n * `canceledOrders` lists up to 200 of the orders whose cancellation was requested, oldest first; `truncated` is true when `totalCanceled` counts more. Read each order's final state from `orders.subscribe` or the order reads.\n * A retry with the same requestId and criteria returns the original counts with `listingStatus: \"not_retained_read_open_orders\"` and an empty `canceledOrders`, which does not mean nothing was canceled; read open orders instead.\n */\n async cancelAll(\n input: v.InferInput<typeof CancelAllOrdersInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<CancelAllOrdersResponse> {\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const validated = parse(CancelAllOrdersInputSchema, resolved);\n const res = await this.#writeClient.cancelAllOrders(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(CancelAllOrdersResponseSchema, res);\n }\n\n /**\n * Arms, refreshes, or disables the account dead-man switch, optionally scoped by symbol ID and side. timeoutSec 0 disables it; 10–120 arms it. An armed switch returns its recorded `effectiveScope`. Generate a new requestId for each deliberate heartbeat, but reuse the same ID when retrying one ambiguous heartbeat.\n */\n async cancelAllAfter(\n input: CancelAllAfterInput,\n options?: PolyesterMutationOptions,\n ): Promise<CancelAllAfterResult> {\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(CancelAllAfterInputSchema, resolved);\n const response = await this.#writeClient.cancelAllAfter(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n return parse(CancelAllAfterResultSchema, response);\n }\n\n /**\n * Fetches one physical order and a bounded page of lineage executions through its generation.\n * Pass nextPageToken as pageToken with the same orderId to continue; deduplicate transfers by txId.\n * Set includeExecutionHistory to false for state-only polling, omitting limit and pageToken.\n * Execution pages are eventually consistent and need not reconcile with cumulative order quantities.\n * `executionsComplete` is true once the trades across every page add up to the filled quantity; while false, read again for the rest.\n * Returns null when the requested order is not found.\n */\n async getDetails(\n input: v.InferInput<typeof GetOrderDetailsInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<OrderDetails | null> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(GetOrderDetailsInputSchema, resolved);\n let res: ProtoRead.GetOrderResponse;\n try {\n res = await this.#readClient.getOrder(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n } catch (error) {\n // Injected transports skip SDK error mapping, so load the detail decoder here.\n await loadErrorDetailDecoders(error);\n if (isOrderNotFoundError(error)) return null;\n throw error;\n }\n if (!res.order) return null;\n return parse(this.#orderDetailsSchema, res);\n }\n\n /**\n * Streams an account's orders over the private WebSocket until the returned unsubscribe\n * function is called. Each changed order arrives complete through `onEvent`; keep the\n * copy with the higher `version`, since equal versions are identical. Gaps, expired\n * tokens, and reconnects resume from the last applied position automatically.\n * Throws ValidationError when `accountId` is not a base58 public ID.\n */\n subscribe(input: SubscribeOrdersInput): () => void {\n idToBigInt(input.accountId, \"accountId\");\n const channel = `private:spot:orders:${input.accountId}`;\n const onError = input.onError;\n const known = (orders: ProtoRead.Order[]) =>\n orders.filter((o) => hasKnownOrderSymbol(this.#scales, o));\n // Order IDs in the live view, so a snapshot can report orders that left it while\n // their removal was not delivered (a resync after an expired cursor).\n const live = new Set<bigint>();\n return connectReadyGated<PrivateOrdersEvent>(\n {\n channel,\n ready: () => this.#scales.ready(),\n onPublication: (event) => {\n if (event.type === \"stale\") {\n input.onStale?.(\n event.stale,\n event.orderIds?.map((id) => formatId(id)),\n );\n return;\n }\n if (event.type === \"snapshot\") {\n const ids = new Set(event.orders.map((o) => o.orderId));\n const removed = [...live].filter((id) => !ids.has(id));\n live.clear();\n for (const id of ids) live.add(id);\n if (input.onSnapshot) {\n input.onSnapshot(\n known(event.orders).map((o) => formatOrder(this.#scales, o)),\n );\n return;\n }\n deliverBatch(\n channel,\n known(event.orders),\n (o) => input.onEvent(formatOrder(this.#scales, o)),\n onError,\n );\n if (removed.length > 0)\n input.onRemoved?.(removed.map((id) => formatId(id)));\n return;\n }\n const { unit } = event;\n for (const o of unit.orders) live.add(o.orderId);\n for (const id of unit.removedOrderIds) live.delete(id);\n deliverBatch(\n channel,\n known(unit.orders),\n (o) => input.onEvent(formatOrder(this.#scales, o)),\n onError,\n );\n if (unit.removedOrderIds.length > 0) {\n input.onRemoved?.(unit.removedOrderIds.map((id) => formatId(id)));\n }\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError,\n },\n (handlers) =>\n this.#realtime.connectPrivateOrders({\n accountId: input.accountId,\n onEvent: handlers.onPublication,\n onConnected: handlers.onConnected,\n onDisconnected: handlers.onDisconnected,\n onError: handlers.onError,\n }),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwEA,SAAS,oBAAoB,QAAmB,OAAsC;CAClF,IAAI;EACA,OAAO,QAAQ,MAAM,QAAQ;EAC7B,OAAO;CACX,QAAQ;EACJ,OAAO;CACX;AACJ;AAEA,MAAM,wCAAwC;AAE9C,SAAS,qBAAqB,OAAyB;CACnD,MAAM,SAAS,iBAAiB,KAAK;CACrC,OACI,wBAAwB,KAAK,KAC5B,kBAAkB,kBACf,OAAO,QAAQ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MAAM,IAAI,IAAI,MAAM,OAAO,KAAK,MAAM,EAAE,OAAO,CAAC;KACtD,MAAM,UAAU,CAAC,GAAG,IAAI,CAAC,CAAC,QAAQ,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC;KACrD,KAAK,MAAM;KACX,KAAK,MAAM,MAAM,KAAK,KAAK,IAAI,EAAE;KACjC,IAAI,MAAM,YAAY;MAClB,MAAM,WACF,MAAM,MAAM,MAAM,CAAC,CAAC,KAAK,MAAM,YAAY,KAAKA,SAAS,CAAC,CAAC,CAC/D;MACA;KACJ;KACA,aACI,SACA,MAAM,MAAM,MAAM,IACjB,MAAM,MAAM,QAAQ,YAAY,KAAKA,SAAS,CAAC,CAAC,GACjD,OACJ;KACA,IAAI,QAAQ,SAAS,GACjB,MAAM,YAAY,QAAQ,KAAK,OAAO,SAAS,EAAE,CAAC,CAAC;KACvD;IACJ;IACA,MAAM,EAAE,SAAS;IACjB,KAAK,MAAM,KAAK,KAAK,QAAQ,KAAK,IAAI,EAAE,OAAO;IAC/C,KAAK,MAAM,MAAM,KAAK,iBAAiB,KAAK,OAAO,EAAE;IACrD,aACI,SACA,MAAM,KAAK,MAAM,IAChB,MAAM,MAAM,QAAQ,YAAY,KAAKA,SAAS,CAAC,CAAC,GACjD,OACJ;IACA,IAAI,KAAK,gBAAgB,SAAS,GAC9B,MAAM,YAAY,KAAK,gBAAgB,KAAK,OAAO,SAAS,EAAE,CAAC,CAAC;GAExE;GACA,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC;EACJ,IACC,aACG,KAAKF,UAAU,qBAAqB;GAChC,WAAW,MAAM;GACjB,SAAS,SAAS;GAClB,aAAa,SAAS;GACtB,gBAAgB,SAAS;GACzB,SAAS,SAAS;EACtB,CAAC,CACT;CACJ;AACJ"}
@@ -10,7 +10,7 @@ declare class RewardsService {
10
10
  #private;
11
11
  constructor(transports: AuthApiTransports);
12
12
  /**
13
- * Returns published awards newest first. `limit` is 0 through 100 (0 or omitted uses 50); pass the previous `nextPageToken` as `pageToken` to continue. An empty `nextPageToken` means no more awards.
13
+ * Returns published awards newest first. `limit` is 0 through 100 (0 or omitted uses 50); pass the previous `nextPageToken` as `pageToken` to continue. An empty `nextPageToken` means no more awards. When `awardsMayChange` is false, polling cannot surface new awards or changes until a new campaign is created.
14
14
  */
15
15
  listAwards(input?: ListRewardAwardsInput, options?: PolyesterRequestOptions): Promise<ListRewardAwardsResult>;
16
16
  /**
@@ -14,7 +14,7 @@ var RewardsService = class {
14
14
  this.#client = createClient(RewardCampaignService, transports.authApi);
15
15
  }
16
16
  /**
17
- * Returns published awards newest first. `limit` is 0 through 100 (0 or omitted uses 50); pass the previous `nextPageToken` as `pageToken` to continue. An empty `nextPageToken` means no more awards.
17
+ * Returns published awards newest first. `limit` is 0 through 100 (0 or omitted uses 50); pass the previous `nextPageToken` as `pageToken` to continue. An empty `nextPageToken` means no more awards. When `awardsMayChange` is false, polling cannot surface new awards or changes until a new campaign is created.
18
18
  */
19
19
  async listAwards(input = {}, options) {
20
20
  const request = parse(ListRewardAwardsInputSchema, input);
@@ -1 +1 @@
1
- {"version":3,"file":"rewards.js","names":["#client","Proto.RewardCampaignService"],"sources":["../../../src/services/rewards/rewards.ts"],"sourcesContent":["import { createClient, type Client } from \"@connectrpc/connect\";\nimport * as Proto from \"../../gen/rewards/v1/rewards_pb.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport type { AuthApiTransports } from \"../../shared/transports.js\";\nimport { parse } from \"../../shared/validation.js\";\nimport {\n ListRewardAwardsInputSchema,\n ListRewardAwardsResultSchema,\n type ListRewardAwardsInput,\n type ListRewardAwardsResult,\n SetRewardDestinationInputSchema,\n SetRewardDestinationResultSchema,\n type SetRewardDestinationInput,\n type SetRewardDestinationResult,\n} from \"./rewards.schemas.js\";\n\n/**\n * Reads published reward campaign awards for the authenticated root account and records payout destinations.\n * The server accepts session JWTs for this service; API keys are not accepted.\n */\nexport class RewardsService {\n #client: Client<typeof Proto.RewardCampaignService>;\n\n constructor(transports: AuthApiTransports) {\n this.#client = createClient(Proto.RewardCampaignService, transports.authApi);\n }\n\n /**\n * Returns published awards newest first. `limit` is 0 through 100 (0 or omitted uses 50); pass the previous `nextPageToken` as `pageToken` to continue. An empty `nextPageToken` means no more awards.\n */\n async listAwards(\n input: ListRewardAwardsInput = {},\n options?: PolyesterRequestOptions,\n ): Promise<ListRewardAwardsResult> {\n const request = parse(ListRewardAwardsInputSchema, input);\n const response = await this.#client.listMyRewardAwards(\n request,\n toConnectCallOptions(options),\n );\n return parse(ListRewardAwardsResultSchema, response);\n }\n\n /**\n * Records a write-once payout destination for an award, interpreted in the award's `network`. Pass the award's `fulfillmentRevision` as `expectedRevision` and reuse the same `requestId` when retrying. Requires a fresh step-up proof via `options.stepUpToken`. This does not execute a transfer or mark the award delivered.\n */\n async setDestination(\n input: SetRewardDestinationInput,\n options?: PolyesterMutationOptions,\n ): Promise<SetRewardDestinationResult> {\n const request = parse(SetRewardDestinationInputSchema, input);\n const response = await this.#client.setMyRewardDestination(\n request,\n toConnectCallOptions(options),\n );\n return parse(SetRewardDestinationResultSchema, response);\n }\n}\n"],"mappings":";;;;;;;;;;AAwBA,IAAa,iBAAb,MAA4B;CACxB;CAEA,YAAY,YAA+B;EACvC,KAAKA,UAAU,aAAaC,uBAA6B,WAAW,OAAO;CAC/E;;;;CAKA,MAAM,WACF,QAA+B,CAAC,GAChC,SAC+B;EAC/B,MAAM,UAAU,MAAM,6BAA6B,KAAK;EACxD,MAAM,WAAW,MAAM,KAAKD,QAAQ,mBAChC,SACA,qBAAqB,OAAO,CAChC;EACA,OAAO,MAAM,8BAA8B,QAAQ;CACvD;;;;CAKA,MAAM,eACF,OACA,SACmC;EACnC,MAAM,UAAU,MAAM,iCAAiC,KAAK;EAC5D,MAAM,WAAW,MAAM,KAAKA,QAAQ,uBAChC,SACA,qBAAqB,OAAO,CAChC;EACA,OAAO,MAAM,kCAAkC,QAAQ;CAC3D;AACJ"}
1
+ {"version":3,"file":"rewards.js","names":["#client","Proto.RewardCampaignService"],"sources":["../../../src/services/rewards/rewards.ts"],"sourcesContent":["import { createClient, type Client } from \"@connectrpc/connect\";\nimport * as Proto from \"../../gen/rewards/v1/rewards_pb.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport type { AuthApiTransports } from \"../../shared/transports.js\";\nimport { parse } from \"../../shared/validation.js\";\nimport {\n ListRewardAwardsInputSchema,\n ListRewardAwardsResultSchema,\n type ListRewardAwardsInput,\n type ListRewardAwardsResult,\n SetRewardDestinationInputSchema,\n SetRewardDestinationResultSchema,\n type SetRewardDestinationInput,\n type SetRewardDestinationResult,\n} from \"./rewards.schemas.js\";\n\n/**\n * Reads published reward campaign awards for the authenticated root account and records payout destinations.\n * The server accepts session JWTs for this service; API keys are not accepted.\n */\nexport class RewardsService {\n #client: Client<typeof Proto.RewardCampaignService>;\n\n constructor(transports: AuthApiTransports) {\n this.#client = createClient(Proto.RewardCampaignService, transports.authApi);\n }\n\n /**\n * Returns published awards newest first. `limit` is 0 through 100 (0 or omitted uses 50); pass the previous `nextPageToken` as `pageToken` to continue. An empty `nextPageToken` means no more awards. When `awardsMayChange` is false, polling cannot surface new awards or changes until a new campaign is created.\n */\n async listAwards(\n input: ListRewardAwardsInput = {},\n options?: PolyesterRequestOptions,\n ): Promise<ListRewardAwardsResult> {\n const request = parse(ListRewardAwardsInputSchema, input);\n const response = await this.#client.listMyRewardAwards(\n request,\n toConnectCallOptions(options),\n );\n return parse(ListRewardAwardsResultSchema, response);\n }\n\n /**\n * Records a write-once payout destination for an award, interpreted in the award's `network`. Pass the award's `fulfillmentRevision` as `expectedRevision` and reuse the same `requestId` when retrying. Requires a fresh step-up proof via `options.stepUpToken`. This does not execute a transfer or mark the award delivered.\n */\n async setDestination(\n input: SetRewardDestinationInput,\n options?: PolyesterMutationOptions,\n ): Promise<SetRewardDestinationResult> {\n const request = parse(SetRewardDestinationInputSchema, input);\n const response = await this.#client.setMyRewardDestination(\n request,\n toConnectCallOptions(options),\n );\n return parse(SetRewardDestinationResultSchema, response);\n }\n}\n"],"mappings":";;;;;;;;;;AAwBA,IAAa,iBAAb,MAA4B;CACxB;CAEA,YAAY,YAA+B;EACvC,KAAKA,UAAU,aAAaC,uBAA6B,WAAW,OAAO;CAC/E;;;;CAKA,MAAM,WACF,QAA+B,CAAC,GAChC,SAC+B;EAC/B,MAAM,UAAU,MAAM,6BAA6B,KAAK;EACxD,MAAM,WAAW,MAAM,KAAKD,QAAQ,mBAChC,SACA,qBAAqB,OAAO,CAChC;EACA,OAAO,MAAM,8BAA8B,QAAQ;CACvD;;;;CAKA,MAAM,eACF,OACA,SACmC;EACnC,MAAM,UAAU,MAAM,iCAAiC,KAAK;EAC5D,MAAM,WAAW,MAAM,KAAKA,QAAQ,uBAChC,SACA,qBAAqB,OAAO,CAChC;EACA,OAAO,MAAM,kCAAkC,QAAQ;CAC3D;AACJ"}
@@ -55,6 +55,13 @@ declare const ListRewardAwardsResultSchema: v.ObjectSchema<{
55
55
  readonly transactionId: v.StringSchema<undefined>;
56
56
  }, undefined>, undefined>, readonly []>;
57
57
  readonly nextPageToken: v.StringSchema<undefined>;
58
+ /**
59
+ * True while a campaign can still publish awards or one of this account's awards is awaiting
60
+ * a destination, ready for payout, or failed and retryable. When false, polling cannot return
61
+ * new awards or award changes until a new campaign is created, so check again on the next
62
+ * page load or focus instead.
63
+ */
64
+ readonly awardsMayChange: v.BooleanSchema<undefined>;
58
65
  }, undefined>;
59
66
  type ListRewardAwardsResult = v.InferOutput<typeof ListRewardAwardsResultSchema>;
60
67
  declare const SetRewardDestinationResultSchema: v.ObjectSchema<{
@@ -1 +1 @@
1
- {"version":3,"file":"rewards.schemas.d.ts","names":[],"sources":["../../../src/services/rewards/rewards.schemas.ts"],"mappings":";;cASa,6BAA2B,EAAA;;;;KAK5B,wBAAwB,EAAE,kBAAkB;cAE3C,iCAA+B,EAAA;;;;;;KAOhC,4BAA4B,EAAE,kBAAkB;cAE/C,mBAAiB,EAAA;;;;;;;;;;;;;;;;;;;;KAelB,cAAc,EAAE,mBAAmB;cAElC,8BAA4B,EAAA;;;;;;;;;;;;;;;;;;;;;;;KAK7B,yBAAyB,EAAE,mBAAmB;cAE7C,kCAAgC,EAAA;;;;;;;;;;;;;;;;;;;;;;KAIjC,6BAA6B,EAAE,mBAAmB"}
1
+ {"version":3,"file":"rewards.schemas.d.ts","names":[],"sources":["../../../src/services/rewards/rewards.schemas.ts"],"mappings":";;cASa,6BAA2B,EAAA;;;;KAK5B,wBAAwB,EAAE,kBAAkB;cAE3C,iCAA+B,EAAA;;;;;;KAOhC,4BAA4B,EAAE,kBAAkB;cAE/C,mBAAiB,EAAA;;;;;;;;;;;;;;;;;;;;KAelB,cAAc,EAAE,mBAAmB;cAElC,8BAA4B,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAY7B,yBAAyB,EAAE,mBAAmB;cAE7C,kCAAgC,EAAA;;;;;;;;;;;;;;;;;;;;;;KAIjC,6BAA6B,EAAE,mBAAmB"}
@@ -29,7 +29,14 @@ const RewardAwardSchema = v.object({
29
29
  });
30
30
  const ListRewardAwardsResultSchema = v.object({
31
31
  awards: v.optional(v.array(RewardAwardSchema), []),
32
- nextPageToken: v.string()
32
+ nextPageToken: v.string(),
33
+ /**
34
+ * True while a campaign can still publish awards or one of this account's awards is awaiting
35
+ * a destination, ready for payout, or failed and retryable. When false, polling cannot return
36
+ * new awards or award changes until a new campaign is created, so check again on the next
37
+ * page load or focus instead.
38
+ */
39
+ awardsMayChange: v.boolean()
33
40
  });
34
41
  const SetRewardDestinationResultSchema = v.object({ award: RewardAwardSchema });
35
42
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"rewards.schemas.js","names":[],"sources":["../../../src/services/rewards/rewards.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { enumLabelSchema } from \"../../shared/proto-enum-codec.js\";\nimport {\n BigIntStringSchema,\n OptionalTimestampMsSchema,\n positiveBigintStringInputSchema,\n} from \"../../shared/schemas.js\";\nimport { RewardFulfillmentMethodCodec, RewardFulfillmentStateCodec } from \"./rewards.codecs.js\";\n\nexport const ListRewardAwardsInputSchema = v.strictObject({\n limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(100))),\n pageToken: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(256)), \"\"),\n});\n\nexport type ListRewardAwardsInput = v.InferInput<typeof ListRewardAwardsInputSchema>;\n\nexport const SetRewardDestinationInputSchema = v.strictObject({\n awardId: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(128)),\n destinationAddress: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(512)),\n expectedRevision: positiveBigintStringInputSchema(\"expectedRevision\"),\n requestId: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(128)),\n});\n\nexport type SetRewardDestinationInput = v.InferInput<typeof SetRewardDestinationInputSchema>;\n\nexport const RewardAwardSchema = v.object({\n awardId: v.string(),\n campaignId: v.string(),\n campaignName: v.string(),\n assetId: v.number(),\n amountBaseUnits: v.string(),\n fulfillmentMethod: enumLabelSchema(RewardFulfillmentMethodCodec.protoToOutput),\n fulfillmentState: enumLabelSchema(RewardFulfillmentStateCodec.protoToOutput),\n publishedAt: OptionalTimestampMsSchema,\n network: v.string(),\n fulfillmentRevision: BigIntStringSchema,\n destinationAddress: v.string(),\n transactionId: v.string(),\n});\n\nexport type RewardAward = v.InferOutput<typeof RewardAwardSchema>;\n\nexport const ListRewardAwardsResultSchema = v.object({\n awards: v.optional(v.array(RewardAwardSchema), []),\n nextPageToken: v.string(),\n});\n\nexport type ListRewardAwardsResult = v.InferOutput<typeof ListRewardAwardsResultSchema>;\n\nexport const SetRewardDestinationResultSchema = v.object({\n award: RewardAwardSchema,\n});\n\nexport type SetRewardDestinationResult = v.InferOutput<typeof S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rD,OAAO,kBACX,CAAC"}
1
+ {"version":3,"file":"rewards.schemas.js","names":[],"sources":["../../../src/services/rewards/rewards.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { enumLabelSchema } from \"../../shared/proto-enum-codec.js\";\nimport {\n BigIntStringSchema,\n OptionalTimestampMsSchema,\n positiveBigintStringInputSchema,\n} from \"../../shared/schemas.js\";\nimport { RewardFulfillmentMethodCodec, RewardFulfillmentStateCodec } from \"./rewards.codecs.js\";\n\nexport const ListRewardAwardsInputSchema = v.strictObject({\n limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(100))),\n pageToken: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(256)), \"\"),\n});\n\nexport type ListRewardAwardsInput = v.InferInput<typeof ListRewardAwardsInputSchema>;\n\nexport const SetRewardDestinationInputSchema = v.strictObject({\n awardId: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(128)),\n destinationAddress: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(512)),\n expectedRevision: positiveBigintStringInputSchema(\"expectedRevision\"),\n requestId: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(128)),\n});\n\nexport type SetRewardDestinationInput = v.InferInput<typeof SetRewardDestinationInputSchema>;\n\nexport const RewardAwardSchema = v.object({\n awardId: v.string(),\n campaignId: v.string(),\n campaignName: v.string(),\n assetId: v.number(),\n amountBaseUnits: v.string(),\n fulfillmentMethod: enumLabelSchema(RewardFulfillmentMethodCodec.protoToOutput),\n fulfillmentState: enumLabelSchema(RewardFulfillmentStateCodec.protoToOutput),\n publishedAt: OptionalTimestampMsSchema,\n network: v.string(),\n fulfillmentRevision: BigIntStringSchema,\n destinationAddress: v.string(),\n transactionId: v.string(),\n});\n\nexport type RewardAward = v.InferOutput<typeof RewardAwardSchema>;\n\nexport const ListRewardAwardsResultSchema = v.object({\n awards: v.optional(v.array(RewardAwardSchema), []),\n nextPageToken: v.string(),\n /**\n * True while a campaign can still publish awards or one of this account's awards is awaiting\n * a destination, ready for payout, or failed and retryable. When false, polling cannot return\n * new awards or award changes until a new campaign is created, so check again on the next\n * page load or focus instead.\n */\n awardsMayChange: v.boolean(),\n});\n\nexport type ListRewardAwardsResult = v.InferOutput<typeof ListRewardAwardsResultSchema>;\n\nexport const SetRewardDestinationResultSchema = v.object({\n award: RewardAwardSchema,\n});\n\nexport type SetRewardDestinationResult = v.InferOutput<typeof SetRewardDestinationResultSchema>;\n"],"mappings":";;;;;AASA,MAAa,8BAA8B,EAAE,aAAa;CACtD,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,QAAQ,GAAG,EAAE,SAAS,CAAC,GAAG,EAAE,SAAS,GAAG,CAAC,CAAC;CACjF,WAAW,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,KAAK,GAAG,EAAE,UAAU,GAAG,CAAC,GAAG,EAAE;AAC5E,CAAC;AAID,MAAa,kCAAkC,EAAE,aAAa;CAC1D,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,KAAK,GAAG,EAAE,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,CAAC;CACtE,oBAAoB,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,KAAK,GAAG,EAAE,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,CAAC;CACjF,kBAAkB,gCAAgC,kBAAkB;CACpE,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,KAAK,GAAG,EAAE,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,CAAC;AAC5E,CAAC;AAID,MAAa,oBAAoB,EAAE,OAAO;CACtC,SAAS,EAAE,OAAO;CAClB,YAAY,EAAE,OAAO;CACrB,cAAc,EAAE,OAAO;CACvB,SAAS,EAAE,OAAO;CAClB,iBAAiB,EAAE,OAAO;CAC1B,mBAAmB,gBAAgB,6BAA6B,aAAa;CAC7E,kBAAkB,gBAAgB,4BAA4B,aAAa;CAC3E,aAAa;CACb,SAAS,EAAE,OAAO;CAClB,qBAAqB;CACrB,oBAAoB,EAAE,OAAO;CAC7B,eAAe,EAAE,OAAO;AAC5B,CAAC;AAID,MAAa,+BAA+B,EAAE,OAAO;CACjD,QAAQ,EAAE,SAAS,EAAE,MAAM,iBAAiB,GAAG,CAAC,CAAC;CACjD,eAAe,EAAE,OAAO;;;;;;;CAOxB,iBAAiB,EAAE,QAAQ;AAC/B,CAAC;AAID,MAAa,mCAAmC,EAAE,OAAO,EACrD,OAAO,kBACX,CAAC"}
@@ -108,7 +108,7 @@ declare class SubaccountsService {
108
108
  nextPageToken: string;
109
109
  }>;
110
110
  /**
111
- * Subscribes to private subaccount updates for an account and emits normalized subaccount records.
111
+ * Subscribes to private subaccount updates for an account and emits normalized subaccount records. A record with `removed: true` means the caller lost access to that subaccount; remove it locally. Losing access also ends the caller's subscriptions to that subaccount's channels.
112
112
  */
113
113
  subscribe(input: SubscribeSubaccountsInput): () => void;
114
114
  /**
@@ -182,7 +182,7 @@ var SubaccountsService = class {
182
182
  };
183
183
  }
184
184
  /**
185
- * Subscribes to private subaccount updates for an account and emits normalized subaccount records.
185
+ * Subscribes to private subaccount updates for an account and emits normalized subaccount records. A record with `removed: true` means the caller lost access to that subaccount; remove it locally. Losing access also ends the caller's subscriptions to that subaccount's channels.
186
186
  */
187
187
  subscribe(input) {
188
188
  const channel = `private:auth:subaccounts:${input.accountId}:proto`;