@polyester/sdk 0.36.0-devnet-20261112202000 → 0.36.0-devnet-20261113022813

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 (244) hide show
  1. package/CHANGELOG.md +21 -1
  2. package/dist/browser-core.js +1 -1
  3. package/dist/gen/ai/v1/assistant_pb.d.ts +212 -10
  4. package/dist/gen/ai/v1/assistant_pb.d.ts.map +1 -1
  5. package/dist/gen/ai/v1/assistant_pb.js +164 -74
  6. package/dist/gen/ai/v1/assistant_pb.js.map +1 -1
  7. package/dist/gen/alerts/v1/price_alerts_pb.d.ts +1 -1
  8. package/dist/gen/auth/v1/address_book_pb.d.ts +1 -1
  9. package/dist/gen/auth/v1/api_keys_pb.d.ts +63 -6
  10. package/dist/gen/auth/v1/api_keys_pb.d.ts.map +1 -1
  11. package/dist/gen/auth/v1/api_keys_pb.js +50 -2
  12. package/dist/gen/auth/v1/api_keys_pb.js.map +1 -1
  13. package/dist/gen/auth/v1/auth_pb.d.ts +1 -1
  14. package/dist/gen/auth/v1/mfa_pb.d.ts +1 -1
  15. package/dist/gen/auth/v1/policies_pb.d.ts +1 -1
  16. package/dist/gen/auth/v1/profile_pb.d.ts +1 -1
  17. package/dist/gen/auth/v1/resolve_pb.d.ts +1 -1
  18. package/dist/gen/auth/v1/social_verification_pb.d.ts +1 -1
  19. package/dist/gen/auth/v1/subaccounts_pb.d.ts +1 -1
  20. package/dist/gen/auth/v1/subaccounts_pb.js +1 -1
  21. package/dist/gen/chain/analytics/v1/analytics_read_pb.d.ts +1 -1
  22. package/dist/gen/chain/deposit/v1/deposit_pb.d.ts +1 -1
  23. package/dist/gen/chain/guard/v1/guard_signer_pb.d.ts +1 -1
  24. package/dist/gen/chain/lifecycle/v1/lifecycle_read_pb.d.ts +11 -3
  25. package/dist/gen/chain/lifecycle/v1/lifecycle_read_pb.d.ts.map +1 -1
  26. package/dist/gen/chain/lifecycle/v1/lifecycle_read_pb.js.map +1 -1
  27. package/dist/gen/chain/lifecycle/v1/types_pb.d.ts +11 -6
  28. package/dist/gen/chain/lifecycle/v1/types_pb.d.ts.map +1 -1
  29. package/dist/gen/chain/lifecycle/v1/types_pb.js +10 -5
  30. package/dist/gen/chain/lifecycle/v1/types_pb.js.map +1 -1
  31. package/dist/gen/chain/withdraw/v1/auto_withdraw_pb.d.ts +7 -2
  32. package/dist/gen/chain/withdraw/v1/auto_withdraw_pb.d.ts.map +1 -1
  33. package/dist/gen/chain/withdraw/v1/auto_withdraw_pb.js.map +1 -1
  34. package/dist/gen/chain/withdraw/v1/withdraw_pb.d.ts +1 -1
  35. package/dist/gen/chain/zipper/v1/reason_pb.d.ts +7 -3
  36. package/dist/gen/chain/zipper/v1/reason_pb.d.ts.map +1 -1
  37. package/dist/gen/chain/zipper/v1/reason_pb.js.map +1 -1
  38. package/dist/gen/chain/zipper/v1/zipper_pb.d.ts +1 -1
  39. package/dist/gen/changelog/v1/changelog_pb.d.ts +483 -3
  40. package/dist/gen/changelog/v1/changelog_pb.d.ts.map +1 -1
  41. package/dist/gen/changelog/v1/changelog_pb.js +157 -14
  42. package/dist/gen/changelog/v1/changelog_pb.js.map +1 -1
  43. package/dist/gen/checkpoints/v1/checkpoints_pb.d.ts +1 -1
  44. package/dist/gen/claims/v1/claims_pb.d.ts +1 -1
  45. package/dist/gen/fees/v1/fees_pb.d.ts +1 -1
  46. package/dist/gen/index.js +20 -20
  47. package/dist/gen/ledger/read/v1/ledger_read_pb.d.ts +4 -4
  48. package/dist/gen/ledger/read/v1/ledger_read_pb.js +1 -1
  49. package/dist/gen/ledger/read/v1/ledger_read_pb.js.map +1 -1
  50. package/dist/gen/ledger/v1/catalog_pb.d.ts +11 -4
  51. package/dist/gen/ledger/v1/catalog_pb.d.ts.map +1 -1
  52. package/dist/gen/ledger/v1/catalog_pb.js +11 -4
  53. package/dist/gen/ledger/v1/catalog_pb.js.map +1 -1
  54. package/dist/gen/marketdata/v1/heatmap_pb.d.ts +1 -1
  55. package/dist/gen/marketdata/v1/marketdata_pb.d.ts +1 -1
  56. package/dist/gen/marketoverview/v1/marketoverview_pb.d.ts +4 -3
  57. package/dist/gen/marketoverview/v1/marketoverview_pb.d.ts.map +1 -1
  58. package/dist/gen/marketoverview/v1/marketoverview_pb.js.map +1 -1
  59. package/dist/gen/notifications/v1/notifications_pb.d.ts +155 -4
  60. package/dist/gen/notifications/v1/notifications_pb.d.ts.map +1 -1
  61. package/dist/gen/notifications/v1/notifications_pb.js +102 -15
  62. package/dist/gen/notifications/v1/notifications_pb.js.map +1 -1
  63. package/dist/gen/orderbook/v1/orderbook_pb.d.ts +19 -11
  64. package/dist/gen/orderbook/v1/orderbook_pb.d.ts.map +1 -1
  65. package/dist/gen/orderbook/v1/orderbook_pb.js.map +1 -1
  66. package/dist/gen/orders/v1/orders_pb.d.ts +13 -2
  67. package/dist/gen/orders/v1/orders_pb.d.ts.map +1 -1
  68. package/dist/gen/orders/v1/orders_pb.js +12 -1
  69. package/dist/gen/orders/v1/orders_pb.js.map +1 -1
  70. package/dist/gen/orders/v1/orders_read_pb.d.ts +7 -2
  71. package/dist/gen/orders/v1/orders_read_pb.d.ts.map +1 -1
  72. package/dist/gen/orders/v1/orders_read_pb.js.map +1 -1
  73. package/dist/gen/polyester/ratelimit/v1/types_pb.d.ts +1 -1
  74. package/dist/gen/polyester/type/v1/u128_pb.d.ts +1 -1
  75. package/dist/gen/privatews/v1/private_ws_pb.d.ts +1 -1
  76. package/dist/gen/ratelimit/v1/ratelimit_pb.d.ts +1 -1
  77. package/dist/gen/rewards/v1/rewards_pb.d.ts +1 -1
  78. package/dist/gen/swap/quickswap/v1/quickswap_broker_pb.d.ts +1 -1
  79. package/dist/gen/swap/quickswap/v1/quickswap_pb.d.ts +1 -1
  80. package/dist/gen/swap/quickswap/v1/quickswap_referral_pb.d.ts +1 -1
  81. package/dist/gen/swap/v1/swap_pb.d.ts +1 -1
  82. package/dist/gen/system/v1/system_pb.d.ts +1 -1
  83. package/dist/gen/tradews/v1/trade_ws_pb.d.ts +1 -1
  84. package/dist/gen/transfer/v1/internal_transfer_pb.d.ts +1 -1
  85. package/dist/gen/triggers/v1/triggers_pb.d.ts +7 -1
  86. package/dist/gen/triggers/v1/triggers_pb.d.ts.map +1 -1
  87. package/dist/gen/triggers/v1/triggers_pb.js.map +1 -1
  88. package/dist/gen/vip/v1/vip_pb.d.ts +1 -1
  89. package/dist/index.d.ts +7 -6
  90. package/dist/index.js +1 -1
  91. package/dist/realtime/snapshot-then-stream.js +1 -1
  92. package/dist/server-core.js +3 -3
  93. package/dist/services/accounts/accounts.js +1 -1
  94. package/dist/services/accounts/accounts.schemas.js +1 -1
  95. package/dist/services/address-book/address-book.js +1 -1
  96. package/dist/services/api-keys/api-keys.codecs.d.ts +14 -0
  97. package/dist/services/api-keys/api-keys.codecs.d.ts.map +1 -0
  98. package/dist/services/api-keys/api-keys.codecs.js +13 -1
  99. package/dist/services/api-keys/api-keys.codecs.js.map +1 -1
  100. package/dist/services/api-keys/api-keys.d.ts +2 -2
  101. package/dist/services/api-keys/api-keys.js +3 -3
  102. package/dist/services/api-keys/api-keys.js.map +1 -1
  103. package/dist/services/api-keys/api-keys.schemas.d.ts +46 -12
  104. package/dist/services/api-keys/api-keys.schemas.d.ts.map +1 -1
  105. package/dist/services/api-keys/api-keys.schemas.js +11 -5
  106. package/dist/services/api-keys/api-keys.schemas.js.map +1 -1
  107. package/dist/services/api-keys/api-keys.types.d.ts +2 -1
  108. package/dist/services/assistant/assistant-events.schemas.d.ts +82 -51
  109. package/dist/services/assistant/assistant-events.schemas.d.ts.map +1 -1
  110. package/dist/services/assistant/assistant-events.schemas.js +20 -2
  111. package/dist/services/assistant/assistant-events.schemas.js.map +1 -1
  112. package/dist/services/assistant/assistant.codecs.d.ts +10 -1
  113. package/dist/services/assistant/assistant.codecs.d.ts.map +1 -1
  114. package/dist/services/assistant/assistant.codecs.js +41 -1
  115. package/dist/services/assistant/assistant.codecs.js.map +1 -1
  116. package/dist/services/assistant/assistant.js +1 -1
  117. package/dist/services/assistant/assistant.schemas.d.ts +21 -3
  118. package/dist/services/assistant/assistant.schemas.d.ts.map +1 -1
  119. package/dist/services/assistant/assistant.schemas.js +28 -5
  120. package/dist/services/assistant/assistant.schemas.js.map +1 -1
  121. package/dist/services/assistant/assistant.types.d.ts +2 -2
  122. package/dist/services/auth/account-signer-auth.js +2 -2
  123. package/dist/services/auth/auth.js +1 -1
  124. package/dist/services/auth/profile/profile.js +2 -2
  125. package/dist/services/auto-withdraw/auto-withdraw.js +1 -1
  126. package/dist/services/auto-withdraw/auto-withdraw.schemas.d.ts +19 -19
  127. package/dist/services/auto-withdraw/auto-withdraw.schemas.js +1 -1
  128. package/dist/services/balances/balances.js +1 -1
  129. package/dist/services/candles/candles.js +2 -2
  130. package/dist/services/chain-analytics/chain-analytics.js +1 -1
  131. package/dist/services/changelog/changelog.codecs.d.ts +10 -1
  132. package/dist/services/changelog/changelog.codecs.d.ts.map +1 -1
  133. package/dist/services/changelog/changelog.codecs.js +13 -1
  134. package/dist/services/changelog/changelog.codecs.js.map +1 -1
  135. package/dist/services/changelog/changelog.d.ts +14 -1
  136. package/dist/services/changelog/changelog.d.ts.map +1 -1
  137. package/dist/services/changelog/changelog.js +23 -2
  138. package/dist/services/changelog/changelog.js.map +1 -1
  139. package/dist/services/changelog/changelog.schemas.d.ts +445 -19
  140. package/dist/services/changelog/changelog.schemas.d.ts.map +1 -1
  141. package/dist/services/changelog/changelog.schemas.js +94 -5
  142. package/dist/services/changelog/changelog.schemas.js.map +1 -1
  143. package/dist/services/changelog/changelog.types.d.ts +3 -3
  144. package/dist/services/checkpoints/checkpoints.js +1 -1
  145. package/dist/services/claims/claims.js +1 -1
  146. package/dist/services/claims/claims.schemas.d.ts +2 -2
  147. package/dist/services/claims/claims.schemas.js +1 -1
  148. package/dist/services/deposit/deposit.js +1 -1
  149. package/dist/services/fees/fees.js +1 -1
  150. package/dist/services/guard-signer/guard-signer.js +1 -1
  151. package/dist/services/guard-signer/guard-signer.schemas.js +1 -1
  152. package/dist/services/heatmap/heatmap.js +2 -2
  153. package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
  154. package/dist/services/internal-transfers/internal-transfers.js +1 -1
  155. package/dist/services/lifecycle/lifecycle.codecs.d.ts +8 -1
  156. package/dist/services/lifecycle/lifecycle.codecs.d.ts.map +1 -1
  157. package/dist/services/lifecycle/lifecycle.codecs.js +62 -1
  158. package/dist/services/lifecycle/lifecycle.codecs.js.map +1 -1
  159. package/dist/services/lifecycle/lifecycle.js +3 -3
  160. package/dist/services/lifecycle/lifecycle.schemas.d.ts +91 -90
  161. package/dist/services/lifecycle/lifecycle.schemas.d.ts.map +1 -1
  162. package/dist/services/lifecycle/lifecycle.schemas.js +4 -4
  163. package/dist/services/lifecycle/lifecycle.schemas.js.map +1 -1
  164. package/dist/services/lifecycle/lifecycle.types.d.ts +2 -2
  165. package/dist/services/market-data/market-data.js +2 -2
  166. package/dist/services/market-overview/market-overview.d.ts +1 -1
  167. package/dist/services/market-overview/market-overview.js +3 -3
  168. package/dist/services/market-overview/market-overview.js.map +1 -1
  169. package/dist/services/market-overview/market-overview.schemas.js +1 -1
  170. package/dist/services/notifications/notifications.codecs.d.ts +8 -2
  171. package/dist/services/notifications/notifications.codecs.d.ts.map +1 -1
  172. package/dist/services/notifications/notifications.codecs.js +14 -2
  173. package/dist/services/notifications/notifications.codecs.js.map +1 -1
  174. package/dist/services/notifications/notifications.js +1 -1
  175. package/dist/services/notifications/notifications.schemas.d.ts +92 -3
  176. package/dist/services/notifications/notifications.schemas.d.ts.map +1 -1
  177. package/dist/services/notifications/notifications.schemas.js +25 -1
  178. package/dist/services/notifications/notifications.schemas.js.map +1 -1
  179. package/dist/services/notifications/notifications.types.d.ts +2 -2
  180. package/dist/services/orderbook/orderbook.d.ts +2 -2
  181. package/dist/services/orderbook/orderbook.js +18 -13
  182. package/dist/services/orderbook/orderbook.js.map +1 -1
  183. package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
  184. package/dist/services/orders/order-errors.schemas.d.ts +1 -1
  185. package/dist/services/orders/order-errors.schemas.js +1 -1
  186. package/dist/services/orders/orders-batch.schemas.d.ts +27 -27
  187. package/dist/services/orders/orders-batch.schemas.js +2 -2
  188. package/dist/services/orders/orders-input.schemas.d.ts +3 -3
  189. package/dist/services/orders/orders-input.schemas.js +2 -2
  190. package/dist/services/orders/orders-modify.schemas.js +2 -2
  191. package/dist/services/orders/orders-output.schemas.d.ts +18 -18
  192. package/dist/services/orders/orders-output.schemas.js +1 -1
  193. package/dist/services/orders/orders-risk.schemas.js +3 -3
  194. package/dist/services/orders/orders.js +2 -2
  195. package/dist/services/policies/api-key-policies/api-key-policies.js +1 -1
  196. package/dist/services/policies/shared.codecs.js +1 -1
  197. package/dist/services/policies/subaccount-policies/subaccount-policies.js +2 -2
  198. package/dist/services/price-alerts/price-alerts.js +1 -1
  199. package/dist/services/price-alerts/price-alerts.schemas.d.ts +10 -10
  200. package/dist/services/rate-limits/rate-limits.js +1 -1
  201. package/dist/services/rewards/rewards.js +1 -1
  202. package/dist/services/rewards/rewards.schemas.d.ts +4 -4
  203. package/dist/services/social-verification/social-verification.js +1 -1
  204. package/dist/services/social-verification/social-verification.schemas.js +1 -1
  205. package/dist/services/subaccounts/subaccounts.js +3 -3
  206. package/dist/services/subaccounts/subaccounts.schemas.d.ts +11 -11
  207. package/dist/services/system/system.js +1 -1
  208. package/dist/services/trades/trades.js +2 -2
  209. package/dist/services/trades/trades.schemas.d.ts +1 -1
  210. package/dist/services/trading-withdraws/trading-withdraws.js +1 -1
  211. package/dist/services/trading-withdraws/trading-withdraws.schemas.js +1 -1
  212. package/dist/services/trading-withdraws/wallet-message.js +1 -1
  213. package/dist/services/transfers/transfers.js +2 -2
  214. package/dist/services/triggers/trigger-child-order.schemas.js +3 -3
  215. package/dist/services/triggers/trigger-input.schemas.d.ts +1 -1
  216. package/dist/services/triggers/trigger-input.schemas.js +2 -2
  217. package/dist/services/triggers/triggers-output.schemas.d.ts +23 -23
  218. package/dist/services/triggers/triggers.d.ts +1 -1
  219. package/dist/services/triggers/triggers.js +3 -3
  220. package/dist/services/triggers/triggers.js.map +1 -1
  221. package/dist/services/vip/vip.js +1 -1
  222. package/dist/services/vip/vip.schemas.d.ts +3 -3
  223. package/dist/services/vip/vip.schemas.js +1 -1
  224. package/dist/services/zipper/zipper.js +1 -1
  225. package/dist/services/zipper/zipper.schemas.js +1 -1
  226. package/dist/shared/error-details/alerts.js +1 -1
  227. package/dist/shared/error-details/assistant.js +1 -1
  228. package/dist/shared/error-details/auth.js +1 -1
  229. package/dist/shared/error-details/claims.js +1 -1
  230. package/dist/shared/error-details/internal-transfer.js +1 -1
  231. package/dist/shared/error-details/ledger.js +1 -1
  232. package/dist/shared/error-details/market-overview.js +1 -1
  233. package/dist/shared/error-details/notifications.js +1 -1
  234. package/dist/shared/error-details/orders.js +1 -1
  235. package/dist/shared/error-details/profile.js +1 -1
  236. package/dist/shared/error-details/rate-limit.js +1 -1
  237. package/dist/shared/error-details/withdraw.js +1 -1
  238. package/dist/shared/ledger-codes.d.ts +5 -3
  239. package/dist/shared/ledger-codes.d.ts.map +1 -1
  240. package/dist/shared/ledger-codes.js.map +1 -1
  241. package/dist/shared/rate-limit.schemas.js +1 -1
  242. package/dist/utils/cookies.js +1 -1
  243. package/dist/wired-services.js +17 -17
  244. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"notifications.schemas.js","names":[],"sources":["../../../src/services/notifications/notifications.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { PRICE_SCALE } from \"../../catalogs/readers.js\";\nimport type * as Proto from \"../../gen/notifications/v1/notifications_pb.js\";\nimport { scaledToDecimalOutput } from \"../../shared/decimal-surface.js\";\nimport { enumLabel } from \"../../shared/proto-enum-codec.js\";\nimport { idInputSchema, optionalIdInputSchema } from \"../../shared/schemas.js\";\nimport { formatId } from \"../../utils/base58-id.js\";\nimport { tsObjToMs } from \"../../utils/time.js\";\nimport { msToTimestamp } from \"../../utils/timestamp.js\";\nimport {\n PriceAlertDirectionCodec,\n PriceAlertPriceSourceCodec,\n} from \"../price-alerts/price-alerts.codecs.js\";\nimport {\n NOTIFICATION_CATEGORY_VALUES,\n NOTIFICATION_READ_STATE_VALUES,\n NotificationCategoryCodec,\n NotificationReadStateCodec,\n NotificationTypeCodec,\n TelegramApprovalActionCodec,\n} from \"./notifications.codecs.js\";\n\nconst NotificationIdInputSchema = idInputSchema(\"notificationId\");\n\n/** Omit or pass empty for every category. */\nconst CategoriesInputSchema = v.optional(\n v.pipe(\n v.array(v.picklist(NOTIFICATION_CATEGORY_VALUES)),\n v.transform((categories) =>\n categories.map((category) => NotificationCategoryCodec.inputToProto[category]),\n ),\n ),\n);\n\nconst TimestampMsInputSchema = v.pipe(\n v.number(),\n v.integer(),\n v.minValue(0),\n v.maxValue(Number.MAX_SAFE_INTEGER),\n);\n\nexport const ListNotificationsInputSchema = v.pipe(\n v.strictObject({\n categories: CategoriesInputSchema,\n /** Only read or only unread notifications; omit for both. */\n readState: v.optional(v.picklist(NOTIFICATION_READ_STATE_VALUES)),\n /** Epoch ms, inclusive. */\n startTime: v.optional(TimestampMsInputSchema),\n /** Epoch ms, exclusive; after `startTime` when both are set. */\n endTime: v.optional(TimestampMsInputSchema),\n /** Page size: default 25, at most 100. */\n limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(100))),\n /** Previous `nextPageToken`; reuse only with the same filters. */\n pageToken: v.optional(v.pipe(v.string(), v.trim())),\n }),\n v.check(\n ({ startTime, endTime }) =>\n startTime === undefined || endTime === undefined || endTime > startTime,\n \"endTime: must be after startTime\",\n ),\n v.transform(({ readState, startTime, endTime, ...input }) => ({\n ...input,\n readState: readState && NotificationReadStateCodec.inputToProto[readState],\n startTime: startTime === undefined ? undefined : msToTimestamp(startTime),\n endTime: endTime === undefined ? undefined : msToTimestamp(endTime),\n })),\n);\n\nexport type ListNotificationsInput = v.InferInput<typeof ListNotificationsInputSchema>;\n\nexport const GetNotificationInputSchema = v.strictObject({\n notificationId: NotificationIdInputSchema,\n});\n\nexport type GetNotificationInput = v.InferInput<typeof GetNotificationInputSchema>;\n\nexport const MarkNotificationsInputSchema = v.strictObject({\n /** One to 100 distinct notification IDs. */\n notificationIds: v.pipe(\n v.array(NotificationIdInputSchema),\n v.minLength(1, \"At least one notification ID is required.\"),\n v.maxLength(100, \"At most 100 notification IDs are allowed.\"),\n v.check((ids) => new Set(ids).size === ids.length, \"Notification IDs must be distinct.\"),\n ),\n});\n\nexport type MarkNotificationsInput = v.InferInput<typeof MarkNotificationsInputSchema>;\n\nexport const MarkAllNotificationsReadInputSchema = v.strictObject({\n categories: CategoriesInputSchema,\n /**\n * Mark only this notification and older ones. Pass the newest one shown, so one that arrives\n * later stays unread; omit to mark every notification that exists when the call runs.\n */\n throughNotificationId: optionalIdInputSchema(\"throughNotificationId\"),\n});\n\nexport type MarkAllNotificationsReadInput = v.InferInput<\n typeof MarkAllNotificationsReadInputSchema\n>;\n\n/*\n * Outputs are formatted straight from the decoded messages, like the assistant's run events.\n * The `detail` oneof becomes a `type`-tagged union; a case this build does not know becomes\n * `{ type: \"unspecified\" }`, and the notification's `title` and `text` describe it.\n */\n\nconst price = (ticks: bigint) => scaledToDecimalOutput(ticks, PRICE_SCALE);\n\nfunction formatDetail(detail: Proto.Notification[\"detail\"]) {\n switch (detail.case) {\n case \"priceAlert\": {\n const notice = detail.value;\n return {\n type: \"price_alert\" as const,\n /** The alert's ID in `client.priceAlerts`. */\n alertId: formatId(notice.alertId),\n symbolId: notice.symbolId,\n direction: enumLabel(PriceAlertDirectionCodec.protoToOutput, notice.direction),\n priceSource: enumLabel(\n PriceAlertPriceSourceCodec.protoToOutput,\n notice.priceSource,\n ),\n /** Alert price, as a decimal string. */\n price: price(notice.priceTicks),\n /** Price that fired the alert, as a decimal string. */\n triggeredPrice: price(notice.triggeredPriceTicks),\n triggeredAt: tsObjToMs(notice.triggeredAt) ?? null,\n };\n }\n case \"telegramApproval\": {\n const notice = detail.value;\n return {\n type: \"telegram_approval\" as const,\n /** The approval's ID in `client.assistant`. */\n approvalId: formatId(notice.approvalId),\n action: enumLabel(TelegramApprovalActionCodec.protoToOutput, notice.action),\n /** Trading account (subaccount) the action acted on. */\n accountId: formatId(notice.accountId),\n summary: notice.summary,\n /** Key parameters in display order, such as market, side and quantity. */\n parameters: notice.parameters.map(({ label, value }) => ({ label, value })),\n approvedAt: tsObjToMs(notice.approvedAt) ?? null,\n };\n }\n default:\n return { type: \"unspecified\" as const };\n }\n}\n\nexport function formatNotification(notification: Proto.Notification) {\n return {\n notificationId: formatId(notification.notificationId),\n type: enumLabel(NotificationTypeCodec.protoToOutput, notification.type),\n category: enumLabel(NotificationCategoryCodec.protoToOutput, notification.category),\n /** Plain-text title, the same for every notification of a type. */\n title: notification.title,\n /** Plain-text summary; may span several lines. */\n text: notification.text,\n createdAt: tsObjToMs(notification.createdAt) ?? null,\n /** Null while unread. */\n readAt: tsObjToMs(notification.readAt) ?? null,\n detail: formatDetail(notification.detail),\n };\n}\n\n/**\n * One notification. When `detail.type` is `\"unspecified\"` (a type this SDK build does not\n * know), show `title` and `text` only.\n */\nexport type AccountNotification = ReturnType<typeof formatNotification>;\n\nexport type AccountNotificationDetail = AccountNotification[\"detail\"];\n\n/** One page of notifications, newest first; an empty `nextPageToken` means no more. */\nexport type ListNotificationsResult = {\n notifications: AccountNotification[];\n nextPageToken: string;\n};\n\nexport function formatNotificationCounts(counts: Proto.GetNotificationCountsResponse) {\n return {\n total: Number(counts.total),\n unread: Number(counts.unread),\n /** Every type in ascending enum order, including types with no notification. */\n types: counts.types.map((count) => ({\n type: enumLabel(NotificationTypeCodec.protoToOutput, count.type),\n category: enumLabel(NotificationCategoryCodec.protoToOutput, count.category),\n total: Number(count.total),\n unread: Number(count.unread),\n })),\n };\n}\n\n/** Exact counts of the caller's notifications, as of one moment. */\nexport type NotificationCounts = ReturnType<typeof formatNotificationCounts>;\n"],"mappings":";;;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KAAK;;EAEhD,QAAQ,UAAU,aAAa,MAAM,KAAK;EAC1C,QAAQ,aAAa,aAAa,MAAM;CAC5C;AACJ;AAgBA,SAAgB,yBAAyB,QAA6C;CAClF,OAAO;EACH,OAAO,OAAO,OAAO,KAAK;EAC1B,QAAQ,OAAO,OAAO,MAAM;;EAE5B,OAAO,OAAO,MAAM,KAAK,WAAW;GAChC,MAAM,UAAU,sBAAsB,eAAe,MAAM,IAAI;GAC/D,UAAU,UAAU,0BAA0B,eAAe,MAAM,QAAQ;GAC3E,OAAO,OAAO,MAAM,KAAK;GACzB,QAAQ,OAAO,MAAM,MAAM;EAC/B,EAAE;CACN;AACJ"}
1
+ {"version":3,"file":"notifications.schemas.js","names":[],"sources":["../../../src/services/notifications/notifications.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { PRICE_SCALE } from \"../../catalogs/readers.js\";\nimport type * as Proto from \"../../gen/notifications/v1/notifications_pb.js\";\nimport { scaledToDecimalOutput } from \"../../shared/decimal-surface.js\";\nimport { enumLabel } from \"../../shared/proto-enum-codec.js\";\nimport { idInputSchema, optionalIdInputSchema } from \"../../shared/schemas.js\";\nimport { formatId } from \"../../utils/base58-id.js\";\nimport { tsObjToMs } from \"../../utils/time.js\";\nimport { msToTimestamp } from \"../../utils/timestamp.js\";\nimport {\n PriceAlertDirectionCodec,\n PriceAlertPriceSourceCodec,\n} from \"../price-alerts/price-alerts.codecs.js\";\nimport {\n BrokerAllowlistActionCodec,\n BrokerAllowlistEventCodec,\n NOTIFICATION_CATEGORY_VALUES,\n NOTIFICATION_READ_STATE_VALUES,\n NotificationCategoryCodec,\n NotificationReadStateCodec,\n NotificationTypeCodec,\n TelegramApprovalActionCodec,\n} from \"./notifications.codecs.js\";\n\nconst NotificationIdInputSchema = idInputSchema(\"notificationId\");\n\n/** Omit or pass empty for every category. */\nconst CategoriesInputSchema = v.optional(\n v.pipe(\n v.array(v.picklist(NOTIFICATION_CATEGORY_VALUES)),\n v.transform((categories) =>\n categories.map((category) => NotificationCategoryCodec.inputToProto[category]),\n ),\n ),\n);\n\nconst TimestampMsInputSchema = v.pipe(\n v.number(),\n v.integer(),\n v.minValue(0),\n v.maxValue(Number.MAX_SAFE_INTEGER),\n);\n\nexport const ListNotificationsInputSchema = v.pipe(\n v.strictObject({\n categories: CategoriesInputSchema,\n /** Only read or only unread notifications; omit for both. */\n readState: v.optional(v.picklist(NOTIFICATION_READ_STATE_VALUES)),\n /** Epoch ms, inclusive. */\n startTime: v.optional(TimestampMsInputSchema),\n /** Epoch ms, exclusive; after `startTime` when both are set. */\n endTime: v.optional(TimestampMsInputSchema),\n /** Page size: default 25, at most 100. */\n limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(100))),\n /** Previous `nextPageToken`; reuse only with the same filters. */\n pageToken: v.optional(v.pipe(v.string(), v.trim())),\n }),\n v.check(\n ({ startTime, endTime }) =>\n startTime === undefined || endTime === undefined || endTime > startTime,\n \"endTime: must be after startTime\",\n ),\n v.transform(({ readState, startTime, endTime, ...input }) => ({\n ...input,\n readState: readState && NotificationReadStateCodec.inputToProto[readState],\n startTime: startTime === undefined ? undefined : msToTimestamp(startTime),\n endTime: endTime === undefined ? undefined : msToTimestamp(endTime),\n })),\n);\n\nexport type ListNotificationsInput = v.InferInput<typeof ListNotificationsInputSchema>;\n\nexport const GetNotificationInputSchema = v.strictObject({\n notificationId: NotificationIdInputSchema,\n});\n\nexport type GetNotificationInput = v.InferInput<typeof GetNotificationInputSchema>;\n\nexport const MarkNotificationsInputSchema = v.strictObject({\n /** One to 100 distinct notification IDs. */\n notificationIds: v.pipe(\n v.array(NotificationIdInputSchema),\n v.minLength(1, \"At least one notification ID is required.\"),\n v.maxLength(100, \"At most 100 notification IDs are allowed.\"),\n v.check((ids) => new Set(ids).size === ids.length, \"Notification IDs must be distinct.\"),\n ),\n});\n\nexport type MarkNotificationsInput = v.InferInput<typeof MarkNotificationsInputSchema>;\n\nexport const MarkAllNotificationsReadInputSchema = v.strictObject({\n categories: CategoriesInputSchema,\n /**\n * Mark only this notification and older ones. Pass the newest one shown, so one that arrives\n * later stays unread; omit to mark every notification that exists when the call runs.\n */\n throughNotificationId: optionalIdInputSchema(\"throughNotificationId\"),\n});\n\nexport type MarkAllNotificationsReadInput = v.InferInput<\n typeof MarkAllNotificationsReadInputSchema\n>;\n\n/*\n * Outputs are formatted straight from the decoded messages, like the assistant's run events.\n * The `detail` oneof becomes a `type`-tagged union; a case this build does not know becomes\n * `{ type: \"unspecified\" }`, and the notification's `title` and `text` describe it.\n */\n\nconst price = (ticks: bigint) => scaledToDecimalOutput(ticks, PRICE_SCALE);\n\nfunction formatDetail(detail: Proto.Notification[\"detail\"]) {\n switch (detail.case) {\n case \"priceAlert\": {\n const notice = detail.value;\n return {\n type: \"price_alert\" as const,\n /** The alert's ID in `client.priceAlerts`. */\n alertId: formatId(notice.alertId),\n symbolId: notice.symbolId,\n direction: enumLabel(PriceAlertDirectionCodec.protoToOutput, notice.direction),\n priceSource: enumLabel(\n PriceAlertPriceSourceCodec.protoToOutput,\n notice.priceSource,\n ),\n /** Alert price, as a decimal string. */\n price: price(notice.priceTicks),\n /** Price that fired the alert, as a decimal string. */\n triggeredPrice: price(notice.triggeredPriceTicks),\n triggeredAt: tsObjToMs(notice.triggeredAt) ?? null,\n };\n }\n case \"telegramApproval\": {\n const notice = detail.value;\n return {\n type: \"telegram_approval\" as const,\n /** The approval's ID in `client.assistant`. */\n approvalId: formatId(notice.approvalId),\n action: enumLabel(TelegramApprovalActionCodec.protoToOutput, notice.action),\n /** Trading account (subaccount) the action acted on. */\n accountId: formatId(notice.accountId),\n summary: notice.summary,\n /** Key parameters in display order, such as market, side and quantity. */\n parameters: notice.parameters.map(({ label, value }) => ({ label, value })),\n approvedAt: tsObjToMs(notice.approvedAt) ?? null,\n };\n }\n case \"brokerAllowlist\": {\n const notice = detail.value;\n return {\n type: \"broker_allowlist_change\" as const,\n broker: notice.broker,\n /** Sub-account ID of the broker vault. */\n vaultAccountId: formatId(notice.vaultAccountId),\n /** The change's ID; key the broker's vault allowlist view on it. */\n changeId: formatId(notice.changeId),\n event: enumLabel(BrokerAllowlistEventCodec.protoToOutput, notice.event),\n action: enumLabel(BrokerAllowlistActionCodec.protoToOutput, notice.action),\n /** Destination chain ID, as a decimal string. */\n destinationChainId: notice.destinationChainId.toString(),\n destinationAddress: notice.destinationAddress,\n /** The requesting member's name for an added address; empty when none. */\n label: notice.label,\n /**\n * Account ID of the member who requested the change. Show a `change_requested`\n * the caller did not make prominently: an added address becomes payable 24 hours\n * after it is listed.\n */\n requestedByAccountId: formatId(notice.requestedByAccountId),\n };\n }\n default:\n return { type: \"unspecified\" as const };\n }\n}\n\nexport function formatNotification(notification: Proto.Notification) {\n return {\n notificationId: formatId(notification.notificationId),\n type: enumLabel(NotificationTypeCodec.protoToOutput, notification.type),\n category: enumLabel(NotificationCategoryCodec.protoToOutput, notification.category),\n /** Plain-text title, the same for every notification of a type. */\n title: notification.title,\n /** Plain-text summary; may span several lines. */\n text: notification.text,\n createdAt: tsObjToMs(notification.createdAt) ?? null,\n /** Null while unread. */\n readAt: tsObjToMs(notification.readAt) ?? null,\n detail: formatDetail(notification.detail),\n };\n}\n\n/**\n * One notification. When `detail.type` is `\"unspecified\"` (a type this SDK build does not\n * know), show `title` and `text` only.\n */\nexport type AccountNotification = ReturnType<typeof formatNotification>;\n\nexport type AccountNotificationDetail = AccountNotification[\"detail\"];\n\n/** One page of notifications, newest first; an empty `nextPageToken` means no more. */\nexport type ListNotificationsResult = {\n notifications: AccountNotification[];\n nextPageToken: string;\n};\n\nexport function formatNotificationCounts(counts: Proto.GetNotificationCountsResponse) {\n return {\n total: Number(counts.total),\n unread: Number(counts.unread),\n /** Every type in ascending enum order, including types with no notification. */\n types: counts.types.map((count) => ({\n type: enumLabel(NotificationTypeCodec.protoToOutput, count.type),\n category: enumLabel(NotificationCategoryCodec.protoToOutput, count.category),\n total: Number(count.total),\n unread: Number(count.unread),\n })),\n };\n}\n\n/** Exact counts of the caller's notifications, as of one moment. */\nexport type NotificationCounts = ReturnType<typeof formatNotificationCounts>;\n"],"mappings":";;;;;;;;;;AAwBA,MAAM,4BAA4B,cAAc,gBAAgB;;AAGhE,MAAM,wBAAwB,EAAE,SAC5B,EAAE,KACE,EAAE,MAAM,EAAE,SAAS,4BAA4B,CAAC,GAChD,EAAE,WAAW,eACT,WAAW,KAAK,aAAa,0BAA0B,aAAa,SAAS,CACjF,CACJ,CACJ;AAEA,MAAM,yBAAyB,EAAE,KAC7B,EAAE,OAAO,GACT,EAAE,QAAQ,GACV,EAAE,SAAS,CAAC,GACZ,EAAE,SAAS,OAAO,gBAAgB,CACtC;AAEA,MAAa,+BAA+B,EAAE,KAC1C,EAAE,aAAa;CACX,YAAY;;CAEZ,WAAW,EAAE,SAAS,EAAE,SAAS,8BAA8B,CAAC;;CAEhE,WAAW,EAAE,SAAS,sBAAsB;;CAE5C,SAAS,EAAE,SAAS,sBAAsB;;CAE1C,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,QAAQ,GAAG,EAAE,SAAS,CAAC,GAAG,EAAE,SAAS,GAAG,CAAC,CAAC;;CAEjF,WAAW,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,KAAK,CAAC,CAAC;AACtD,CAAC,GACD,EAAE,OACG,EAAE,WAAW,cACV,cAAc,KAAA,KAAa,YAAY,KAAA,KAAa,UAAU,WAClE,kCACJ,GACA,EAAE,WAAW,EAAE,WAAW,WAAW,SAAS,GAAG,aAAa;CAC1D,GAAG;CACH,WAAW,aAAa,2BAA2B,aAAa;CAChE,WAAW,cAAc,KAAA,IAAY,KAAA,IAAY,cAAc,SAAS;CACxE,SAAS,YAAY,KAAA,IAAY,KAAA,IAAY,cAAc,OAAO;AACtE,EAAE,CACN;AAIA,MAAa,6BAA6B,EAAE,aAAa,EACrD,gBAAgB,0BACpB,CAAC;AAID,MAAa,+BAA+B,EAAE,aAAa;;AAEvD,iB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ACtE,QAAQ,UAAU,2BAA2B,eAAe,OAAO,MAAM;;IAEzE,oBAAoB,OAAO,mBAAmB,SAAS;IACvD,oBAAoB,OAAO;;IAE3B,OAAO,OAAO;;;;;;IAMd,sBAAsB,SAAS,OAAO,oBAAoB;GAC9D;EACJ;EACA,SACI,OAAO,EAAE,MAAM,cAAuB;CAC9C;AACJ;AAEA,SAAgB,mBAAmB,cAAkC;CACjE,OAAO;EACH,gBAAgB,SAAS,aAAa,cAAc;EACpD,MAAM,UAAU,sBAAsB,eAAe,aAAa,IAAI;EACtE,UAAU,UAAU,0BAA0B,eAAe,aAAa,QAAQ;;EAElF,OAAO,aAAa;;EAEpB,MAAM,aAAa;EACnB,WAAW,UAAU,aAAa,SAAS,KAAK;;EAEhD,QAAQ,UAAU,aAAa,MAAM,KAAK;EAC1C,QAAQ,aAAa,aAAa,MAAM;CAC5C;AACJ;AAgBA,SAAgB,yBAAyB,QAA6C;CAClF,OAAO;EACH,OAAO,OAAO,OAAO,KAAK;EAC1B,QAAQ,OAAO,OAAO,MAAM;;EAE5B,OAAO,OAAO,MAAM,KAAK,WAAW;GAChC,MAAM,UAAU,sBAAsB,eAAe,MAAM,IAAI;GAC/D,UAAU,UAAU,0BAA0B,eAAe,MAAM,QAAQ;GAC3E,OAAO,OAAO,MAAM,KAAK;GACzB,QAAQ,OAAO,MAAM,MAAM;EAC/B,EAAE;CACN;AACJ"}
@@ -1,3 +1,3 @@
1
1
  import { AccountNotification, AccountNotificationDetail, GetNotificationInput, ListNotificationsInput, ListNotificationsResult, MarkAllNotificationsReadInput, MarkNotificationsInput, NotificationCounts } from "./notifications.schemas.js";
2
- import { NotificationCategory, NotificationReadState, NotificationType, TelegramApprovalAction } from "./notifications.codecs.js";
3
- export type { AccountNotification, AccountNotificationDetail, GetNotificationInput, ListNotificationsInput, ListNotificationsResult, MarkAllNotificationsReadInput, MarkNotificationsInput, NotificationCategory, NotificationCounts, NotificationReadState, NotificationType, TelegramApprovalAction };
2
+ import { BrokerAllowlistAction, BrokerAllowlistEvent, NotificationCategory, NotificationReadState, NotificationType, TelegramApprovalAction } from "./notifications.codecs.js";
3
+ export type { AccountNotification, AccountNotificationDetail, BrokerAllowlistAction, BrokerAllowlistEvent, GetNotificationInput, ListNotificationsInput, ListNotificationsResult, MarkAllNotificationsReadInput, MarkNotificationsInput, NotificationCategory, NotificationCounts, NotificationReadState, NotificationType, TelegramApprovalAction };
@@ -33,11 +33,11 @@ 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 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.
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 each delta only when it chains onto the book, and refetches on reconnects. After a sequence gap the book holds its last state until the server's next reset, sent about every 30 seconds and after gaps. 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
  *
40
- * 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.
40
+ * Refetching is driven by 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.
41
41
  */
42
42
  createSubscription(input: CreateOrderbookSubscriptionInput): OrderbookSubscription;
43
43
  }
@@ -1,4 +1,3 @@
1
- import { GetOrderBookResponseSchema, OrderBookDeltaSchema, OrderbookService as OrderbookService$1 } from "../../gen/orderbook/v1/orderbook_pb.js";
2
1
  import { ServiceUnavailableError } from "../../shared/errors.js";
3
2
  import { parse } from "../../shared/validation.js";
4
3
  import { toConnectCallOptions } from "../../shared/request-options.js";
@@ -6,6 +5,7 @@ import { decimalInputToScaled } from "../../shared/decimal-surface.js";
6
5
  import { publicationHandlerErrorContext } from "../../shared/subscription-errors.js";
7
6
  import { isResourceNotFoundError } from "../../utils/errors.js";
8
7
  import { snapshotThenStream } from "../../realtime/snapshot-then-stream.js";
8
+ import { GetOrderBookResponseSchema, OrderBookDeltaSchema, OrderbookService as OrderbookService$1 } from "../../gen/orderbook/v1/orderbook_pb.js";
9
9
  import { orderbookWsChannelDepth } from "./orderbook.codecs.js";
10
10
  import { GetOrderbookInputSchema, createOrderbookDataSchema, formatOrderbookLevel } from "./orderbook.schemas.js";
11
11
  import { create } from "@bufbuild/protobuf";
@@ -50,11 +50,11 @@ 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 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.
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 each delta only when it chains onto the book, and refetches on reconnects. After a sequence gap the book holds its last state until the server's next reset, sent about every 30 seconds and after gaps. 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
  *
57
- * 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.
57
+ * Refetching is driven by 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.
58
58
  */
59
59
  createSubscription(input) {
60
60
  const { symbolId } = parse(GetOrderbookInputSchema, {
@@ -69,6 +69,7 @@ var OrderbookService = class {
69
69
  let bidsMap = /* @__PURE__ */ new Map();
70
70
  let asksMap = /* @__PURE__ */ new Map();
71
71
  let currentBookSeq = 0n;
72
+ let awaitingReset = false;
72
73
  let bucketTicks = null;
73
74
  let stream;
74
75
  function levelsToMap(levels) {
@@ -153,22 +154,25 @@ var OrderbookService = class {
153
154
  if (!isBookAvailable(res)) throw new ServiceUnavailableError(`Order book for symbol ${symbolId} is not available yet`);
154
155
  return res;
155
156
  }
157
+ /**
158
+ * Applies a delta only when it chains onto the current book (`bookSeqStart` equals the
159
+ * last applied `bookSeqEnd`) or is a reset. A delta that does not chain leaves the book
160
+ * waiting for the next reset, which the server sends periodically and after a gap.
161
+ */
156
162
  function handleDelta(delta) {
157
- if (delta.bookSeqEnd <= currentBookSeq) return true;
163
+ if (delta.bookSeqEnd <= currentBookSeq) return;
158
164
  if (delta.reset) {
159
165
  bidsMap.clear();
160
166
  asksMap.clear();
161
- currentBookSeq = 0n;
162
- }
163
- if (currentBookSeq !== 0n && delta.bookSeqStart > currentBookSeq + 1n) {
164
- stream?.refreshSnapshot();
165
- return false;
167
+ awaitingReset = false;
168
+ } else if (awaitingReset || delta.bookSeqStart !== currentBookSeq) {
169
+ awaitingReset = true;
170
+ return;
166
171
  }
167
172
  applySideDelta(bidsMap, delta.bids);
168
173
  applySideDelta(asksMap, delta.asks);
169
- currentBookSeq = delta.bookSeqEnd > currentBookSeq ? delta.bookSeqEnd : currentBookSeq;
174
+ currentBookSeq = delta.bookSeqEnd;
170
175
  emit();
171
- return true;
172
176
  }
173
177
  setBucket(input.bucket);
174
178
  stream = snapshotThenStream({
@@ -187,16 +191,17 @@ var OrderbookService = class {
187
191
  bidsMap = levelsToMap(snapshot.bids);
188
192
  asksMap = levelsToMap(snapshot.asks);
189
193
  currentBookSeq = snapshot.bookSeq;
194
+ awaitingReset = false;
190
195
  emit();
191
196
  for (const delta of bufferedDeltas) {
192
197
  if (stream?.isDisposed()) return;
193
- if (!handleDelta(delta)) return;
198
+ handleDelta(delta);
194
199
  }
195
200
  },
196
201
  applyLivePublications: (deltas) => {
197
202
  for (const delta of deltas) {
198
203
  if (stream?.isDisposed()) return;
199
- if (!handleDelta(delta)) return;
204
+ handleDelta(delta);
200
205
  }
201
206
  },
202
207
  onOpen: input.onOpen,
@@ -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 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,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;;;;;;;;CAS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,KAAK,SAAS,KAAK,IAAI,KAAK,SAAS;AACrE"}
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 each delta only when it chains onto the book, and refetches on reconnects. After a sequence gap the book holds its last state until the server's next reset, sent about every 30 seconds and after gaps. 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 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 // Set when a delta does not chain onto the book; only the next reset recovers it.\n let awaitingReset = false;\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 /**\n * Applies a delta only when it chains onto the current book (`bookSeqStart` equals the\n * last applied `bookSeqEnd`) or is a reset. A delta that does not chain leaves the book\n * waiting for the next reset, which the server sends periodically and after a gap.\n */\n function handleDelta(delta: Proto.OrderBookDelta): void {\n if (delta.bookSeqEnd <= currentBookSeq) return;\n\n if (delta.reset) {\n bidsMap.clear();\n asksMap.clear();\n awaitingReset = false;\n } else if (awaitingReset || delta.bookSeqStart !== currentBookSeq) {\n awaitingReset = true;\n return;\n }\n\n applySideDelta(bidsMap, delta.bids);\n applySideDelta(asksMap, delta.asks);\n\n currentBookSeq = delta.bookSeqEnd;\n emit();\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 awaitingReset = false;\n emit();\n for (const delta of bufferedDeltas) {\n if (stream?.isDisposed()) return;\n handleDelta(delta);\n }\n },\n applyLivePublications: (deltas) => {\n for (const delta of deltas) {\n if (stream?.isDisposed()) return;\n handleDelta(delta);\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,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BAAiB,SAAS;IAC1B,gBAAgB;IAChB,KAAK;IACL,KAAK,MAAM,SAAS,gBAAgB;KAChC,IAAI,QAAQ,WAAW,GAAG;KAC1B,YAAY,KAAK;IACrB;GACJ;GACA,wBAAwB,WAAW;IAC/B,KAAK,MAAM,SAAS,QAAQ;KACxB,IAAI,QAAQ,WAAW,GAAG;KAC1B,YAAY,KAAK;IACrB;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 | 10 | 5 | 20 | 100 | 200 | 500 | 1000 | 50;
13
+ depth: 1 | 5 | 10 | 20 | 100 | 200 | 500 | 1000 | 50;
14
14
  protoDepth: Depth;
15
15
  }>]>;
16
16
  type GetOrderbookInput = v.InferInput<typeof GetOrderbookInputSchema>;
@@ -3,7 +3,7 @@ import * as v from "valibot";
3
3
  //#region src/services/orders/order-errors.schemas.d.ts
4
4
  type OrderErrorCode = keyof typeof ErrorCode;
5
5
  declare const OrderErrorDetailSchema: v.ObjectSchema<{
6
- readonly code: v.SchemaWithPipe<readonly [v.EnumSchema<typeof ErrorCode, undefined>, v.TransformAction<ErrorCode, "STALE_QUOTE" | "UNSPECIFIED" | "UNAUTHENTICATED" | "RATE_LIMIT_EXCEEDED" | "INTERNAL_ERROR" | "PERMISSION_DENIED" | "SUBACCOUNT_INACTIVE" | "BAD_REQUEST" | "INVALID_ARGUMENT" | "INSUFFICIENT_FUNDS" | "UNKNOWN_SYMBOL" | "BAD_PRICE" | "BAD_QTY" | "MIN_NOTIONAL" | "QTY_STEP_SIZE" | "CONFLICT_DUPLICATE_CLIENT_ORDER_ID" | "UNAVAILABLE" | "NOT_FOUND" | "UPSTREAM_ERROR" | "FEE_ASSET_NOT_ALLOWED" | "PAIR_DISABLED" | "ORDER_UNKNOWN" | "POLICY_MARKET_DENY" | "POLICY_MAX_NOTIONAL" | "POLICY_TRADING_HALTED" | "POLICY_SPOT_TRADE_DENY" | "API_KEY_ROOT_SCOPE_ONLY" | "API_KEY_SUB_SCOPE_ONLY" | "API_KEY_SUBACCOUNT_MISMATCH" | "API_KEY_POLICY_REQUIRED" | "API_KEY_UNKNOWN" | "API_KEY_MARKET_DENY" | "API_KEY_SPOT_TRADE_DENY" | "PRICE_TICK_SIZE" | "MIN_QTY" | "POST_ONLY_LIMIT_ONLY" | "BATCH_TOO_LARGE" | "POLICY_MAX_OPEN_ORDERS" | "MODIFICATION_REQUIRES_REPLACE" | "CONFLICT_IDEMPOTENCY_KEY_REUSE" | "MARKET_PRICE_UNAVAILABLE" | "PAIR_NOT_LISTED_YET" | "PAIR_DELISTED" | "PAIR_CANCEL_ONLY" | "PAIR_POST_ONLY" | "PAIR_REDUCE_ONLY" | "RISK_LIMIT" | "MARKET_HALTED" | "ACCOUNT_UNKNOWN" | "POST_ONLY_CROSS" | "REDUCE_ONLY_BLOCKED" | "PRICE_BAND_VIOLATION" | "MARKET_CAP_VIOLATION" | "EMPTY_BOOK" | "FOK_INSUFFICIENT_LIQUIDITY" | "ORDER_ALREADY_TERMINAL" | "TRIGGER_PRICE_INVALID" | "TRIGGER_PRICE_SOURCE_UNSUPPORTED" | "TRAILING_DISTANCE_INVALID" | "TRIGGER_NOT_FOUND" | "TRIGGER_STATUS_INVALID" | "TRIGGER_NOT_MODIFIABLE" | "CONFLICT_DUPLICATE_CLIENT_TRIGGER_ID" | "MAX_SLIPPAGE_INVALID" | "VALIDATION_ERROR" | "OVERLOADED" | "QUOTE_SIZE_TOO_SMALL" | "SUBACCOUNT_READ_FORBIDDEN" | "POLICY_SPOT_READ_DENY" | "API_KEY_SPOT_READ_DENY" | "CANCEL_REQUEST_EXPIRED" | "MAX_QTY" | "MAX_NOTIONAL" | "QTY_AT_OR_BELOW_FILLED" | "GATEWAY_MISCONFIGURED" | "INVALID_ORDER_ID" | "CHILD_QTY_RAISE_NOT_ALLOWED" | "ATTACHED_RISK_NOT_SUPPORTED" | "SETTLEMENT_BACKLOGGED" | "PRICE_LEVEL_QUANTITY_LIMIT" | "MARKET_QUOTE_STALE" | "MARKET_QUOTE_UNHEALTHY" | "INVALID_TIME_IN_FORCE" | "QUICKSWAP_NOT_PERMITTED" | "DUPLICATE_ORDER_ID" | "MAX_OPEN_ORDERS_TOTAL" | "STP_MODE_NOT_ALLOWED" | "PAIR_BACKLOGGED" | "PRICE_LEVELS_EXHAUSTED" | "CLIENT_ORDER_IDS_EXHAUSTED" | "ORDER_ID_CONFLICT" | "INVALID_SIDE" | "INVALID_ORDER_TYPE" | "INVALID_STP_MODE" | "INVALID_ORDER_FLAGS" | "BATCH_OTHER_ITEM_INVALID" | "REPLACE_ONTO_OWN_ID" | "INVALID_CLIENT_ORDER_ID" | "ORDER_SEQUENCE_EXHAUSTED" | "INVALID_HANDLING_MODE" | "FEE_SCHEDULE_UNAVAILABLE" | "POLICY_UNAVAILABLE" | "CANCEL_ALL_AFTER_TIMEOUT_INVALID" | "CANCEL_SCOPE_TOO_LARGE" | "RATE_LIMIT_POLICY_UNAVAILABLE" | "SYSTEM_RATE_LIMITED" | "ORDER_MODIFY_IN_PROGRESS" | "ORDER_PLACEMENT_PENDING" | "INVALID_MODIFY_BEHAVIOR" | "BATCH_REPLACE_ONLY_REQUIRED" | "BATCH_SINGLE_SYMBOL_REQUIRED" | "REQUEST_RECEIPTS_EXHAUSTED" | "INTENT_ID_INVALID" | "DRY_RUN_INVALID" | "CANCEL_ALL_AFTER_SCOPE_CONFLICT" | "NEW_ACCOUNT_CAPACITY_REACHED" | "TRIGGER_CHILD_PRICE_NOT_MODIFIABLE" | "TRIGGER_GENERATIONS_EXHAUSTED" | "TRIGGER_CONTROL_SHARE_EXHAUSTED" | "TRIGGER_CONTROLS_BUSY" | "TRIGGER_TYPE_NOT_SUPPORTED" | "INVALID_TRIGGER_TYPE" | "TRIGGER_DIRECTION_INVALID" | "TRIGGER_QTY_INVALID" | "TRIGGER_BUY_REQUIRES_LIMIT" | "ACCOUNT_ROUTING_INVALID" | "TRIGGER_LIMIT_EXCEEDED" | "TRIGGER_CONTROL_IN_PROGRESS" | "TRIGGER_PATCH_EMPTY" | "CLIENT_TRIGGER_ID_INVALID" | "TRIGGER_ACTIVATION_PRICE_INVALID" | "SLIPPAGE_TICKS_INVALID" | "SLIPPAGE_BPS_INVALID" | "TRIGGER_CONTROL_OUTCOME_UNKNOWN" | "TRIGGER_CAPACITY_REACHED" | "RESERVATION_CAPACITY_REACHED" | "CLIENT_ORDER_ID_CAPACITY_REACHED" | "ACCOUNT_RESERVATION_LIMIT_REACHED" | "INVALID_TRIGGER_CONTROL" | "TRIGGER_PATCH_NOT_ALLOWED" | "TRIGGER_PATCH_FIELD_UNKNOWN" | "TRIGGER_PATCH_VALUE_UNMASKED" | "TRIGGER_PATCH_PRICE_MODE_INVALID" | "ACCOUNT_ORDERS_SUSPENDED" | "TRAILING_SIDE_NOT_SUPPORTED" | "TRAILING_CHILD_NOT_MARKET" | "TWAP_DURATION_INVALID" | "LIMIT_CHILD_SLIPPAGE_SET" | "SLIPPAGE_BOUNDS_CONFLICT" | "TWAP_INTERVAL_INVALID" | "LADDER_LEVEL_REJECTED" | "LADDER_RANGE_TOO_NARROW" | "LADDER_LEVELS_INVALID" | "ORDER_LIMITS_UNAVAILABLE" | "ORDER_TYPE_NOT_ALLOWED_IN_AUCTION" | "POST_ONLY_NOT_ALLOWED_IN_AUCTION" | "QUICKSWAP_FEE_DETAILS_INCOMPLETE" | "QUICKSWAP_MARKET_NOT_PRICED" | "QUICKSWAP_BROKER_FEE_TERMS_MISMATCH" | "QUICKSWAP_FEE_RECIPIENT_IS_PAYER" | "QUICKSWAP_BROKER_FEE_TERMS_UNAVAILABLE" | "QUICKSWAP_BROKER_ACCOUNT_UNAVAILABLE" | "QUICKSWAP_ACCOUNT_OWNER_UNKNOWN" | "QUICKSWAP_DISABLED" | "QUICKSWAP_ATTACHED_RISK_NOT_ALLOWED" | "QUICKSWAP_ORDER_NOT_MODIFIABLE" | "QUICKSWAP_FEE_TOTAL_TOO_HIGH" | "QUICKSWAP_BROKER_FEE_TERMS_INVALID" | "QUICKSWAP_BROKER_INVALID" | "QUICKSWAP_FEE_SCHEDULE_INVALID" | "QUICKSWAP_MARKET_FEE_INVALID" | "QUICKSWAP_SETUP_INVALID" | "QUICKSWAP_CAPACITY_REACHED" | "ATTACHED_EXIT_WORKING" | "MARKET_TRIGGER_LIMIT_EXCEEDED" | "MARKET_TWAP_LIMIT_EXCEEDED" | "MARKET_LADDER_LIMIT_EXCEEDED" | "CHILD_QTY_EXCEEDS_REMAINING" | "ORDER_CANCEL_OUTCOME_UNKNOWN" | "ORDER_MODIFY_OUTCOME_UNKNOWN" | "ORDER_REPAIRING" | "ACCOUNT_REPAIRING" | "TRIGGER_WOULD_TRIGGER_IMMEDIATELY" | "ORDER_CREATE_OUTCOME_UNKNOWN" | "TRIGGER_CREATE_OUTCOME_UNKNOWN" | "TRIGGER_SYMBOL_MISMATCH" | "MAX_OPEN_ORDERS_PER_PAIR" | "SELF_TRADE_PREVENTED" | "ATTACHED_LEGS_EXCEEDED" | "FEE_ASSET_INVALID" | "FEE_CEILING_INVALID" | "UNSUPPORTED_FIELD_SET" | "TRIGGER_FIRE_LIMIT_REACHED" | "CONDITION_FLAGS_INVALID" | "CONDITION_PARAMETER_SET" | "TWAP_CAPACITY_REACHED" | "CHILD_ORDER_INCONSISTENT" | "PATH_BODY_ID_MISMATCH" | "REQUEST_DEADLINE_EXCEEDED" | "ICEBERG_NOT_ALLOWED" | "ICEBERG_DISPLAY_TOO_SMALL" | "ICEBERG_DISPLAY_INVALID" | "PEG_LIMIT_VIOLATION" | "PEG_REFERENCE_UNAVAILABLE" | "INVALID_PEG">]>;
6
+ readonly code: v.SchemaWithPipe<readonly [v.EnumSchema<typeof ErrorCode, undefined>, v.TransformAction<ErrorCode, "STALE_QUOTE" | "UNSPECIFIED" | "BAD_REQUEST" | "INVALID_ARGUMENT" | "INSUFFICIENT_FUNDS" | "UNKNOWN_SYMBOL" | "BAD_PRICE" | "BAD_QTY" | "MIN_NOTIONAL" | "QTY_STEP_SIZE" | "CONFLICT_DUPLICATE_CLIENT_ORDER_ID" | "UNAVAILABLE" | "UNAUTHENTICATED" | "PERMISSION_DENIED" | "NOT_FOUND" | "UPSTREAM_ERROR" | "FEE_ASSET_NOT_ALLOWED" | "PAIR_DISABLED" | "ORDER_UNKNOWN" | "INTERNAL_ERROR" | "SUBACCOUNT_INACTIVE" | "POLICY_MARKET_DENY" | "POLICY_MAX_NOTIONAL" | "POLICY_TRADING_HALTED" | "POLICY_SPOT_TRADE_DENY" | "API_KEY_ROOT_SCOPE_ONLY" | "API_KEY_SUB_SCOPE_ONLY" | "API_KEY_SUBACCOUNT_MISMATCH" | "API_KEY_POLICY_REQUIRED" | "API_KEY_UNKNOWN" | "API_KEY_MARKET_DENY" | "API_KEY_SPOT_TRADE_DENY" | "PRICE_TICK_SIZE" | "MIN_QTY" | "POST_ONLY_LIMIT_ONLY" | "BATCH_TOO_LARGE" | "POLICY_MAX_OPEN_ORDERS" | "MODIFICATION_REQUIRES_REPLACE" | "CONFLICT_IDEMPOTENCY_KEY_REUSE" | "MARKET_PRICE_UNAVAILABLE" | "PAIR_NOT_LISTED_YET" | "PAIR_DELISTED" | "PAIR_CANCEL_ONLY" | "PAIR_POST_ONLY" | "PAIR_REDUCE_ONLY" | "RISK_LIMIT" | "MARKET_HALTED" | "ACCOUNT_UNKNOWN" | "POST_ONLY_CROSS" | "REDUCE_ONLY_BLOCKED" | "PRICE_BAND_VIOLATION" | "MARKET_CAP_VIOLATION" | "EMPTY_BOOK" | "FOK_INSUFFICIENT_LIQUIDITY" | "ORDER_ALREADY_TERMINAL" | "TRIGGER_PRICE_INVALID" | "TRIGGER_PRICE_SOURCE_UNSUPPORTED" | "TRAILING_DISTANCE_INVALID" | "TRIGGER_NOT_FOUND" | "TRIGGER_STATUS_INVALID" | "TRIGGER_NOT_MODIFIABLE" | "CONFLICT_DUPLICATE_CLIENT_TRIGGER_ID" | "MAX_SLIPPAGE_INVALID" | "VALIDATION_ERROR" | "OVERLOADED" | "QUOTE_SIZE_TOO_SMALL" | "RATE_LIMIT_EXCEEDED" | "SUBACCOUNT_READ_FORBIDDEN" | "POLICY_SPOT_READ_DENY" | "API_KEY_SPOT_READ_DENY" | "CANCEL_REQUEST_EXPIRED" | "MAX_QTY" | "MAX_NOTIONAL" | "QTY_AT_OR_BELOW_FILLED" | "GATEWAY_MISCONFIGURED" | "INVALID_ORDER_ID" | "CHILD_QTY_RAISE_NOT_ALLOWED" | "ATTACHED_RISK_NOT_SUPPORTED" | "SETTLEMENT_BACKLOGGED" | "PRICE_LEVEL_QUANTITY_LIMIT" | "MARKET_QUOTE_STALE" | "MARKET_QUOTE_UNHEALTHY" | "INVALID_TIME_IN_FORCE" | "QUICKSWAP_NOT_PERMITTED" | "DUPLICATE_ORDER_ID" | "MAX_OPEN_ORDERS_TOTAL" | "STP_MODE_NOT_ALLOWED" | "PAIR_BACKLOGGED" | "PRICE_LEVELS_EXHAUSTED" | "CLIENT_ORDER_IDS_EXHAUSTED" | "ORDER_ID_CONFLICT" | "INVALID_SIDE" | "INVALID_ORDER_TYPE" | "INVALID_STP_MODE" | "INVALID_ORDER_FLAGS" | "BATCH_OTHER_ITEM_INVALID" | "REPLACE_ONTO_OWN_ID" | "INVALID_CLIENT_ORDER_ID" | "ORDER_SEQUENCE_EXHAUSTED" | "INVALID_HANDLING_MODE" | "FEE_SCHEDULE_UNAVAILABLE" | "POLICY_UNAVAILABLE" | "CANCEL_ALL_AFTER_TIMEOUT_INVALID" | "CANCEL_SCOPE_TOO_LARGE" | "RATE_LIMIT_POLICY_UNAVAILABLE" | "SYSTEM_RATE_LIMITED" | "ORDER_MODIFY_IN_PROGRESS" | "ORDER_PLACEMENT_PENDING" | "INVALID_MODIFY_BEHAVIOR" | "BATCH_REPLACE_ONLY_REQUIRED" | "BATCH_SINGLE_SYMBOL_REQUIRED" | "REQUEST_RECEIPTS_EXHAUSTED" | "INTENT_ID_INVALID" | "DRY_RUN_INVALID" | "CANCEL_ALL_AFTER_SCOPE_CONFLICT" | "NEW_ACCOUNT_CAPACITY_REACHED" | "TRIGGER_CHILD_PRICE_NOT_MODIFIABLE" | "TRIGGER_GENERATIONS_EXHAUSTED" | "TRIGGER_CONTROL_SHARE_EXHAUSTED" | "TRIGGER_CONTROLS_BUSY" | "TRIGGER_TYPE_NOT_SUPPORTED" | "INVALID_TRIGGER_TYPE" | "TRIGGER_DIRECTION_INVALID" | "TRIGGER_QTY_INVALID" | "TRIGGER_BUY_REQUIRES_LIMIT" | "ACCOUNT_ROUTING_INVALID" | "TRIGGER_LIMIT_EXCEEDED" | "TRIGGER_CONTROL_IN_PROGRESS" | "TRIGGER_PATCH_EMPTY" | "CLIENT_TRIGGER_ID_INVALID" | "TRIGGER_ACTIVATION_PRICE_INVALID" | "SLIPPAGE_TICKS_INVALID" | "SLIPPAGE_BPS_INVALID" | "TRIGGER_CONTROL_OUTCOME_UNKNOWN" | "TRIGGER_CAPACITY_REACHED" | "RESERVATION_CAPACITY_REACHED" | "CLIENT_ORDER_ID_CAPACITY_REACHED" | "ACCOUNT_RESERVATION_LIMIT_REACHED" | "INVALID_TRIGGER_CONTROL" | "TRIGGER_PATCH_NOT_ALLOWED" | "TRIGGER_PATCH_FIELD_UNKNOWN" | "TRIGGER_PATCH_VALUE_UNMASKED" | "TRIGGER_PATCH_PRICE_MODE_INVALID" | "ACCOUNT_ORDERS_SUSPENDED" | "TRAILING_SIDE_NOT_SUPPORTED" | "TRAILING_CHILD_NOT_MARKET" | "TWAP_DURATION_INVALID" | "LIMIT_CHILD_SLIPPAGE_SET" | "SLIPPAGE_BOUNDS_CONFLICT" | "TWAP_INTERVAL_INVALID" | "LADDER_LEVEL_REJECTED" | "LADDER_RANGE_TOO_NARROW" | "LADDER_LEVELS_INVALID" | "ORDER_LIMITS_UNAVAILABLE" | "ORDER_TYPE_NOT_ALLOWED_IN_AUCTION" | "POST_ONLY_NOT_ALLOWED_IN_AUCTION" | "QUICKSWAP_FEE_DETAILS_INCOMPLETE" | "QUICKSWAP_MARKET_NOT_PRICED" | "QUICKSWAP_BROKER_FEE_TERMS_MISMATCH" | "QUICKSWAP_FEE_RECIPIENT_IS_PAYER" | "QUICKSWAP_BROKER_FEE_TERMS_UNAVAILABLE" | "QUICKSWAP_BROKER_ACCOUNT_UNAVAILABLE" | "QUICKSWAP_ACCOUNT_OWNER_UNKNOWN" | "QUICKSWAP_DISABLED" | "QUICKSWAP_ATTACHED_RISK_NOT_ALLOWED" | "QUICKSWAP_ORDER_NOT_MODIFIABLE" | "QUICKSWAP_FEE_TOTAL_TOO_HIGH" | "QUICKSWAP_BROKER_FEE_TERMS_INVALID" | "QUICKSWAP_BROKER_INVALID" | "QUICKSWAP_FEE_SCHEDULE_INVALID" | "QUICKSWAP_MARKET_FEE_INVALID" | "QUICKSWAP_SETUP_INVALID" | "QUICKSWAP_CAPACITY_REACHED" | "ATTACHED_EXIT_WORKING" | "MARKET_TRIGGER_LIMIT_EXCEEDED" | "MARKET_TWAP_LIMIT_EXCEEDED" | "MARKET_LADDER_LIMIT_EXCEEDED" | "CHILD_QTY_EXCEEDS_REMAINING" | "ORDER_CANCEL_OUTCOME_UNKNOWN" | "ORDER_MODIFY_OUTCOME_UNKNOWN" | "ORDER_REPAIRING" | "ACCOUNT_REPAIRING" | "TRIGGER_WOULD_TRIGGER_IMMEDIATELY" | "ORDER_CREATE_OUTCOME_UNKNOWN" | "TRIGGER_CREATE_OUTCOME_UNKNOWN" | "TRIGGER_SYMBOL_MISMATCH" | "MAX_OPEN_ORDERS_PER_PAIR" | "SELF_TRADE_PREVENTED" | "ATTACHED_LEGS_EXCEEDED" | "FEE_ASSET_INVALID" | "FEE_CEILING_INVALID" | "UNSUPPORTED_FIELD_SET" | "TRIGGER_FIRE_LIMIT_REACHED" | "CONDITION_FLAGS_INVALID" | "CONDITION_PARAMETER_SET" | "TWAP_CAPACITY_REACHED" | "CHILD_ORDER_INCONSISTENT" | "PATH_BODY_ID_MISMATCH" | "REQUEST_DEADLINE_EXCEEDED" | "ICEBERG_NOT_ALLOWED" | "ICEBERG_DISPLAY_TOO_SMALL" | "ICEBERG_DISPLAY_INVALID" | "PEG_LIMIT_VIOLATION" | "PEG_REFERENCE_UNAVAILABLE" | "INVALID_PEG" | "TRIGGER_ACTIVATION_PRICE_NOT_MODIFIABLE">]>;
7
7
  readonly violations: v.ArraySchema<v.ObjectSchema<{
8
8
  readonly fieldPath: v.StringSchema<undefined>;
9
9
  readonly ruleId: v.StringSchema<undefined>;
@@ -1,5 +1,5 @@
1
- import { ErrorCode } from "../../gen/orders/v1/orders_pb.js";
2
1
  import { OptionalPublicIdSchema } from "../../shared/schemas.js";
2
+ import { ErrorCode } from "../../gen/orders/v1/orders_pb.js";
3
3
  import { RateLimitDetailSchema } from "../../shared/rate-limit.schemas.js";
4
4
  import * as v from "valibot";
5
5
  //#region src/services/orders/order-errors.schemas.ts