@polyester/sdk 0.36.0-devnet-20261118184607 → 0.36.0-devnet-20261119010940

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 (219) hide show
  1. package/CHANGELOG.md +28 -2
  2. package/dist/client.d.ts +2 -0
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +2 -0
  5. package/dist/client.js.map +1 -1
  6. package/dist/gen/ai/v1/assistant_pb.d.ts +5 -6
  7. package/dist/gen/ai/v1/assistant_pb.d.ts.map +1 -1
  8. package/dist/gen/ai/v1/assistant_pb.js.map +1 -1
  9. package/dist/gen/auth/v1/address_book_pb.d.ts +1 -1
  10. package/dist/gen/auth/v1/address_book_pb.js +1 -1
  11. package/dist/gen/auth/v1/address_book_pb.js.map +1 -1
  12. package/dist/gen/auth/v1/api_keys_pb.d.ts +70 -9
  13. package/dist/gen/auth/v1/api_keys_pb.d.ts.map +1 -1
  14. package/dist/gen/auth/v1/api_keys_pb.js +16 -1
  15. package/dist/gen/auth/v1/api_keys_pb.js.map +1 -1
  16. package/dist/gen/auth/v1/auth_pb.d.ts +74 -5
  17. package/dist/gen/auth/v1/auth_pb.d.ts.map +1 -1
  18. package/dist/gen/auth/v1/auth_pb.js +58 -6
  19. package/dist/gen/auth/v1/auth_pb.js.map +1 -1
  20. package/dist/gen/auth/v1/connected_apps_pb.d.ts +382 -0
  21. package/dist/gen/auth/v1/connected_apps_pb.d.ts.map +1 -0
  22. package/dist/gen/auth/v1/connected_apps_pb.js +107 -0
  23. package/dist/gen/auth/v1/connected_apps_pb.js.map +1 -0
  24. package/dist/gen/auth/v1/mfa_pb.d.ts +2 -140
  25. package/dist/gen/auth/v1/mfa_pb.d.ts.map +1 -1
  26. package/dist/gen/auth/v1/mfa_pb.js +8 -80
  27. package/dist/gen/auth/v1/mfa_pb.js.map +1 -1
  28. package/dist/gen/auth/v1/policies_pb.d.ts +164 -41
  29. package/dist/gen/auth/v1/policies_pb.d.ts.map +1 -1
  30. package/dist/gen/auth/v1/policies_pb.js +36 -3
  31. package/dist/gen/auth/v1/policies_pb.js.map +1 -1
  32. package/dist/gen/auth/v1/social_verification_pb.d.ts +4 -4
  33. package/dist/gen/auth/v1/social_verification_pb.js.map +1 -1
  34. package/dist/gen/chain/lifecycle/v1/lifecycle_read_pb.d.ts +17 -10
  35. package/dist/gen/chain/lifecycle/v1/lifecycle_read_pb.d.ts.map +1 -1
  36. package/dist/gen/chain/lifecycle/v1/lifecycle_read_pb.js.map +1 -1
  37. package/dist/gen/chain/withdraw/v1/withdraw_pb.d.ts +3 -1
  38. package/dist/gen/chain/withdraw/v1/withdraw_pb.d.ts.map +1 -1
  39. package/dist/gen/chain/withdraw/v1/withdraw_pb.js.map +1 -1
  40. package/dist/gen/fees/v1/fees_pb.d.ts +2 -1
  41. package/dist/gen/fees/v1/fees_pb.d.ts.map +1 -1
  42. package/dist/gen/fees/v1/fees_pb.js.map +1 -1
  43. package/dist/gen/index.d.ts +8 -5
  44. package/dist/gen/index.js +8 -5
  45. package/dist/gen/ledger/read/v1/ledger_read_pb.d.ts +3 -2
  46. package/dist/gen/ledger/read/v1/ledger_read_pb.d.ts.map +1 -1
  47. package/dist/gen/ledger/read/v1/ledger_read_pb.js.map +1 -1
  48. package/dist/gen/marketdata/v1/heatmap_pb.d.ts +9 -58
  49. package/dist/gen/marketdata/v1/heatmap_pb.d.ts.map +1 -1
  50. package/dist/gen/marketdata/v1/heatmap_pb.js +8 -57
  51. package/dist/gen/marketdata/v1/heatmap_pb.js.map +1 -1
  52. package/dist/gen/notifications/v1/notifications_pb.d.ts +141 -4
  53. package/dist/gen/notifications/v1/notifications_pb.d.ts.map +1 -1
  54. package/dist/gen/notifications/v1/notifications_pb.js +94 -16
  55. package/dist/gen/notifications/v1/notifications_pb.js.map +1 -1
  56. package/dist/gen/orderbook/v1/orderbook_pb.d.ts +14 -12
  57. package/dist/gen/orderbook/v1/orderbook_pb.d.ts.map +1 -1
  58. package/dist/gen/orderbook/v1/orderbook_pb.js +6 -1
  59. package/dist/gen/orderbook/v1/orderbook_pb.js.map +1 -1
  60. package/dist/gen/orders/v1/orders_pb.d.ts +66 -18
  61. package/dist/gen/orders/v1/orders_pb.d.ts.map +1 -1
  62. package/dist/gen/orders/v1/orders_pb.js +1 -1
  63. package/dist/gen/orders/v1/orders_pb.js.map +1 -1
  64. package/dist/gen/orders/v1/orders_read_pb.d.ts +8 -0
  65. package/dist/gen/orders/v1/orders_read_pb.d.ts.map +1 -1
  66. package/dist/gen/orders/v1/orders_read_pb.js.map +1 -1
  67. package/dist/gen/polyester/api/options_pb.d.ts +2 -1
  68. package/dist/gen/polyester/api/options_pb.d.ts.map +1 -1
  69. package/dist/gen/polyester/api/options_pb.js +2 -1
  70. package/dist/gen/polyester/api/options_pb.js.map +1 -1
  71. package/dist/gen/polyester/api/v1/request_error_pb.d.ts +66 -0
  72. package/dist/gen/polyester/api/v1/request_error_pb.d.ts.map +1 -0
  73. package/dist/gen/polyester/api/v1/request_error_pb.js +49 -0
  74. package/dist/gen/polyester/api/v1/request_error_pb.js.map +1 -0
  75. package/dist/gen/polyester/type/v1/depth_tier_pb.d.ts +98 -0
  76. package/dist/gen/polyester/type/v1/depth_tier_pb.d.ts.map +1 -0
  77. package/dist/gen/polyester/type/v1/depth_tier_pb.js +104 -0
  78. package/dist/gen/polyester/type/v1/depth_tier_pb.js.map +1 -0
  79. package/dist/gen/ratelimit/v1/ratelimit_pb.d.ts +42 -23
  80. package/dist/gen/ratelimit/v1/ratelimit_pb.d.ts.map +1 -1
  81. package/dist/gen/ratelimit/v1/ratelimit_pb.js +14 -2
  82. package/dist/gen/ratelimit/v1/ratelimit_pb.js.map +1 -1
  83. package/dist/gen/swap/quickswap/v1/quickswap_pb.d.ts +126 -13
  84. package/dist/gen/swap/quickswap/v1/quickswap_pb.d.ts.map +1 -1
  85. package/dist/gen/swap/quickswap/v1/quickswap_pb.js +100 -28
  86. package/dist/gen/swap/quickswap/v1/quickswap_pb.js.map +1 -1
  87. package/dist/gen/transfer/v1/internal_transfer_pb.d.ts +5 -3
  88. package/dist/gen/transfer/v1/internal_transfer_pb.d.ts.map +1 -1
  89. package/dist/gen/transfer/v1/internal_transfer_pb.js.map +1 -1
  90. package/dist/gen/triggers/v1/triggers_pb.d.ts +25 -3
  91. package/dist/gen/triggers/v1/triggers_pb.d.ts.map +1 -1
  92. package/dist/gen/triggers/v1/triggers_pb.js +18 -1
  93. package/dist/gen/triggers/v1/triggers_pb.js.map +1 -1
  94. package/dist/index.d.ts +5 -3
  95. package/dist/services/account-activity/account-activity.schemas.d.ts +2 -2
  96. package/dist/services/address-book/address-book.js +1 -1
  97. package/dist/services/address-book/address-book.schemas.d.ts +2 -2
  98. package/dist/services/api-keys/api-keys.codecs.d.ts +6 -1
  99. package/dist/services/api-keys/api-keys.codecs.d.ts.map +1 -1
  100. package/dist/services/api-keys/api-keys.codecs.js +19 -7
  101. package/dist/services/api-keys/api-keys.codecs.js.map +1 -1
  102. package/dist/services/api-keys/api-keys.js +1 -1
  103. package/dist/services/api-keys/api-keys.schemas.d.ts +12 -4
  104. package/dist/services/api-keys/api-keys.schemas.d.ts.map +1 -1
  105. package/dist/services/api-keys/api-keys.schemas.js +15 -6
  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 -2
  108. package/dist/services/assistant/assistant-events.schemas.d.ts +25 -25
  109. package/dist/services/assistant/assistant.schemas.d.ts +1 -1
  110. package/dist/services/auth/auth.d.ts +4 -0
  111. package/dist/services/auth/auth.d.ts.map +1 -1
  112. package/dist/services/auth/auth.js +12 -2
  113. package/dist/services/auth/auth.js.map +1 -1
  114. package/dist/services/balances/balances.js +1 -1
  115. package/dist/services/changelog/changelog.schemas.d.ts +38 -38
  116. package/dist/services/claims/claims.schemas.d.ts +2 -2
  117. package/dist/services/connected-apps/connected-apps.d.ts +46 -0
  118. package/dist/services/connected-apps/connected-apps.d.ts.map +1 -0
  119. package/dist/services/connected-apps/connected-apps.js +69 -0
  120. package/dist/services/connected-apps/connected-apps.js.map +1 -0
  121. package/dist/services/connected-apps/connected-apps.schemas.d.ts +132 -0
  122. package/dist/services/connected-apps/connected-apps.schemas.d.ts.map +1 -0
  123. package/dist/services/connected-apps/connected-apps.schemas.js +68 -0
  124. package/dist/services/connected-apps/connected-apps.schemas.js.map +1 -0
  125. package/dist/services/connected-apps/connected-apps.types.d.ts +2 -0
  126. package/dist/services/connected-apps/service.d.ts +8 -0
  127. package/dist/services/connected-apps/service.d.ts.map +1 -0
  128. package/dist/services/connected-apps/service.js +9 -0
  129. package/dist/services/connected-apps/service.js.map +1 -0
  130. package/dist/services/dust-conversion/dust-conversion.schemas.d.ts +2 -2
  131. package/dist/services/heatmap/heatmap.codecs.d.ts +1 -0
  132. package/dist/services/heatmap/heatmap.codecs.d.ts.map +1 -1
  133. package/dist/services/heatmap/heatmap.codecs.js +2 -27
  134. package/dist/services/heatmap/heatmap.codecs.js.map +1 -1
  135. package/dist/services/heatmap/heatmap.schemas.d.ts +9 -8
  136. package/dist/services/heatmap/heatmap.schemas.d.ts.map +1 -1
  137. package/dist/services/heatmap/heatmap.schemas.js +4 -3
  138. package/dist/services/heatmap/heatmap.schemas.js.map +1 -1
  139. package/dist/services/internal-transfers/internal-transfers.schemas.d.ts +2 -2
  140. package/dist/services/lifecycle/lifecycle.schemas.d.ts +52 -52
  141. package/dist/services/notifications/notifications.codecs.d.ts +6 -3
  142. package/dist/services/notifications/notifications.codecs.d.ts.map +1 -1
  143. package/dist/services/notifications/notifications.codecs.js +14 -3
  144. package/dist/services/notifications/notifications.codecs.js.map +1 -1
  145. package/dist/services/notifications/notifications.schemas.d.ts +97 -3
  146. package/dist/services/notifications/notifications.schemas.d.ts.map +1 -1
  147. package/dist/services/notifications/notifications.schemas.js +18 -1
  148. package/dist/services/notifications/notifications.schemas.js.map +1 -1
  149. package/dist/services/notifications/notifications.types.d.ts +2 -2
  150. package/dist/services/orderbook/orderbook.codecs.js +1 -1
  151. package/dist/services/orderbook/orderbook.codecs.js.map +1 -1
  152. package/dist/services/orderbook/orderbook.d.ts +2 -2
  153. package/dist/services/orderbook/orderbook.d.ts.map +1 -1
  154. package/dist/services/orderbook/orderbook.js +7 -9
  155. package/dist/services/orderbook/orderbook.js.map +1 -1
  156. package/dist/services/orderbook/orderbook.schemas.d.ts +3 -6
  157. package/dist/services/orderbook/orderbook.schemas.d.ts.map +1 -1
  158. package/dist/services/orderbook/orderbook.schemas.js +5 -5
  159. package/dist/services/orderbook/orderbook.schemas.js.map +1 -1
  160. package/dist/services/orders/order-errors.schemas.d.ts +6 -6
  161. package/dist/services/orders/orders-batch.schemas.d.ts +78 -74
  162. package/dist/services/orders/orders-batch.schemas.d.ts.map +1 -1
  163. package/dist/services/orders/orders-batch.schemas.js +2 -0
  164. package/dist/services/orders/orders-batch.schemas.js.map +1 -1
  165. package/dist/services/orders/orders-input.schemas.d.ts +18 -10
  166. package/dist/services/orders/orders-input.schemas.d.ts.map +1 -1
  167. package/dist/services/orders/orders-input.schemas.js +7 -2
  168. package/dist/services/orders/orders-input.schemas.js.map +1 -1
  169. package/dist/services/orders/orders-output.schemas.d.ts +14 -14
  170. package/dist/services/policies/api-key-policies/api-key-policies.d.ts +4 -1
  171. package/dist/services/policies/api-key-policies/api-key-policies.d.ts.map +1 -1
  172. package/dist/services/policies/api-key-policies/api-key-policies.js +5 -2
  173. package/dist/services/policies/api-key-policies/api-key-policies.js.map +1 -1
  174. package/dist/services/policies/api-key-policies/api-key-policies.schemas.d.ts +25 -15
  175. package/dist/services/policies/api-key-policies/api-key-policies.schemas.d.ts.map +1 -1
  176. package/dist/services/policies/api-key-policies/api-key-policies.schemas.js +3 -0
  177. package/dist/services/policies/api-key-policies/api-key-policies.schemas.js.map +1 -1
  178. package/dist/services/policies/shared.codecs.js +25 -5
  179. package/dist/services/policies/shared.codecs.js.map +1 -1
  180. package/dist/services/policies/shared.d.ts +1 -1
  181. package/dist/services/policies/subaccount-policies/subaccount-policies.d.ts +4 -1
  182. package/dist/services/policies/subaccount-policies/subaccount-policies.d.ts.map +1 -1
  183. package/dist/services/policies/subaccount-policies/subaccount-policies.js +5 -2
  184. package/dist/services/policies/subaccount-policies/subaccount-policies.js.map +1 -1
  185. package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.d.ts +11 -3
  186. package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.d.ts.map +1 -1
  187. package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.js +4 -0
  188. package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.js.map +1 -1
  189. package/dist/services/rate-limits/rate-limits.codecs.d.ts +1 -1
  190. package/dist/services/rate-limits/rate-limits.codecs.js +2 -1
  191. package/dist/services/rate-limits/rate-limits.codecs.js.map +1 -1
  192. package/dist/services/rate-limits/rate-limits.schemas.d.ts +4 -4
  193. package/dist/services/rewards/rewards.schemas.d.ts +4 -4
  194. package/dist/services/statement-exports/statement-exports.schemas.d.ts +6 -6
  195. package/dist/services/subaccounts/subaccounts.js +2 -2
  196. package/dist/services/subaccounts/subaccounts.schemas.d.ts +22 -22
  197. package/dist/services/system/system.schemas.d.ts +13 -13
  198. package/dist/services/trades/trades.schemas.d.ts +1 -1
  199. package/dist/services/transfers/transfers.js +1 -1
  200. package/dist/services/triggers/trigger-input.schemas.d.ts +1 -1
  201. package/dist/services/triggers/triggers-output.schemas.d.ts +43 -43
  202. package/dist/services/triggers/triggers.codecs.d.ts.map +1 -1
  203. package/dist/services/triggers/triggers.codecs.js +2 -0
  204. package/dist/services/triggers/triggers.codecs.js.map +1 -1
  205. package/dist/shared/connect-error-mapping.d.ts.map +1 -1
  206. package/dist/shared/connect-error-mapping.js +1 -1
  207. package/dist/shared/connect-error-mapping.js.map +1 -1
  208. package/dist/shared/depth-tier.js +46 -0
  209. package/dist/shared/depth-tier.js.map +1 -0
  210. package/dist/shared/error-detail.d.ts +6 -0
  211. package/dist/shared/error-detail.d.ts.map +1 -1
  212. package/dist/shared/error-detail.js +2 -1
  213. package/dist/shared/error-detail.js.map +1 -1
  214. package/dist/shared/error-details/request.js +16 -0
  215. package/dist/shared/error-details/request.js.map +1 -0
  216. package/dist/wired-services.d.ts.map +1 -1
  217. package/dist/wired-services.js +6 -4
  218. package/dist/wired-services.js.map +1 -1
  219. package/package.json +1 -1
@@ -56,7 +56,7 @@ declare const MarkAllNotificationsReadInputSchema: v.StrictObjectSchema<{
56
56
  type MarkAllNotificationsReadInput = v.InferInput<typeof MarkAllNotificationsReadInputSchema>;
57
57
  declare function formatNotification(notification: Notification): {
58
58
  notificationId: string;
59
- type: "unspecified" | "price_alert" | "telegram_approval" | "broker_allowlist_change" | "telegram_linked";
59
+ type: "unspecified" | "price_alert" | "telegram_approval" | "broker_allowlist_change" | "telegram_linked" | "admin_key_action";
60
60
  category: "unspecified" | "security" | "alerts";
61
61
  /** Plain-text title, the same for every notification of a type. */
62
62
  title: string;
@@ -104,11 +104,20 @@ declare function formatNotification(notification: Notification): {
104
104
  */
105
105
  requestedByAccountId?: undefined;
106
106
  linkedAt?: undefined;
107
+ adminKeyId?: undefined;
108
+ /** The API key changed; empty for a sub-account policy change. */
109
+ keyId?: undefined;
110
+ /** Null for the main account, or for a sub-account policy update. */
111
+ subaccountId?: undefined;
112
+ /** API key policy for `set_api_key_policy`, sub-account policy for the sub-account actions; null when none. */
113
+ policyId?: undefined;
114
+ sourceIp?: undefined;
115
+ changedAt?: undefined;
107
116
  } | {
108
117
  type: "telegram_approval";
109
118
  /** The approval's ID in `client.assistant`. */
110
119
  approvalId: string;
111
- action: "unspecified" | "place_order" | "place_orders" | "modify_orders" | "cancel_order" | "cancel_all_orders" | "modify_trigger" | "pause_trigger" | "resume_trigger" | "swap";
120
+ action: "unspecified" | "place_order" | "place_orders" | "modify_orders" | "cancel_order" | "cancel_all_orders" | "modify_trigger" | "pause_trigger" | "resume_trigger" | "swap" | "convert_dust";
112
121
  /** Trading account (subaccount) the action acted on. */
113
122
  accountId: string;
114
123
  summary: string;
@@ -146,6 +155,15 @@ declare function formatNotification(notification: Notification): {
146
155
  */
147
156
  requestedByAccountId?: undefined;
148
157
  linkedAt?: undefined;
158
+ adminKeyId?: undefined;
159
+ /** The API key changed; empty for a sub-account policy change. */
160
+ keyId?: undefined;
161
+ /** Null for the main account, or for a sub-account policy update. */
162
+ subaccountId?: undefined;
163
+ /** API key policy for `set_api_key_policy`, sub-account policy for the sub-account actions; null when none. */
164
+ policyId?: undefined;
165
+ sourceIp?: undefined;
166
+ changedAt?: undefined;
149
167
  } | {
150
168
  type: "broker_allowlist_change";
151
169
  broker: string;
@@ -185,6 +203,15 @@ declare function formatNotification(notification: Notification): {
185
203
  parameters?: undefined;
186
204
  approvedAt?: undefined;
187
205
  linkedAt?: undefined;
206
+ adminKeyId?: undefined;
207
+ /** The API key changed; empty for a sub-account policy change. */
208
+ keyId?: undefined;
209
+ /** Null for the main account, or for a sub-account policy update. */
210
+ subaccountId?: undefined;
211
+ /** API key policy for `set_api_key_policy`, sub-account policy for the sub-account actions; null when none. */
212
+ policyId?: undefined;
213
+ sourceIp?: undefined;
214
+ changedAt?: undefined;
188
215
  } | {
189
216
  /** A Telegram account was linked; if the caller did not link it, unlink it. */
190
217
  type: "telegram_linked";
@@ -225,6 +252,64 @@ declare function formatNotification(notification: Notification): {
225
252
  * after it is listed.
226
253
  */
227
254
  requestedByAccountId?: undefined;
255
+ adminKeyId?: undefined;
256
+ /** The API key changed; empty for a sub-account policy change. */
257
+ keyId?: undefined;
258
+ /** Null for the main account, or for a sub-account policy update. */
259
+ subaccountId?: undefined;
260
+ /** API key policy for `set_api_key_policy`, sub-account policy for the sub-account actions; null when none. */
261
+ policyId?: undefined;
262
+ sourceIp?: undefined;
263
+ changedAt?: undefined;
264
+ } | {
265
+ /** An admin API key changed a key or policy; if nobody on the account did, revoke it. */
266
+ type: "admin_key_action";
267
+ adminKeyId: string;
268
+ action: "unspecified" | "create_api_key" | "update_api_key" | "delete_api_key" | "set_api_key_policy" | "set_subaccount_policy" | "update_subaccount_policy";
269
+ /** The API key changed; empty for a sub-account policy change. */
270
+ keyId: string;
271
+ /** Null for the main account, or for a sub-account policy update. */
272
+ subaccountId: string | null;
273
+ /** API key policy for `set_api_key_policy`, sub-account policy for the sub-account actions; null when none. */
274
+ policyId: string | null;
275
+ sourceIp: string;
276
+ changedAt: number | null;
277
+ /** The alert's ID in `client.priceAlerts`. */
278
+ alertId?: undefined;
279
+ symbolId?: undefined;
280
+ direction?: undefined;
281
+ priceSource?: undefined;
282
+ /** Alert price, as a decimal string. */
283
+ price?: undefined;
284
+ /** Price that fired the alert, as a decimal string. */
285
+ triggeredPrice?: undefined;
286
+ triggeredAt?: undefined;
287
+ /** The approval's ID in `client.assistant`. */
288
+ approvalId?: undefined;
289
+ /** Trading account (subaccount) the action acted on. */
290
+ accountId?: undefined;
291
+ summary?: undefined;
292
+ /** Key parameters in display order, such as market, side and quantity. */
293
+ parameters?: undefined;
294
+ approvedAt?: undefined;
295
+ broker?: undefined;
296
+ /** Sub-account ID of the broker vault. */
297
+ vaultAccountId?: undefined;
298
+ /** The change's ID; key the broker's vault allowlist view on it. */
299
+ changeId?: undefined;
300
+ event?: undefined;
301
+ /** Destination chain ID, as a decimal string. */
302
+ destinationChainId?: undefined;
303
+ destinationAddress?: undefined;
304
+ /** The requesting member's name for an added address; empty when none. */
305
+ label?: undefined;
306
+ /**
307
+ * Account ID of the member who requested the change. Show a `change_requested`
308
+ * the caller did not make prominently: an added address becomes payable 24 hours
309
+ * after it is listed.
310
+ */
311
+ requestedByAccountId?: undefined;
312
+ linkedAt?: undefined;
228
313
  } | {
229
314
  type: "unspecified";
230
315
  /** The alert's ID in `client.priceAlerts`. */
@@ -264,6 +349,15 @@ declare function formatNotification(notification: Notification): {
264
349
  */
265
350
  requestedByAccountId?: undefined;
266
351
  linkedAt?: undefined;
352
+ adminKeyId?: undefined;
353
+ /** The API key changed; empty for a sub-account policy change. */
354
+ keyId?: undefined;
355
+ /** Null for the main account, or for a sub-account policy update. */
356
+ subaccountId?: undefined;
357
+ /** API key policy for `set_api_key_policy`, sub-account policy for the sub-account actions; null when none. */
358
+ policyId?: undefined;
359
+ sourceIp?: undefined;
360
+ changedAt?: undefined;
267
361
  };
268
362
  };
269
363
  /**
@@ -282,7 +376,7 @@ declare function formatNotificationCounts(counts: GetNotificationCountsResponse)
282
376
  unread: number;
283
377
  /** Every type in ascending enum order, including types with no notification. */
284
378
  types: {
285
- type: "unspecified" | "price_alert" | "telegram_approval" | "broker_allowlist_change" | "telegram_linked";
379
+ type: "unspecified" | "price_alert" | "telegram_approval" | "broker_allowlist_change" | "telegram_linked" | "admin_key_action";
286
380
  category: "unspecified" | "security" | "alerts";
287
381
  total: number;
288
382
  unread: number;
@@ -1 +1 @@
1
- {"version":3,"file":"notifications.schemas.d.ts","names":[],"sources":["../../../src/services/notifications/notifications.schemas.ts"],"mappings":";;;cA2Ca,8BAA4B,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA2B7B,yBAAyB,EAAE,kBAAkB;cAE5C,4BAA0B,EAAA;;;KAI3B,uBAAuB,EAAE,kBAAkB;cAE1C,8BAA4B,EAAA;;;;KAU7B,yBAAyB,EAAE,kBAAkB;cAE5C,qCAAmC,EAAA;;;;;;;;KASpC,gCAAgC,EAAE,kBACnC;iBAkFK,mBAAmB,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAoBrC,sBAAsB,kBAAkB;KAExC,4BAA4B;;KAG5B;EACR,eAAe;EACf;;iBAGY,yBAAyB,QAAQ;;;;;;;;;;;;KAerC,qBAAqB,kBAAkB"}
1
+ {"version":3,"file":"notifications.schemas.d.ts","names":[],"sources":["../../../src/services/notifications/notifications.schemas.ts"],"mappings":";;;cA4Ca,8BAA4B,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA2B7B,yBAAyB,EAAE,kBAAkB;cAE5C,4BAA0B,EAAA;;;KAI3B,uBAAuB,EAAE,kBAAkB;cAE1C,8BAA4B,EAAA;;;;KAU7B,yBAAyB,EAAE,kBAAkB;cAE5C,qCAAmC,EAAA;;;;;;;;KASpC,gCAAgC,EAAE,kBACnC;iBAmGK,mBAAmB,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAoBrC,sBAAsB,kBAAkB;KAExC,4BAA4B;;KAG5B;EACR,eAAe;EACf;;iBAGY,yBAAyB,QAAQ;;;;;;;;;;;;KAerC,qBAAqB,kBAAkB"}
@@ -5,7 +5,7 @@ import { enumLabel } from "../../shared/proto-enum-codec.js";
5
5
  import { scaledToDecimalOutput } from "../../shared/decimal-surface.js";
6
6
  import { msToTimestamp } from "../../utils/timestamp.js";
7
7
  import { PriceAlertDirectionCodec, PriceAlertPriceSourceCodec } from "../price-alerts/price-alerts.codecs.js";
8
- import { BrokerAllowlistActionCodec, BrokerAllowlistEventCodec, NOTIFICATION_CATEGORY_VALUES, NOTIFICATION_READ_STATE_VALUES, NotificationCategoryCodec, NotificationReadStateCodec, NotificationTypeCodec, TelegramApprovalActionCodec } from "./notifications.codecs.js";
8
+ import { AdminKeyActionCodec, BrokerAllowlistActionCodec, BrokerAllowlistEventCodec, NOTIFICATION_CATEGORY_VALUES, NOTIFICATION_READ_STATE_VALUES, NotificationCategoryCodec, NotificationReadStateCodec, NotificationTypeCodec, TelegramApprovalActionCodec } from "./notifications.codecs.js";
9
9
  import * as v from "valibot";
10
10
  //#region src/services/notifications/notifications.schemas.ts
11
11
  const NotificationIdInputSchema = idInputSchema("notificationId");
@@ -108,6 +108,23 @@ function formatDetail(detail) {
108
108
  type: "telegram_linked",
109
109
  linkedAt: tsObjToMs(detail.value.linkedAt) ?? null
110
110
  };
111
+ case "adminKeyAction": {
112
+ const notice = detail.value;
113
+ return {
114
+ /** An admin API key changed a key or policy; if nobody on the account did, revoke it. */
115
+ type: "admin_key_action",
116
+ adminKeyId: notice.adminKeyId,
117
+ action: enumLabel(AdminKeyActionCodec.protoToOutput, notice.action),
118
+ /** The API key changed; empty for a sub-account policy change. */
119
+ keyId: notice.keyId,
120
+ /** Null for the main account, or for a sub-account policy update. */
121
+ subaccountId: notice.subaccountId === 0n ? null : formatId(notice.subaccountId),
122
+ /** API key policy for `set_api_key_policy`, sub-account policy for the sub-account actions; null when none. */
123
+ policyId: notice.policyId === 0n ? null : formatId(notice.policyId),
124
+ sourceIp: notice.sourceIp,
125
+ changedAt: tsObjToMs(notice.changedAt) ?? null
126
+ };
127
+ }
111
128
  default: return { type: "unspecified" };
112
129
  }
113
130
  }
@@ -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 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 case \"telegramLink\":\n return {\n /** A Telegram account was linked; if the caller did not link it, unlink it. */\n type: \"telegram_linked\" as const,\n linkedAt: tsObjToMs(detail.value.linkedAt) ?? null,\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,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Aa,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 AdminKeyActionCodec,\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 case \"telegramLink\":\n return {\n /** A Telegram account was linked; if the caller did not link it, unlink it. */\n type: \"telegram_linked\" as const,\n linkedAt: tsObjToMs(detail.value.linkedAt) ?? null,\n };\n case \"adminKeyAction\": {\n const notice = detail.value;\n return {\n /** An admin API key changed a key or policy; if nobody on the account did, revoke it. */\n type: \"admin_key_action\" as const,\n adminKeyId: notice.adminKeyId,\n action: enumLabel(AdminKeyActionCodec.protoToOutput, notice.action),\n /** The API key changed; empty for a sub-account policy change. */\n keyId: notice.keyId,\n /** Null for the main account, or for a sub-account policy update. */\n subaccountId: notice.subaccountId === 0n ? null : formatId(notice.subaccountId),\n /** API key policy for `set_api_key_policy`, sub-account policy for the sub-account actions; null when none. */\n policyId: notice.policyId === 0n ? null : formatId(notice.policyId),\n sourceIp: notice.sourceIp,\n changedAt: tsObjToMs(notice.changedAt) ?? 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":";;;;;;;;;;AAyBA,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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e,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 { 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 };
2
+ import { AdminKeyAction, BrokerAllowlistAction, BrokerAllowlistEvent, NotificationCategory, NotificationReadState, NotificationType, TelegramApprovalAction } from "./notifications.codecs.js";
3
+ export type { AccountNotification, AccountNotificationDetail, AdminKeyAction, BrokerAllowlistAction, BrokerAllowlistEvent, GetNotificationInput, ListNotificationsInput, ListNotificationsResult, MarkAllNotificationsReadInput, MarkNotificationsInput, NotificationCategory, NotificationCounts, NotificationReadState, NotificationType, TelegramApprovalAction };
@@ -1,7 +1,7 @@
1
1
  //#region src/services/orderbook/orderbook.codecs.ts
2
2
  /**
3
3
  * Depths for which the backend publishes `public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto`
4
- * channels. Narrower than the depths the REST snapshot accepts (1 to its `maxDepth`):
4
+ * channels. Narrower than the depth tiers the REST snapshot serves (`DEPTH_TIER_VALUES`):
5
5
  * subscribing to a depth outside this set succeeds and then never delivers a publication, so the book
6
6
  * silently stays empty.
7
7
  */
@@ -1 +1 @@
1
- {"version":3,"file":"orderbook.codecs.js","names":[],"sources":["../../../src/services/orderbook/orderbook.codecs.ts"],"sourcesContent":["/**\n * Depths for which the backend publishes `public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto`\n * channels. Narrower than the depths the REST snapshot accepts (1 to its `maxDepth`):\n * subscribing to a depth outside this set succeeds and then never delivers a publication, so the book\n * silently stays empty.\n */\nexport const ORDERBOOK_WS_DEPTHS = [1, 20, 50, 200, 500] as const;\n\nexport type OrderbookWsDepth = (typeof ORDERBOOK_WS_DEPTHS)[number];\n\n/**\n * Smallest published channel depth that covers `depth`, so a request for an unpublished depth rides a\n * deeper feed and is sliced back down locally instead of subscribing to a channel with no publisher.\n */\nexport function orderbookWsChannelDepth(depth: number): OrderbookWsDepth {\n for (const d of ORDERBOOK_WS_DEPTHS) if (d >= depth) return d;\n return 500;\n}\n"],"mappings":";;;;;;;AAMA,MAAa,sBAAsB;CAAC;CAAG;CAAI;CAAI;CAAK;AAAG;;;;;AAQvD,SAAgB,wBAAwB,OAAiC;CACrE,KAAK,MAAM,KAAK,qBAAqB,IAAI,KAAK,OAAO,OAAO;CAC5D,OAAO;AACX"}
1
+ {"version":3,"file":"orderbook.codecs.js","names":[],"sources":["../../../src/services/orderbook/orderbook.codecs.ts"],"sourcesContent":["/**\n * Depths for which the backend publishes `public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto`\n * channels. Narrower than the depth tiers the REST snapshot serves (`DEPTH_TIER_VALUES`):\n * subscribing to a depth outside this set succeeds and then never delivers a publication, so the book\n * silently stays empty.\n */\nexport const ORDERBOOK_WS_DEPTHS = [1, 20, 50, 200, 500] as const;\n\nexport type OrderbookWsDepth = (typeof ORDERBOOK_WS_DEPTHS)[number];\n\n/**\n * Smallest published channel depth that covers `depth`, so a request for an unpublished depth rides a\n * deeper feed and is sliced back down locally instead of subscribing to a channel with no publisher.\n */\nexport function orderbookWsChannelDepth(depth: number): OrderbookWsDepth {\n for (const d of ORDERBOOK_WS_DEPTHS) if (d >= depth) return d;\n return 500;\n}\n"],"mappings":";;;;;;;AAMA,MAAa,sBAAsB;CAAC;CAAG;CAAI;CAAI;CAAK;AAAG;;;;;AAQvD,SAAgB,wBAAwB,OAAiC;CACrE,KAAK,MAAM,KAAK,qBAAqB,IAAI,KAAK,OAAO,OAAO;CAC5D,OAAO;AACX"}
@@ -24,7 +24,7 @@ declare class OrderbookService {
24
24
  #private;
25
25
  constructor(transports: PublicApiTransports, realtime: PolyesterRealtime, scales: SdkScales);
26
26
  /**
27
- * Fetches a spot order book depth snapshot for a symbol ID and requested depth, returning best bids and asks with the backend book sequence.
27
+ * Fetches a spot order book depth snapshot for a symbol ID and depth tier (`DEPTH_TIER_VALUES`, default 50), returning best bids and asks with the backend book sequence.
28
28
  * 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.
29
29
  */
30
30
  get(input: v.InferInput<typeof GetOrderbookInputSchema>, options?: PolyesterRequestOptions): Promise<OrderbookData>;
@@ -35,7 +35,7 @@ declare class OrderbookService {
35
35
  /**
36
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
- * `depth` above 500 throws ValidationError; other depths ride the smallest published channel depth that covers it (see ORDERBOOK_WS_DEPTHS); levels are sliced back to the requested depth locally.
38
+ * `depth` above 500 throws ValidationError, since only REST serves 1000 and 5000; other depths ride the smallest published channel depth that covers it (see ORDERBOOK_WS_DEPTHS); levels are sliced back to the requested depth locally.
39
39
  *
40
40
  * A refetched snapshot from an older `bookEpoch` than the book's is discarded and retried.
41
41
  *
@@ -1 +1 @@
1
- {"version":3,"file":"orderbook.d.ts","names":[],"sources":["../../../src/services/orderbook/orderbook.ts"],"mappings":";;;;;;;;UA6BU,gCAAgC,mBAAmB;EACzD;EACA;EACA;;UAGa,gCAAgC,mBAAmB;UAEnD;EACb;EACA,YAAY;;UAGC,yCAET,yBACA,KAAK;;;;cAOA;;EAKG,YAAA,YAAY,qBAAqB,UAAU,mBAAmB,QAAQ;;;;;EAU5E,IACF,OAAO,EAAE,kBAAkB,0BAC3B,UAAU,0BACX,QAAQ;;;;EAuBX,UAAU,OAAO;;;;;;;;;;EAajB,mBAAmB,OAAO,mCAAmC"}
1
+ {"version":3,"file":"orderbook.d.ts","names":[],"sources":["../../../src/services/orderbook/orderbook.ts"],"mappings":";;;;;;;;UA8BU,gCAAgC,mBAAmB;EACzD;EACA;EACA;;UAGa,gCAAgC,mBAAmB;UAEnD;EACb;EACA,YAAY;;UAGC,yCAET,yBACA,KAAK;;;;cAOA;;EAKG,YAAA,YAAY,qBAAqB,UAAU,mBAAmB,QAAQ;;;;;EAU5E,IACF,OAAO,EAAE,kBAAkB,0BAC3B,UAAU,0BACX,QAAQ;;;;EAwBX,UAAU,OAAO;;;;;;;;;;EAajB,mBAAmB,OAAO,mCAAmC"}
@@ -4,6 +4,7 @@ import { toConnectCallOptions } from "../../shared/request-options.js";
4
4
  import { publicationHandlerErrorContext } from "../../shared/subscription-errors.js";
5
5
  import { decimalInputToScaled } from "../../shared/decimal-surface.js";
6
6
  import { isResourceNotFoundError } from "../../utils/errors.js";
7
+ import { DepthTierCodec } from "../../shared/depth-tier.js";
7
8
  import { snapshotThenStream } from "../../realtime/snapshot-then-stream.js";
8
9
  import { GetOrderBookResponseSchema, OrderBookDeltaSchema, OrderbookService as OrderbookService$1 } from "../../gen/orderbook/v1/orderbook_pb.js";
9
10
  import { GetOrderbookInputSchema, createOrderbookDataSchema, formatOrderbookLevel } from "./orderbook.schemas.js";
@@ -24,7 +25,7 @@ var OrderbookService = class {
24
25
  this.#scales = scales;
25
26
  }
26
27
  /**
27
- * Fetches a spot order book depth snapshot for a symbol ID and requested depth, returning best bids and asks with the backend book sequence.
28
+ * Fetches a spot order book depth snapshot for a symbol ID and depth tier (`DEPTH_TIER_VALUES`, default 50), returning best bids and asks with the backend book sequence.
28
29
  * 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.
29
30
  */
30
31
  async get(input, options) {
@@ -32,14 +33,14 @@ var OrderbookService = class {
32
33
  await this.#scales.ready();
33
34
  const res = await this.#client.getOrderBook({
34
35
  symbolId: validated.symbolId,
35
- depth: validated.depth
36
+ depth: DepthTierCodec.inputToProto[validated.depth]
36
37
  }, toConnectCallOptions(options));
38
+ const served = DepthTierCodec.protoToOutput[res.depth];
37
39
  return parse(createOrderbookDataSchema(this.#scales, validated.symbolId), {
38
40
  symbolId: res.symbolId,
39
- depth: validated.depth,
41
+ depth: typeof served === "number" ? served : validated.depth,
40
42
  bookSeq: res.bookSeq,
41
43
  bookEpoch: res.bookEpoch,
42
- maxDepth: res.maxDepth,
43
44
  available: isBookAvailable(res),
44
45
  bids: res.bids,
45
46
  asks: res.asks,
@@ -55,7 +56,7 @@ var OrderbookService = class {
55
56
  /**
56
57
  * 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.
57
58
  *
58
- * `depth` above 500 throws ValidationError; other depths ride the smallest published channel depth that covers it (see ORDERBOOK_WS_DEPTHS); levels are sliced back to the requested depth locally.
59
+ * `depth` above 500 throws ValidationError, since only REST serves 1000 and 5000; other depths ride the smallest published channel depth that covers it (see ORDERBOOK_WS_DEPTHS); levels are sliced back to the requested depth locally.
59
60
  *
60
61
  * A refetched snapshot from an older `bookEpoch` than the book's is discarded and retried.
61
62
  *
@@ -75,7 +76,6 @@ var OrderbookService = class {
75
76
  let asksMap = /* @__PURE__ */ new Map();
76
77
  let currentBookSeq = 0n;
77
78
  let currentBookEpoch = 0n;
78
- let maxDepth = 0;
79
79
  let awaitingReset = false;
80
80
  let bucketTicks = null;
81
81
  let stream;
@@ -120,7 +120,6 @@ var OrderbookService = class {
120
120
  depth,
121
121
  bookSeq: currentBookSeq.toString(),
122
122
  bookEpoch: currentBookEpoch.toString(),
123
- maxDepth,
124
123
  available: true,
125
124
  bids: sideToUIBucketed(bidsMap, "bids", depth, bucketTicks),
126
125
  asks: sideToUIBucketed(asksMap, "asks", depth, bucketTicks)
@@ -144,7 +143,7 @@ var OrderbookService = class {
144
143
  try {
145
144
  res = await client.getOrderBook({
146
145
  symbolId,
147
- depth: channelDepth
146
+ depth: DepthTierCodec.inputToProto[channelDepth]
148
147
  });
149
148
  } catch (error) {
150
149
  if (!isResourceNotFoundError(error)) throw error;
@@ -199,7 +198,6 @@ var OrderbookService = class {
199
198
  asksMap = levelsToMap(snapshot.asks);
200
199
  currentBookSeq = snapshot.bookSeq;
201
200
  currentBookEpoch = snapshot.bookEpoch;
202
- maxDepth = snapshot.maxDepth;
203
201
  awaitingReset = false;
204
202
  emit();
205
203
  for (const delta of bufferedDeltas) {
@@ -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, ValidationError } 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.depth },\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 bookEpoch: res.bookEpoch,\n maxDepth: res.maxDepth,\n available: isBookAvailable(res),\n bids: res.bids,\n asks: res.asks,\n ts: res.ts,\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` above 500 throws ValidationError; other depths ride the smallest published channel depth that covers it (see ORDERBOOK_WS_DEPTHS); levels are sliced back to the requested depth locally.\n *\n * A refetched snapshot from an older `bookEpoch` than the book's is discarded and retried.\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, depth } = parse(GetOrderbookInputSchema, {\n symbolId: input.symbolId,\n depth: input.depth,\n });\n if (depth > 500) {\n throw new ValidationError(\n `depth must be at most 500 for a managed order book, got ${depth}`,\n );\n }\n const channelDepth = orderbookWsChannelDepth(depth);\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 currentBookEpoch = 0n;\n let maxDepth = 0;\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,\n bookSeq: currentBookSeq.toString(),\n bookEpoch: currentBookEpoch.toString(),\n maxDepth,\n available: true,\n bids: sideToUIBucketed(bidsMap, \"bids\", depth, bucketTicks),\n asks: sideToUIBucketed(asksMap, \"asks\", depth, 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 let res: Proto.GetOrderBookResponse;\n try {\n res = await client.getOrderBook({ symbolId, depth: channelDepth });\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 if (res.bookEpoch < currentBookEpoch) {\n throw new ServiceUnavailableError(\n `Order book snapshot for symbol ${symbolId} is from an older epoch`,\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 // GetOrderBook answers unavailable while the book is (re)built; keep asking until it is ready.\n snapshotRetry: {\n maxAttempts: Number.POSITIVE_INFINITY,\n delayMs: 1_000,\n maxDelayMs: 8_000,\n },\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 currentBookEpoch = snapshot.bookEpoch;\n maxDepth = snapshot.maxDepth;\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,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;EAAM,GACvD,qBAAqB,OAAO,CAChC;EACA,OAAO,MAAM,0BAA0B,KAAKG,SAAS,UAAU,QAAQ,GAAG;GACtE,UAAU,IAAI;GACd,OAAO,UAAU;GACjB,SAAS,IAAI;GACb,WAAW,IAAI;GACf,UAAU,IAAI;GACd,WAAW,gBAAgB,GAAG;GAC9B,MAAM,IAAI;GACV,MAAM,IAAI;GACV,IAAI,IAAI;EACZ,CAAC;CACL;;;;CAKA,UAAU,OAA4C;EAClD,OAAO,KAAK,mBAAmB,KAAK,CAAC,CAAC;CAC1C;;;;;;;;;;CAWA,mBAAmB,OAAgE;EAC/E,MAAM,EAAE,UAAU,UAAU,MAAM,yBAAyB;GACvD,UAAU,MAAM;GAChB,OAAO,MAAM;EACjB,CAAC;EACD,IAAI,QAAQ,KACR,MAAM,IAAI,gBACN,2DAA2D,OAC/D;EAEJ,MAAM,eAAe,wBAAwB,KAAK;EAClD,MAAM,UAAU,sCAAsC,aAAa,GAAG,SAAS;EAE/E,MAAM,SAAS,KAAKH;EACpB,MAAM,SAAS,KAAKG;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gBAAgB;IAC/D,gBAAgB;IAChB;GACJ;GAEA,eAAe,SAAS,MAAM,IAAI;GAClC,eAAe,SAAS,MAAM,IAAI;GAElC,iBAAiB,MAAM;GACvB,KAAK;EACT;EAEA,UAAU,MAAM,MAAM;EACtB,SAAS,mBAAmB;GACxB,UAAU,KAAKF;GACf;GACA,QAAQG;GACR,yBAAyB;GACzB,kBAAkB;GAElB,eAAe;IACX,aAAa,OAAO;IACpB,SAAS;IACT,YAAY;GAChB;GACA,eAAe;GACf,kBAAkB,UAAU,CAAC,KAAK;GAClC,gBAAgB,UAAU,mBAAmB;IACzC,UAAU,YAAY,SAAS,IAAI;IACnC,UAAU,YAAY,SAAS,IAAI;IACnC,iBAAiB,SAAS;IAC1B,mBAAmB,SAAS;IAC5B,WAAW,SAAS;IACpB,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"}
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 { DepthTierCodec } from \"../../shared/depth-tier.js\";\nimport { isResourceNotFoundError } from \"../../utils/errors.js\";\nimport { ServiceUnavailableError, ValidationError } 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 depth tier (`DEPTH_TIER_VALUES`, default 50), 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: DepthTierCodec.inputToProto[validated.depth] },\n toConnectCallOptions(options),\n );\n // Servers that predate the served tier leave it unset; they served the requested one.\n const served = DepthTierCodec.protoToOutput[res.depth];\n return parse(createOrderbookDataSchema(this.#scales, validated.symbolId), {\n symbolId: res.symbolId,\n depth: typeof served === \"number\" ? served : validated.depth,\n bookSeq: res.bookSeq,\n bookEpoch: res.bookEpoch,\n available: isBookAvailable(res),\n bids: res.bids,\n asks: res.asks,\n ts: res.ts,\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` above 500 throws ValidationError, since only REST serves 1000 and 5000; other depths ride the smallest published channel depth that covers it (see ORDERBOOK_WS_DEPTHS); levels are sliced back to the requested depth locally.\n *\n * A refetched snapshot from an older `bookEpoch` than the book's is discarded and retried.\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, depth } = parse(GetOrderbookInputSchema, {\n symbolId: input.symbolId,\n depth: input.depth,\n });\n if (depth > 500) {\n throw new ValidationError(\n `depth must be at most 500 for a managed order book, got ${depth}`,\n );\n }\n const channelDepth = orderbookWsChannelDepth(depth);\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 currentBookEpoch = 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,\n bookSeq: currentBookSeq.toString(),\n bookEpoch: currentBookEpoch.toString(),\n available: true,\n bids: sideToUIBucketed(bidsMap, \"bids\", depth, bucketTicks),\n asks: sideToUIBucketed(asksMap, \"asks\", depth, 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 let res: Proto.GetOrderBookResponse;\n try {\n res = await client.getOrderBook({\n symbolId,\n depth: DepthTierCodec.inputToProto[channelDepth],\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 if (res.bookEpoch < currentBookEpoch) {\n throw new ServiceUnavailableError(\n `Order book snapshot for symbol ${symbolId} is from an older epoch`,\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 // GetOrderBook answers unavailable while the book is (re)built; keep asking until it is ready.\n snapshotRetry: {\n maxAttempts: Number.POSITIVE_INFINITY,\n delayMs: 1_000,\n maxDelayMs: 8_000,\n },\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 currentBookEpoch = snapshot.bookEpoch;\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.as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EACT;EAEA,UAAU,MAAM,MAAM;EACtB,SAAS,mBAAmB;GACxB,UAAU,KAAKF;GACf;GACA,QAAQG;GACR,yBAAyB;GACzB,kBAAkB;GAElB,eAAe;IACX,aAAa,OAAO;IACpB,SAAS;IACT,YAAY;GAChB;GACA,eAAe;GACf,kBAAkB,UAAU,CAAC,KAAK;GAClC,gBAAgB,UAAU,mBAAmB;IACzC,UAAU,YAAY,SAAS,IAAI;IACnC,UAAU,YAAY,SAAS,IAAI;IACnC,iBAAiB,SAAS;IAC1B,mBAAmB,SAAS;IAC5B,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"}
@@ -3,8 +3,8 @@ import * as v from "valibot";
3
3
  //#region src/services/orderbook/orderbook.schemas.d.ts
4
4
  declare const GetOrderbookInputSchema: v.ObjectSchema<{
5
5
  readonly symbolId: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 4294967295, undefined>]>;
6
- /** Price levels per side, sent as given. The server rejects a depth above the `maxDepth` it reports. */
7
- readonly depth: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 4294967295, undefined>]>, 50>;
6
+ /** Price levels per side: one of `DEPTH_TIER_VALUES`. Any other count is refused before sending. */
7
+ readonly depth: v.OptionalSchema<v.PicklistSchema<readonly [1, 5, 10, 20, 50, 100, 200, 500, 1000, 5000], undefined>, 50>;
8
8
  }, undefined>;
9
9
  type GetOrderbookInput = v.InferInput<typeof GetOrderbookInputSchema>;
10
10
  declare const OrderbookLevelInputSchema: v.ObjectSchema<{
@@ -19,12 +19,11 @@ declare function formatOrderbookLevel(level: OrderbookLevelInput, scales: SdkSca
19
19
  type OrderbookLevel = ReturnType<typeof formatOrderbookLevel>;
20
20
  declare function createOrderbookDataSchema(scales: SdkScales, symbolId: number): v.SchemaWithPipe<readonly [v.ObjectSchema<{
21
21
  readonly symbolId: v.LiteralSchema<number, undefined>;
22
+ /** Price levels per side this snapshot was served at. */
22
23
  readonly depth: v.NumberSchema<undefined>;
23
24
  readonly bookSeq: v.BigintSchema<undefined>;
24
25
  /** Epoch of `bookSeq`: order snapshots by `(bookEpoch, bookSeq)`, since a new epoch may restart `bookSeq`. */
25
26
  readonly bookEpoch: v.BigintSchema<undefined>;
26
- /** Largest `depth` the server accepts. */
27
- readonly maxDepth: v.NumberSchema<undefined>;
28
27
  /** False while the book is being built or after it was invalidated: its levels are unknown, not empty. */
29
28
  readonly available: v.BooleanSchema<undefined>;
30
29
  readonly bids: v.ArraySchema<v.ObjectSchema<{
@@ -48,7 +47,6 @@ declare function createOrderbookDataSchema(scales: SdkScales, symbolId: number):
48
47
  depth: number;
49
48
  bookSeq: bigint;
50
49
  bookEpoch: bigint;
51
- maxDepth: number;
52
50
  available: boolean;
53
51
  bids: {
54
52
  priceTicks: bigint;
@@ -72,7 +70,6 @@ declare function createOrderbookDataSchema(scales: SdkScales, symbolId: number):
72
70
  }[];
73
71
  symbolId: number;
74
72
  depth: number;
75
- maxDepth: number;
76
73
  available: boolean;
77
74
  ts?: number | undefined;
78
75
  }>]>;
@@ -1 +1 @@
1
- {"version":3,"file":"orderbook.schemas.d.ts","names":[],"sources":["../../../src/services/orderbook/orderbook.schemas.ts"],"mappings":";;;cAKa,yBAAuB,EAAA;;;;;KAMxB,oBAAoB,EAAE,kBAAkB;cAE9C,2BAAyB,EAAA;;;;KAKnB,sBAAsB,EAAE,mBAAmB;iBAEvC,qBACZ,OAAO,qBACP,QAAQ,WACR;;;;KAQQ,iBAAiB,kBAAkB;iBAE/B,0BAA0B,QAAQ,WAAW,mBAAgB,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA2BjE,gBAAgB,EAAE,YAAY,kBAAkB"}
1
+ {"version":3,"file":"orderbook.schemas.d.ts","names":[],"sources":["../../../src/services/orderbook/orderbook.schemas.ts"],"mappings":";;;cAMa,yBAAuB,EAAA;;;;;KAMxB,oBAAoB,EAAE,kBAAkB;cAE9C,2BAAyB,EAAA;;;;KAKnB,sBAAsB,EAAE,mBAAmB;iBAEvC,qBACZ,OAAO,qBACP,QAAQ,WACR;;;;KAQQ,iBAAiB,kBAAkB;iBAE/B,0BAA0B,QAAQ,WAAW,mBAAgB,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA0BjE,gBAAgB,EAAE,YAAY,kBAAkB"}
@@ -1,12 +1,13 @@
1
1
  import { OptionalTimestampMsSchema } from "../../shared/schemas.js";
2
2
  import { scaledToDecimalOutput } from "../../shared/decimal-surface.js";
3
- import { PositiveUint32InputSchema, SymbolIdInputSchema } from "../shared.js";
3
+ import { SymbolIdInputSchema } from "../shared.js";
4
+ import { DEPTH_TIER_VALUES } from "../../shared/depth-tier.js";
4
5
  import * as v from "valibot";
5
6
  //#region src/services/orderbook/orderbook.schemas.ts
6
7
  const GetOrderbookInputSchema = v.object({
7
8
  symbolId: SymbolIdInputSchema,
8
- /** Price levels per side, sent as given. The server rejects a depth above the `maxDepth` it reports. */
9
- depth: v.optional(PositiveUint32InputSchema, 50)
9
+ /** Price levels per side: one of `DEPTH_TIER_VALUES`. Any other count is refused before sending. */
10
+ depth: v.optional(v.picklist(DEPTH_TIER_VALUES), 50)
10
11
  });
11
12
  const OrderbookLevelInputSchema = v.object({
12
13
  priceTicks: v.bigint(),
@@ -21,12 +22,11 @@ function formatOrderbookLevel(level, scales, symbolId) {
21
22
  function createOrderbookDataSchema(scales, symbolId) {
22
23
  return v.pipe(v.object({
23
24
  symbolId: v.literal(symbolId),
25
+ /** Price levels per side this snapshot was served at. */
24
26
  depth: v.number(),
25
27
  bookSeq: v.bigint(),
26
28
  /** Epoch of `bookSeq`: order snapshots by `(bookEpoch, bookSeq)`, since a new epoch may restart `bookSeq`. */
27
29
  bookEpoch: v.bigint(),
28
- /** Largest `depth` the server accepts. */
29
- maxDepth: v.number(),
30
30
  /** False while the book is being built or after it was invalidated: its levels are unknown, not empty. */
31
31
  available: v.boolean(),
32
32
  bids: v.array(OrderbookLevelInputSchema),
@@ -1 +1 @@
1
- {"version":3,"file":"orderbook.schemas.js","names":[],"sources":["../../../src/services/orderbook/orderbook.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { scaledToDecimalOutput, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport { OptionalTimestampMsSchema } from \"../../shared/schemas.js\";\nimport { PositiveUint32InputSchema, SymbolIdInputSchema } from \"../shared.js\";\n\nexport const GetOrderbookInputSchema = v.object({\n symbolId: SymbolIdInputSchema,\n /** Price levels per side, sent as given. The server rejects a depth above the `maxDepth` it reports. */\n depth: v.optional(PositiveUint32InputSchema, 50),\n});\n\nexport type GetOrderbookInput = v.InferInput<typeof GetOrderbookInputSchema>;\n\nconst OrderbookLevelInputSchema = v.object({\n priceTicks: v.bigint(),\n qtyScaled: v.bigint(),\n});\n\nexport type OrderbookLevelInput = v.InferOutput<typeof OrderbookLevelInputSchema>;\n\nexport function formatOrderbookLevel(\n level: OrderbookLevelInput,\n scales: SdkScales,\n symbolId: number,\n) {\n return {\n price: scaledToDecimalOutput(level.priceTicks, scales.price()),\n qty: scaledToDecimalOutput(level.qtyScaled, scales.baseQty(symbolId)),\n };\n}\n\nexport type OrderbookLevel = ReturnType<typeof formatOrderbookLevel>;\n\nexport function createOrderbookDataSchema(scales: SdkScales, symbolId: number) {\n return v.pipe(\n v.object({\n symbolId: v.literal(symbolId),\n depth: v.number(),\n bookSeq: v.bigint(),\n /** Epoch of `bookSeq`: order snapshots by `(bookEpoch, bookSeq)`, since a new epoch may restart `bookSeq`. */\n bookEpoch: v.bigint(),\n /** Largest `depth` the server accepts. */\n maxDepth: v.number(),\n /** False while the book is being built or after it was invalidated: its levels are unknown, not empty. */\n available: v.boolean(),\n bids: v.array(OrderbookLevelInputSchema),\n asks: v.array(OrderbookLevelInputSchema),\n /** Best-effort snapshot time in epoch ms; absent when the server sends none. */\n ts: OptionalTimestampMsSchema,\n }),\n v.transform((d) => ({\n ...d,\n bookSeq: d.bookSeq.toString(),\n bookEpoch: d.bookEpoch.toString(),\n bids: d.bids.map((level) => formatOrderbookLevel(level, scales, symbolId)),\n asks: d.asks.map((level) => formatOrderbookLevel(level, scales, symbolId)),\n })),\n );\n}\n\nexport type OrderbookData = v.InferOutput<ReturnType<typeof createOrderbookDataSchema>>;\n"],"mappings":";;;;;AAKA,MAAa,0BAA0B,EAAE,OAAO;CAC5C,UAAU;;CAEV,OAAO,EAAE,SAAS,2BAA2B,EAAE;AACnD,CAAC;AAID,MAAM,4BAA4B,EAAE,OAAO;CACvC,YAAY,EAAE,OAAO;CACrB,WAAW,EAAE,OAAO;AACxB,CAAC;AAID,SAAgB,qBACZ,OACA,QACA,UACF;CACE,OAAO;EACH,OAAO,sBAAsB,MAAM,YAAY,OAAO,MAAM,CAAC;EAC7D,KAAK,sBAAsB,MAAM,WAAW,OAAO,QAAQ,QAAQ,CAAC;CACxE;AACJ;AAIA,SAAgB,0BAA0B,QAAmB,UAAkB;CAC3E,OAAO,EAAE,KACL,EAAE,OAAO;EACL,UAAU,EAAE,QAAQ,QAAQ;EAC5B,OAAO,EAAE,OAAO;EAChB,SAAS,EAAE,OAAO;;EAElB,WAAW,EAAE,OAAO;;EAEpB,UAAU,EAAE,OAAO;;EAEnB,WAAW,EAAE,QAAQ;EACrB,MAAM,EAAE,MAAM,yBAAyB;EACvC,MAAM,EAAE,MAAM,yBAAyB;;EAEvC,IAAI;CACR,CAAC,GACD,EAAE,WAAW,OAAO;EAChB,GAAG;EACH,SAAS,EAAE,QAAQ,SAAS;EAC5B,WAAW,EAAE,UAAU,SAAS;EAChC,MAAM,EAAE,KAAK,KAAK,UAAU,qBAAqB,OAAO,QAAQ,QAAQ,CAAC;EACzE,MAAM,EAAE,KAAK,KAAK,UAAU,qBAAqB,OAAO,QAAQ,QAAQ,CAAC;CAC7E,EAAE,CACN;AACJ"}
1
+ {"version":3,"file":"orderbook.schemas.js","names":[],"sources":["../../../src/services/orderbook/orderbook.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { scaledToDecimalOutput, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport { OptionalTimestampMsSchema } from \"../../shared/schemas.js\";\nimport { DEPTH_TIER_VALUES } from \"../../shared/depth-tier.js\";\nimport { SymbolIdInputSchema } from \"../shared.js\";\n\nexport const GetOrderbookInputSchema = v.object({\n symbolId: SymbolIdInputSchema,\n /** Price levels per side: one of `DEPTH_TIER_VALUES`. Any other count is refused before sending. */\n depth: v.optional(v.picklist(DEPTH_TIER_VALUES), 50),\n});\n\nexport type GetOrderbookInput = v.InferInput<typeof GetOrderbookInputSchema>;\n\nconst OrderbookLevelInputSchema = v.object({\n priceTicks: v.bigint(),\n qtyScaled: v.bigint(),\n});\n\nexport type OrderbookLevelInput = v.InferOutput<typeof OrderbookLevelInputSchema>;\n\nexport function formatOrderbookLevel(\n level: OrderbookLevelInput,\n scales: SdkScales,\n symbolId: number,\n) {\n return {\n price: scaledToDecimalOutput(level.priceTicks, scales.price()),\n qty: scaledToDecimalOutput(level.qtyScaled, scales.baseQty(symbolId)),\n };\n}\n\nexport type OrderbookLevel = ReturnType<typeof formatOrderbookLevel>;\n\nexport function createOrderbookDataSchema(scales: SdkScales, symbolId: number) {\n return v.pipe(\n v.object({\n symbolId: v.literal(symbolId),\n /** Price levels per side this snapshot was served at. */\n depth: v.number(),\n bookSeq: v.bigint(),\n /** Epoch of `bookSeq`: order snapshots by `(bookEpoch, bookSeq)`, since a new epoch may restart `bookSeq`. */\n bookEpoch: v.bigint(),\n /** False while the book is being built or after it was invalidated: its levels are unknown, not empty. */\n available: v.boolean(),\n bids: v.array(OrderbookLevelInputSchema),\n asks: v.array(OrderbookLevelInputSchema),\n /** Best-effort snapshot time in epoch ms; absent when the server sends none. */\n ts: OptionalTimestampMsSchema,\n }),\n v.transform((d) => ({\n ...d,\n bookSeq: d.bookSeq.toString(),\n bookEpoch: d.bookEpoch.toString(),\n bids: d.bids.map((level) => formatOrderbookLevel(level, scales, symbolId)),\n asks: d.asks.map((level) => formatOrderbookLevel(level, scales, symbolId)),\n })),\n );\n}\n\nexport type OrderbookData = v.InferOutput<ReturnType<typeof createOrderbookDataSchema>>;\n"],"mappings":";;;;;;AAMA,MAAa,0BAA0B,EAAE,OAAO;CAC5C,UAAU;;CAEV,OAAO,EAAE,SAAS,EAAE,SAAS,iBAAiB,GAAG,EAAE;AACvD,CAAC;AAID,MAAM,4BAA4B,EAAE,OAAO;CACvC,YAAY,EAAE,OAAO;CACrB,WAAW,EAAE,OAAO;AACxB,CAAC;AAID,SAAgB,qBACZ,OACA,QACA,UACF;CACE,OAAO;EACH,OAAO,sBAAsB,MAAM,YAAY,OAAO,MAAM,CAAC;EAC7D,KAAK,sBAAsB,MAAM,WAAW,OAAO,QAAQ,QAAQ,CAAC;CACxE;AACJ;AAIA,SAAgB,0BAA0B,QAAmB,UAAkB;CAC3E,OAAO,EAAE,KACL,EAAE,OAAO;EACL,UAAU,EAAE,QAAQ,QAAQ;;EAE5B,OAAO,EAAE,OAAO;EAChB,SAAS,EAAE,OAAO;;EAElB,WAAW,EAAE,OAAO;;EAEpB,WAAW,EAAE,QAAQ;EACrB,MAAM,EAAE,MAAM,yBAAyB;EACvC,MAAM,EAAE,MAAM,yBAAyB;;EAEvC,IAAI;CACR,CAAC,GACD,EAAE,WAAW,OAAO;EAChB,GAAG;EACH,SAAS,EAAE,QAAQ,SAAS;EAC5B,WAAW,EAAE,UAAU,SAAS;EAChC,MAAM,EAAE,KAAK,KAAK,UAAU,qBAAqB,OAAO,QAAQ,QAAQ,CAAC;EACzE,MAAM,EAAE,KAAK,KAAK,UAAU,qBAAqB,OAAO,QAAQ,QAAQ,CAAC;CAC7E,EAAE,CACN;AACJ"}