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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +21 -1
  2. package/README.md +12 -0
  3. package/dist/index.d.ts +2 -2
  4. package/dist/realtime/client.d.ts.map +1 -1
  5. package/dist/realtime/client.js +178 -29
  6. package/dist/realtime/client.js.map +1 -1
  7. package/dist/realtime/index.d.ts +2 -2
  8. package/dist/realtime/types.d.ts +21 -2
  9. package/dist/realtime/types.d.ts.map +1 -1
  10. package/dist/services/candles/candles.schemas.d.ts +10 -10
  11. package/dist/services/checkpoints/checkpoints.schemas.d.ts +8 -2
  12. package/dist/services/checkpoints/checkpoints.schemas.d.ts.map +1 -1
  13. package/dist/services/checkpoints/checkpoints.schemas.js +6 -0
  14. package/dist/services/checkpoints/checkpoints.schemas.js.map +1 -1
  15. package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
  16. package/dist/services/lifecycle/lifecycle.schemas.d.ts +79 -79
  17. package/dist/services/orderbook/orderbook.d.ts +1 -1
  18. package/dist/services/orderbook/orderbook.js +1 -1
  19. package/dist/services/orderbook/orderbook.js.map +1 -1
  20. package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
  21. package/dist/services/orders/orders-batch.schemas.d.ts +7 -7
  22. package/dist/services/orders/orders-output.schemas.d.ts +3 -3
  23. package/dist/services/orders/orders.d.ts +1 -1
  24. package/dist/services/orders/orders.js +1 -1
  25. package/dist/services/orders/orders.js.map +1 -1
  26. package/dist/services/rewards/rewards.d.ts +1 -1
  27. package/dist/services/rewards/rewards.js +1 -1
  28. package/dist/services/rewards/rewards.js.map +1 -1
  29. package/dist/services/rewards/rewards.schemas.d.ts +7 -0
  30. package/dist/services/rewards/rewards.schemas.d.ts.map +1 -1
  31. package/dist/services/rewards/rewards.schemas.js +8 -1
  32. package/dist/services/rewards/rewards.schemas.js.map +1 -1
  33. package/dist/services/subaccounts/subaccounts.d.ts +1 -1
  34. package/dist/services/subaccounts/subaccounts.js +1 -1
  35. package/dist/services/subaccounts/subaccounts.js.map +1 -1
  36. package/dist/services/subaccounts/subaccounts.schemas.d.ts +10 -1
  37. package/dist/services/subaccounts/subaccounts.schemas.d.ts.map +1 -1
  38. package/dist/services/subaccounts/subaccounts.schemas.js +8 -1
  39. package/dist/services/subaccounts/subaccounts.schemas.js.map +1 -1
  40. package/dist/services/trades/trades.schemas.d.ts +2 -2
  41. package/dist/services/triggers/triggers-output.schemas.d.ts +19 -19
  42. package/dist/shared/connect-error-mapping.d.ts.map +1 -1
  43. package/dist/shared/connect-error-mapping.js +5 -2
  44. package/dist/shared/connect-error-mapping.js.map +1 -1
  45. package/dist/shared/errors.d.ts +1 -1
  46. package/dist/shared/errors.d.ts.map +1 -1
  47. package/dist/shared/errors.js.map +1 -1
  48. package/dist/shared/subscription-errors.d.ts +2 -0
  49. package/dist/shared/subscription-errors.d.ts.map +1 -1
  50. package/dist/shared/subscription-errors.js.map +1 -1
  51. package/dist/shared/transports.js.map +1 -1
  52. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":["#config","#getAuthHeaders","#fetchToken","#sharedSubs","#channelKind","#emitSubscriptionError","#fetchSubscriptionToken","#publicClient","#terminateSubscriptions","#pendingTeardowns","#privateClient","#emitConnectionTokenError","#createPublicClient","#hasAuth","#createPrivateClient","#ensurePublicClient","#assertChannelAuth","#attachSubscriptionNow","#attachSubscriptionWhenLoaded","#ensureClientForChannel","#subscriptionOpts","#attachSubscription","#callErrorHandler","#teardownSubscription","#disconnectClientIfIdle","#hasChannelsForKind","#privateOrdersEpoch","#privateOrders","#disconnectPrivateOrders","#disconnectCentrifuge","#getOrCreateSubscription","#callConsumerHandler","#privateOrdersLoading","#disconnect","#disconnectPrivate"],"sources":["../../src/realtime/client.ts"],"sourcesContent":["import { fromBinary, type DescMessage, type MessageShape } from \"@bufbuild/protobuf\";\nimport type {\n Centrifuge,\n SubscriptionErrorContext,\n PublicationContext,\n Subscription,\n} from \"centrifuge/build/protobuf\";\nimport type * as CentrifugeModule from \"centrifuge/build/protobuf\";\nimport {\n createSdkSubscriptionErrorContext,\n fromCentrifugeSubscriptionError,\n type SdkSubscriptionErrorContext,\n} from \"../shared/subscription-errors.js\";\nimport {\n AuthenticationError,\n errorFromHttpStatus,\n InternalServerError,\n PolyesterError,\n} from \"../shared/errors.js\";\nimport { makeFetch } from \"../shared/transports.js\";\nimport { decodeProtoFrame } from \"../utils/streams.js\";\nimport { idToBigInt } from \"../utils/base58-id.js\";\nimport type { ConnectChannelParams, PolyesterRealtime, SubscribeHandlers } from \"./types.js\";\nimport type { ConnectPrivateOrdersParams, PrivateOrderStream } from \"./private-orders.js\";\n\nconst realtimeFetch = makeFetch();\n\ntype CentrifugeCtor = typeof CentrifugeModule.Centrifuge;\ntype CentrifugeModuleLoader = () => Promise<typeof CentrifugeModule>;\n\nconst defaultCentrifugeModuleLoader: CentrifugeModuleLoader = () =>\n import(\"centrifuge/build/protobuf\");\n\n// Centrifuge's protobuf build embeds the protobuf.js runtime (~300 KB minified).\n// Loading it lazily keeps it out of the eager module graph on both the server\n// (Cloudflare isolate cold start — SSR never opens a websocket) and the client\n// app shell; it is only fetched when the first subscription attaches.\nlet centrifugeCtorPromise: Promise<CentrifugeCtor> | null = null;\nlet loadedCentrifugeCtor: CentrifugeCtor | null = null;\nlet centrifugeModuleLoader = defaultCentrifugeModuleLoader;\nexport function __setRealtimeCentrifugeForTests(Centrifuge: CentrifugeCtor | null): void {\n loadedCentrifugeCtor = Centrifuge;\n centrifugeCtorPromise = Centrifuge ? Promise.resolve(Centrifuge) : null;\n}\n\n/** Replaces the lazy Centrifuge module loader for isolated transport-load tests. */\nexport function __setRealtimeCentrifugeLoaderForTests(loader: CentrifugeModuleLoader | null): void {\n centrifugeModuleLoader = loader ?? defaultCentrifugeModuleLoader;\n loadedCentrifugeCtor = null;\n centrifugeCtorPromise = null;\n}\n\nfunction loadCentrifuge(): Promise<CentrifugeCtor> {\n if (\n centrifugeModuleLoader === defaultCentrifugeModuleLoader &&\n (import.meta as { env?: { SSR?: boolean } }).env?.SSR\n ) {\n return Promise.reject(new Error(\"Realtime subscriptions are browser-only during SSR.\"));\n }\n\n if (!centrifugeCtorPromise) {\n const loadAttempt = Promise.resolve().then(centrifugeModuleLoader);\n const retryableLoad = loadAttempt.then(\n (mod) => {\n loadedCentrifugeCtor = mod.Centrifuge;\n return mod.Centrifuge;\n },\n (error) => {\n if (centrifugeCtorPromise === retryableLoad) centrifugeCtorPromise = null;\n throw error;\n },\n );\n centrifugeCtorPromise = retryableLoad;\n }\n return centrifugeCtorPromise;\n}\n\nexport interface RealtimeAuthRequest {\n url: string | URL;\n method: string;\n}\n\nexport interface RealtimeConfig {\n wsUrl: string;\n tokenEndpoint: string;\n subscribeEndpoint: string;\n /** Private WebSocket endpoint for account order streams (`/v1/ws/private`). */\n privateWsUrl: string;\n getAuthHeaders?: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth?: () => boolean;\n}\n\ntype ResolvedRealtimeConfig = Pick<\n RealtimeConfig,\n \"wsUrl\" | \"tokenEndpoint\" | \"subscribeEndpoint\" | \"privateWsUrl\"\n> & {\n getAuthHeaders: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth: () => boolean;\n};\n\nexport type { ConnectChannelParams, PolyesterRealtime, SubscribeHandlers } from \"./types.js\";\n\ntype PublicationHandler<T = unknown> = (data: T) => void;\ntype ErrorHandler = (ctx: SdkSubscriptionErrorContext) => void;\ntype RealtimeClientKind = \"public\" | \"private\";\n\ninterface SharedSubscription {\n channel: string;\n sub: Subscription | null;\n client: Centrifuge | null;\n attachmentEpoch: number;\n consumers: number;\n subscriptionEpoch: number;\n publicationHandlers: Set<PublicationHandler>;\n subscribedHandlers: Set<(epoch: number) => void>;\n unsubscribedHandlers: Set<() => void>;\n errorHandlers: Set<ErrorHandler>;\n}\n\n/**\n * Shared Centrifuge realtime client that multiplexes public and private protobuf subscriptions across SDK services.\n */\nexport class RealtimeClient implements PolyesterRealtime {\n #publicClient: Centrifuge | null = null;\n #privateClient: Centrifuge | null = null;\n #sharedSubs = new Map<string, SharedSubscription>();\n #pendingTeardowns = new Map<string, SharedSubscription>();\n // Loaded on first use: the stream's protobuf graph (orders included) stays out of the app shell.\n #privateOrdersLoading: Promise<PrivateOrderStream> | null = null;\n #privateOrders: PrivateOrderStream | null = null;\n #privateOrdersEpoch = 0;\n readonly #config: ResolvedRealtimeConfig;\n\n constructor(config: RealtimeConfig) {\n this.#config = {\n wsUrl: config.wsUrl,\n tokenEndpoint: config.tokenEndpoint,\n subscribeEndpoint: config.subscribeEndpoint,\n privateWsUrl: config.privateWsUrl,\n getAuthHeaders: config.getAuthHeaders ?? (() => ({})),\n hasAuth: config.hasAuth ?? (() => false),\n };\n }\n\n async #getAuthHeaders(request: RealtimeAuthRequest): Promise<HeadersInit> {\n return this.#config.getAuthHeaders(request);\n }\n\n async #fetchToken(url: string | URL, kind: \"connection\" | \"subscription\"): Promise<string> {\n const headers = await this.#getAuthHeaders({ url, method: \"GET\" });\n const res = await realtimeFetch(url, { headers });\n if (!res.ok) {\n throw errorFromHttpStatus(res.status, `Failed to fetch ${kind} token: ${res.status}`, {\n status: res.status,\n });\n }\n const json = (await res.json()) as { token?: string };\n if (!json?.token) {\n throw new InternalServerError(\n `${kind === \"connection\" ? \"Connection\" : \"Subscription\"} token response had no token`,\n );\n }\n return json.token;\n }\n\n #fetchSubscriptionToken(channel: string): Promise<string> {\n const url = new URL(this.#config.subscribeEndpoint);\n url.searchParams.set(\"channel\", channel);\n return this.#fetchToken(url, \"subscription\");\n }\n\n #emitSubscriptionError(shared: SharedSubscription, type: string, error: unknown): void {\n const ctx = createSdkSubscriptionErrorContext(shared.channel, type, error);\n for (const handler of shared.errorHandlers) {\n handler(ctx);\n }\n }\n\n #emitConnectionTokenError(error: unknown): void {\n for (const shared of this.#sharedSubs.values()) {\n if (this.#channelKind(shared.channel) === \"private\") {\n this.#emitSubscriptionError(shared, \"connection_token\", error);\n }\n }\n }\n\n #subscriptionOpts(\n Centrifuge: CentrifugeCtor,\n shared: SharedSubscription,\n attachmentEpoch: number,\n ) {\n if (this.#channelKind(shared.channel) !== \"private\") return undefined;\n return {\n getToken: async () => {\n try {\n return await this.#fetchSubscriptionToken(shared.channel);\n } catch (error) {\n if (shared.attachmentEpoch === attachmentEpoch) {\n this.#emitSubscriptionError(shared, \"subscription_token\", error);\n }\n if (error instanceof PolyesterError && !error.retryable) {\n throw new Centrifuge.UnauthorizedError(error.message);\n }\n throw error;\n }\n },\n };\n }\n\n #hasAuth(): boolean {\n return this.#config.hasAuth();\n }\n\n #channelKind(channel: string): RealtimeClientKind {\n return channel.startsWith(\"private:\") ? \"private\" : \"public\";\n }\n\n #createPublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n const client = new Centrifuge(this.#config.wsUrl);\n this.#publicClient = client;\n\n client.on(\"disconnected\", (ctx) => {\n // Codes 0 (disconnectCalled) and 1 (unauthorized) are handled elsewhere;\n // every other disconnected event is terminal.\n if (this.#publicClient !== client || ctx.code <= 1) return;\n this.#publicClient = null;\n this.#terminateSubscriptions(\n [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()].filter(\n (shared) => shared.client === client,\n ),\n \"disconnected\",\n ctx,\n );\n });\n\n client.connect();\n return client;\n }\n\n #createPrivateClient(Centrifuge: CentrifugeCtor): Centrifuge {\n let client: Centrifuge;\n const opts = {\n getToken: async () => {\n try {\n return await this.#fetchToken(this.#config.tokenEndpoint, \"connection\");\n } catch (error) {\n if (this.#privateClient === client) {\n this.#emitConnectionTokenError(error);\n }\n if (error instanceof PolyesterError && !error.retryable) {\n throw new Centrifuge.UnauthorizedError(error.message);\n }\n throw error;\n }\n },\n };\n\n client = new Centrifuge(this.#config.wsUrl, opts);\n this.#privateClient = client;\n\n client.on(\"disconnected\", (ctx) => {\n // Codes 0 (disconnectCalled) and 1 (unauthorized) are handled elsewhere;\n // every other disconnected event is terminal.\n if (this.#privateClient !== client || ctx.code <= 1) return;\n this.#privateClient = null;\n this.#terminateSubscriptions(\n [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()].filter(\n (shared) => shared.client === client,\n ),\n \"disconnected\",\n ctx,\n );\n });\n\n client.connect();\n return client;\n }\n\n #ensurePublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n return this.#publicClient ?? this.#createPublicClient(Centrifuge);\n }\n\n #assertChannelAuth(channel: string): void {\n if (this.#channelKind(channel) === \"private\" && !this.#hasAuth()) {\n throw new AuthenticationError(\n `Cannot subscribe to private channel \"${channel}\" without authentication`,\n );\n }\n }\n\n #ensureClientForChannel(Centrifuge: CentrifugeCtor, channel: string): Centrifuge {\n if (this.#channelKind(channel) === \"private\") {\n return this.#privateClient ?? this.#createPrivateClient(Centrifuge);\n }\n\n return this.#ensurePublicClient(Centrifuge);\n }\n\n #attachSubscription(shared: SharedSubscription): void {\n if (shared.sub) return;\n\n // Auth failures must surface synchronously to subscribe() callers, as\n // they did when centrifuge was imported statically.\n this.#assertChannelAuth(shared.channel);\n\n const attachmentEpoch = shared.attachmentEpoch + 1;\n shared.attachmentEpoch = attachmentEpoch;\n\n // Once the transport module is loaded, attachment stays fully\n // synchronous — only the very first attach pays the dynamic import.\n if (loadedCentrifugeCtor) {\n this.#attachSubscriptionNow(loadedCentrifugeCtor, shared, attachmentEpoch);\n return;\n }\n void this.#attachSubscriptionWhenLoaded(shared, attachmentEpoch);\n }\n\n async #attachSubscriptionWhenLoaded(\n shared: SharedSubscription,\n attachmentEpoch: number,\n ): Promise<void> {\n let Centrifuge: CentrifugeCtor;\n try {\n Centrifuge = await loadCentrifuge();\n } catch (error) {\n if (shared.attachmentEpoch !== attachmentEpoch) return;\n if (this.#sharedSubs.get(shared.channel) === shared) {\n this.#sharedSubs.delete(shared.channel);\n }\n this.#emitSubscriptionError(shared, \"transport_load\", error);\n return;\n }\n\n // The subscription may have been torn down or re-attached while the\n // transport module was loading.\n if (shared.attachmentEpoch !== attachmentEpoch || shared.sub) return;\n if (this.#sharedSubs.get(shared.channel) !== shared) return;\n\n try {\n this.#assertChannelAuth(shared.channel);\n this.#attachSubscriptionNow(Centrifuge, shared, attachmentEpoch);\n } catch (error) {\n this.#sharedSubs.delete(shared.channel);\n this.#emitSubscriptionError(shared, \"auth\", error);\n }\n }\n\n #attachSubscriptionNow(\n Centrifuge: CentrifugeCtor,\n shared: SharedSubscription,\n attachmentEpoch: number,\n ): void {\n const client = this.#ensureClientForChannel(Centrifuge, shared.channel);\n\n const sub = client.newSubscription(\n shared.channel,\n this.#subscriptionOpts(Centrifuge, shared, attachmentEpoch),\n );\n shared.sub = sub;\n shared.client = client;\n\n sub.on(\"publication\", (ctx: PublicationContext) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n for (const handler of shared.publicationHandlers) handler(ctx.data);\n });\n sub.on(\"subscribed\", () => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n const subscriptionEpoch = ++shared.subscriptionEpoch;\n for (const handler of shared.subscribedHandlers) handler(subscriptionEpoch);\n });\n sub.on(\"unsubscribed\", (ctx) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n if (ctx.code >= 2000 && ctx.code < 2500) {\n this.#terminateSubscriptions([shared], \"unsubscribed\", ctx);\n return;\n }\n for (const handler of shared.unsubscribedHandlers) handler();\n });\n sub.on(\"error\", (ctx: SubscriptionErrorContext) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n const sdkCtx = fromCentrifugeSubscriptionError(ctx);\n for (const handler of shared.errorHandlers) handler(sdkCtx);\n });\n\n sub.subscribe();\n }\n\n #getOrCreateSubscription(channel: string): SharedSubscription {\n const existing = this.#sharedSubs.get(channel);\n if (existing) return existing;\n\n const pending = this.#pendingTeardowns.get(channel);\n if (pending) {\n this.#pendingTeardowns.delete(channel);\n this.#sharedSubs.set(channel, pending);\n if (!pending.sub) {\n this.#attachSubscription(pending);\n } else if (pending.sub.state !== \"subscribed\") {\n pending.sub.subscribe();\n }\n return pending;\n }\n\n const shared: SharedSubscription = {\n channel,\n sub: null,\n client: null,\n attachmentEpoch: 0,\n consumers: 0,\n subscriptionEpoch: 0,\n publicationHandlers: new Set(),\n subscribedHandlers: new Set(),\n unsubscribedHandlers: new Set(),\n errorHandlers: new Set(),\n };\n\n this.#sharedSubs.set(channel, shared);\n try {\n this.#attachSubscription(shared);\n } catch (error) {\n this.#sharedSubs.delete(channel);\n throw error;\n }\n return shared;\n }\n\n #callErrorHandler(handler: ErrorHandler | undefined, ctx: SdkSubscriptionErrorContext): void {\n if (!handler) return;\n\n try {\n handler(ctx);\n } catch {\n // Keep error reporting isolated from other subscription consumers.\n }\n }\n\n #callConsumerHandler(\n channel: string,\n type: string,\n handler: () => void,\n onError?: ErrorHandler,\n ): void {\n try {\n handler();\n } catch (error) {\n this.#callErrorHandler(\n onError,\n createSdkSubscriptionErrorContext(channel, type, error),\n );\n }\n }\n\n #terminateSubscriptions(\n subscriptions: SharedSubscription[],\n type: \"disconnected\" | \"unsubscribed\",\n ctx: { code: number; reason: string },\n ): void {\n const notifications = subscriptions.map((shared) => ({\n error: createSdkSubscriptionErrorContext(shared.channel, type, {\n code: ctx.code,\n message: ctx.reason,\n }),\n errorHandlers: [...shared.errorHandlers],\n closeHandlers: [...shared.unsubscribedHandlers],\n }));\n\n // Finish cleanup for every affected channel before callbacks can resubscribe.\n for (const shared of subscriptions) {\n if (this.#sharedSubs.get(shared.channel) === shared) {\n this.#sharedSubs.delete(shared.channel);\n }\n if (this.#pendingTeardowns.get(shared.channel) === shared) {\n this.#pendingTeardowns.delete(shared.channel);\n }\n this.#teardownSubscription(shared);\n shared.publicationHandlers.clear();\n shared.subscribedHandlers.clear();\n shared.unsubscribedHandlers.clear();\n shared.errorHandlers.clear();\n }\n\n for (const { error, errorHandlers, closeHandlers } of notifications) {\n for (const handler of errorHandlers) handler(error);\n for (const handler of closeHandlers) handler();\n }\n }\n\n #teardownSubscription(shared: SharedSubscription): void {\n const sub = shared.sub;\n const client = shared.client;\n const kind = this.#channelKind(shared.channel);\n shared.sub = null;\n shared.client = null;\n shared.attachmentEpoch++;\n if (!sub) return;\n\n try {\n if (sub.state !== \"unsubscribed\") {\n sub.unsubscribe();\n }\n } catch {\n // noop\n }\n try {\n client?.removeSubscription?.(sub);\n } catch {\n // noop\n }\n this.#disconnectClientIfIdle(kind);\n }\n\n #hasChannelsForKind(kind: RealtimeClientKind): boolean {\n for (const shared of this.#sharedSubs.values()) {\n if (this.#channelKind(shared.channel) === kind) return true;\n }\n for (const shared of this.#pendingTeardowns.values()) {\n if (this.#channelKind(shared.channel) === kind) return true;\n }\n return false;\n }\n\n #disconnectClientIfIdle(kind: RealtimeClientKind): void {\n if (this.#hasChannelsForKind(kind)) return;\n\n const client = kind === \"private\" ? this.#privateClient : this.#publicClient;\n if (kind === \"private\") {\n this.#privateClient = null;\n } else {\n this.#publicClient = null;\n }\n\n try {\n client?.disconnect();\n } catch {\n // noop\n }\n }\n\n /** Consumers still waiting for the stream module see the new epoch and never connect. */\n #disconnectPrivateOrders(): void {\n this.#privateOrdersEpoch++;\n this.#privateOrders?.disconnect();\n }\n\n #disconnect(): void {\n this.#disconnectPrivateOrders();\n this.#disconnectCentrifuge();\n }\n\n /** Leaves private order streams alone: they run on their own socket. */\n #disconnectCentrifuge(): void {\n const publicClient = this.#publicClient;\n const privateClient = this.#privateClient;\n\n this.#pendingTeardowns.clear();\n this.#sharedSubs.clear();\n this.#publicClient = null;\n this.#privateClient = null;\n\n try {\n publicClient?.disconnect();\n } catch {\n // noop\n }\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n }\n\n #disconnectPrivate(): void {\n this.#disconnectPrivateOrders();\n const privateClient = this.#privateClient;\n this.#privateClient = null;\n\n for (const [channel, shared] of this.#sharedSubs) {\n if (this.#channelKind(channel) !== \"private\") continue;\n this.#sharedSubs.delete(channel);\n this.#teardownSubscription(shared);\n }\n for (const [channel, shared] of this.#pendingTeardowns) {\n if (this.#channelKind(channel) !== \"private\") continue;\n this.#pendingTeardowns.delete(channel);\n this.#teardownSubscription(shared);\n }\n\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n }\n\n /**\n * Subscribes to a realtime channel and returns an unsubscribe function. Missing\n * authentication is reported to `onError`, or thrown synchronously when no error\n * observer is provided. Non-retryable token failures stop automatic retries;\n * calling subscribe again after correcting the failure restarts private realtime.\n */\n subscribe<T>(channel: string, handlers: SubscribeHandlers<T>): () => void {\n let shared: SharedSubscription;\n try {\n shared = this.#getOrCreateSubscription(channel);\n } catch (error) {\n if (!(error instanceof AuthenticationError)) throw error;\n if (!handlers.onError) throw error;\n\n const ctx = createSdkSubscriptionErrorContext(channel, \"auth\", error);\n queueMicrotask(() => this.#callErrorHandler(handlers.onError, ctx));\n return () => {};\n }\n shared.consumers++;\n\n const publicationHandler = handlers.onPublication;\n const errorHandler = handlers.onError;\n const subscribedHandler = handlers.onSubscribed;\n const unsubscribedHandler = handlers.onUnsubscribed;\n\n const onError: ErrorHandler | undefined = errorHandler\n ? (ctx) => this.#callErrorHandler(errorHandler, ctx)\n : undefined;\n const onPub: PublicationHandler = (data) => {\n this.#callConsumerHandler(\n channel,\n \"publication_handler\",\n () => publicationHandler(data as T),\n onError,\n );\n };\n let lastSubscribedEpoch = -1;\n const onSubscribed = subscribedHandler\n ? (subscriptionEpoch: number) => {\n if (subscriptionEpoch <= lastSubscribedEpoch) return;\n lastSubscribedEpoch = subscriptionEpoch;\n this.#callConsumerHandler(\n channel,\n \"subscribed_handler\",\n subscribedHandler,\n onError,\n );\n }\n : undefined;\n const onUnsubscribed = unsubscribedHandler\n ? () =>\n this.#callConsumerHandler(\n channel,\n \"unsubscribed_handler\",\n unsubscribedHandler,\n onError,\n )\n : undefined;\n\n shared.publicationHandlers.add(onPub);\n\n if (onSubscribed) shared.subscribedHandlers.add(onSubscribed);\n if (onUnsubscribed) shared.unsubscribedHandlers.add(onUnsubscribed);\n if (onError) shared.errorHandlers.add(onError);\n\n // Only an explicit subscribe restarts terminal private token failures.\n if (this.#channelKind(channel) === \"private\") {\n const reconnect = shared.client?.state === \"disconnected\";\n const resubscribe = shared.sub?.state === \"unsubscribed\";\n // hasAuth() reads the token provider, so only call it when a restart is possible.\n if ((reconnect || resubscribe) && this.#hasAuth()) {\n if (reconnect) shared.client?.connect();\n if (resubscribe) shared.sub?.subscribe();\n }\n }\n\n let closed = false;\n if (onSubscribed && shared.sub?.state === \"subscribed\") {\n const subscriptionEpoch = shared.subscriptionEpoch;\n queueMicrotask(() => {\n if (closed || shared.sub?.state !== \"subscribed\") return;\n onSubscribed(subscriptionEpoch);\n });\n }\n\n return () => {\n if (closed) return;\n closed = true;\n\n shared.publicationHandlers.delete(onPub);\n if (onSubscribed) shared.subscribedHandlers.delete(onSubscribed);\n if (onUnsubscribed) shared.unsubscribedHandlers.delete(onUnsubscribed);\n if (onError) shared.errorHandlers.delete(onError);\n\n shared.consumers--;\n if (shared.consumers <= 0) {\n const currentShared = this.#sharedSubs.get(channel);\n if (currentShared !== shared) return;\n\n this.#sharedSubs.delete(channel);\n this.#pendingTeardowns.set(channel, shared);\n\n queueMicrotask(() => {\n if (this.#pendingTeardowns.get(channel) !== shared) return;\n this.#pendingTeardowns.delete(channel);\n\n this.#teardownSubscription(shared);\n\n if (this.#sharedSubs.size === 0 && this.#pendingTeardowns.size === 0) {\n this.#disconnectCentrifuge();\n }\n });\n }\n };\n }\n\n /**\n * Connects to a realtime channel with a custom message decoder.\n */\n connectChannel<T extends DescMessage>(params: ConnectChannelParams<T>): () => void {\n return this.subscribe<Uint8Array>(params.channel, {\n onPublication: (data) => {\n let decoded: MessageShape<T>;\n try {\n decoded = fromBinary(params.schema, data);\n } catch (error) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(params.channel, \"decode\", error),\n );\n return;\n }\n params.onPublication(decoded);\n },\n onSubscribed: params.onConnected,\n onUnsubscribed: params.onDisconnected,\n onError: params.onError,\n });\n }\n\n /**\n * Connects to a realtime channel that emits protobuf messages.\n */\n connectProtoChannel<T extends DescMessage>(params: ConnectChannelParams<T>): () => void {\n return this.subscribe<Uint8Array | MessageShape<T>>(params.channel, {\n onPublication: (data) => {\n let msg: MessageShape<T> | null;\n try {\n msg = decodeProtoFrame(params.schema, data);\n } catch (error) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(params.channel, \"decode\", error),\n );\n return;\n }\n if (!msg) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(\n params.channel,\n \"decode\",\n \"Unable to decode protobuf frame\",\n ),\n );\n return;\n }\n params.onPublication(msg);\n },\n onSubscribed: params.onConnected,\n onUnsubscribed: params.onDisconnected,\n onError: params.onError,\n });\n }\n\n /**\n * Streams one account's orders over the private WebSocket. Missing authentication\n * is reported to `onError`, or thrown synchronously when no error observer is provided.\n * Throws ValidationError when `accountId` is not a base58 public ID.\n */\n connectPrivateOrders(params: ConnectPrivateOrdersParams): () => void {\n idToBigInt(params.accountId, \"accountId\");\n const channel = `private:spot:orders:${params.accountId}`;\n if (!this.#hasAuth()) {\n const error = new AuthenticationError(\n `Cannot subscribe to private channel \"${channel}\" without authentication`,\n );\n if (!params.onError) throw error;\n const ctx = createSdkSubscriptionErrorContext(channel, \"auth\", error);\n queueMicrotask(() => this.#callErrorHandler(params.onError, ctx));\n return () => {};\n }\n // Once loaded, connect at once: an unsubscribe and resubscribe in one tick keeps the stream.\n if (this.#privateOrders) return this.#privateOrders.connect(params);\n const loading = (this.#privateOrdersLoading ??= import(\"./private-orders.js\").then(\n ({ PrivateOrderStream }) =>\n (this.#privateOrders = new PrivateOrderStream({\n url: this.#config.privateWsUrl,\n fetchConnectToken: () =>\n this.#fetchToken(this.#config.tokenEndpoint, \"connection\"),\n fetchSubscribeToken: (ch) => this.#fetchSubscriptionToken(ch),\n })),\n ));\n const epoch = this.#privateOrdersEpoch;\n let closed = false;\n let stop: (() => void) | undefined;\n loading.then(\n (stream) => {\n if (!closed && epoch === this.#privateOrdersEpoch) stop = stream.connect(params);\n },\n (error) => {\n if (this.#privateOrdersLoading === loading) this.#privateOrdersLoading = null;\n if (closed || epoch !== this.#privateOrdersEpoch) return;\n const ctx = createSdkSubscriptionErrorContext(channel, \"transport_load\", error);\n this.#callErrorHandler(params.onError, ctx);\n this.#callConsumerHandler(\n channel,\n \"unsubscribed_handler\",\n () => params.onDisconnected?.(),\n params.onError,\n );\n },\n );\n return () => {\n closed = true;\n stop?.();\n };\n }\n\n /**\n * Disconnects the realtime client from all active channels.\n */\n disconnect(): void {\n this.#disconnect();\n }\n\n /**\n * Disconnects authenticated realtime state without touching public channels.\n */\n disconnectPrivate(): void {\n this.#disconnectPrivate();\n }\n\n get isConnected(): boolean {\n return (\n this.#publicClient !== null ||\n this.#privateClient !== null ||\n (this.#privateOrders?.activeChannels ?? 0) > 0\n );\n }\n\n get activeChannels(): number {\n return this.#sharedSubs.size + (this.#privateOrders?.activeChannels ?? 0);\n }\n\n get totalConsumers(): number {\n let total = this.#privateOrders?.totalConsumers ?? 0;\n for (const shared of this.#sharedSubs.values()) {\n total += shared.consumers;\n }\n return total;\n }\n}\n"],"mappings":";;;;;;;AAyBA,MAAM,gBAAgB,UAAU;AAKhC,MAAM,sCACF,OAAO;AAMX,IAAI,wBAAwD;AAC5D,IAAI,uBAA8C;AAClD,IAAI,yBAAyB;AAa7B,SAAS,iBAA0C;CAC/C,IACI,2BAA2B,iCAC1B,YAA4C,KAAK,KAElD,OAAO,QAAQ,uBAAO,IAAI,MAAM,qDAAqD,CAAC;CAG1F,IAAI,CAAC,uBAAuB;EAExB,MAAM,gBADc,QAAQ,QAAQ,CAAC,CAAC,KAAK,sBACX,CAAC,CAAC,MAC7B,QAAQ;GACL,uBAAuB,IAAI;GAC3B,OAAO,IAAI;EACf,IACC,UAAU;GACP,IAAI,0BAA0B,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qBAAqB;GAClD,MAAM,MAAM,kCAAkC,SAAS,kBAAkB,KAAK;GAC9E,KAAKJ,kBAAkB,OAAO,SAAS,GAAG;GAC1C,KAAKS,qBACD,SACA,8BACM,OAAO,iBAAiB,GAC9B,OAAO,OACX;EACJ,CACJ;EACA,aAAa;GACT,SAAS;GACT,OAAO;EACX;CACJ;;;;CAKA,aAAmB;EACf,KAAKE,YAAY;CACrB;;;;CAKA,oBAA0B;EACtB,KAAKC,mBAAmB;CAC5B;CAEA,IAAI,cAAuB;EACvB,OACI,KAAK3B,kBAAkB,QACvB,KAAKG,mBAAmB,SACvB,KAAKiB,gBAAgB,kBAAkB,KAAK;CAErD;CAEA,IAAI,iBAAyB;EACzB,OAAO,KAAKxB,YAAY,QAAQ,KAAKwB,gBAAgB,kBAAkB;CAC3E;CAEA,IAAI,iBAAyB;EACzB,IAAI,QAAQ,KAAKA,gBAAgB,kBAAkB;EACnD,KAAK,MAAM,UAAU,KAAKxB,YAAY,OAAO,GACzC,SAAS,OAAO;EAEpB,OAAO;CACX;AACJ"}
1
+ {"version":3,"file":"client.js","names":["#config","#getAuthHeaders","#fetchToken","#tokenRetryAt","#emitErrors","#sharedSubs","#channelKind","#fetchSubscriptionToken","#emitSubscriptionError","#publicClient","#watchClient","#privateClient","#emitConnectionTokenError","#privateTokenFailure","#connection","#connectionListeners","#setConnection","#currentClient","#transportErrors","#terminateSubscriptions","#pendingTeardowns","#createPublicClient","#hasAuth","#createPrivateClient","#ensurePublicClient","#assertChannelAuth","#attachSubscriptionNow","#attachSubscriptionWhenLoaded","#ensureClientForChannel","#subscriptionOpts","#attachSubscription","#callErrorHandler","#teardownSubscription","#dropConsumers","#disconnectClientIfIdle","#hasChannelsForKind","#privateOrdersEpoch","#privateOrders","#disconnectPrivateOrders","#disconnectCentrifuge","#getOrCreateSubscription","#callConsumerHandler","#privateOrdersLoading","#disconnect","#disconnectPrivate"],"sources":["../../src/realtime/client.ts"],"sourcesContent":["import { fromBinary, type DescMessage, type MessageShape } from \"@bufbuild/protobuf\";\nimport type {\n Centrifuge,\n ErrorContext,\n SubscriptionErrorContext,\n PublicationContext,\n Subscription,\n} from \"centrifuge/build/protobuf\";\nimport type * as CentrifugeModule from \"centrifuge/build/protobuf\";\nimport {\n createSdkSubscriptionErrorContext,\n fromCentrifugeSubscriptionError,\n type SdkSubscriptionErrorContext,\n} from \"../shared/subscription-errors.js\";\nimport {\n AuthenticationError,\n errorFromHttpStatus,\n InternalServerError,\n PolyesterError,\n RealtimeError,\n} from \"../shared/errors.js\";\nimport { parseRetryAfterHeader } from \"../shared/connect-error-mapping.js\";\nimport { makeFetch } from \"../shared/transports.js\";\nimport { decodeProtoFrame } from \"../utils/streams.js\";\nimport { idToBigInt } from \"../utils/base58-id.js\";\nimport type {\n ConnectChannelParams,\n PolyesterRealtime,\n RealtimeConnection,\n RealtimeConnectionStatus,\n SubscribeHandlers,\n} from \"./types.js\";\nimport type { ConnectPrivateOrdersParams, PrivateOrderStream } from \"./private-orders.js\";\n\nconst realtimeFetch = makeFetch();\n// ponytail: caps a bogus or huge Retry-After; a longer server window just answers 429 again with a new hint.\nconst MAX_RETRY_AFTER_MS = 60_000;\n\ntype CentrifugeCtor = typeof CentrifugeModule.Centrifuge;\ntype CentrifugeModuleLoader = () => Promise<typeof CentrifugeModule>;\n\nconst defaultCentrifugeModuleLoader: CentrifugeModuleLoader = () =>\n import(\"centrifuge/build/protobuf\");\n\n// Centrifuge's protobuf build embeds the protobuf.js runtime (~300 KB minified).\n// Loading it lazily keeps it out of the eager module graph on both the server\n// (Cloudflare isolate cold start — SSR never opens a websocket) and the client\n// app shell; it is only fetched when the first subscription attaches.\nlet centrifugeCtorPromise: Promise<CentrifugeCtor> | null = null;\nlet loadedCentrifugeCtor: CentrifugeCtor | null = null;\nlet centrifugeModuleLoader = defaultCentrifugeModuleLoader;\nexport function __setRealtimeCentrifugeForTests(Centrifuge: CentrifugeCtor | null): void {\n loadedCentrifugeCtor = Centrifuge;\n centrifugeCtorPromise = Centrifuge ? Promise.resolve(Centrifuge) : null;\n}\n\n/** Replaces the lazy Centrifuge module loader for isolated transport-load tests. */\nexport function __setRealtimeCentrifugeLoaderForTests(loader: CentrifugeModuleLoader | null): void {\n centrifugeModuleLoader = loader ?? defaultCentrifugeModuleLoader;\n loadedCentrifugeCtor = null;\n centrifugeCtorPromise = null;\n}\n\nfunction loadCentrifuge(): Promise<CentrifugeCtor> {\n if (\n centrifugeModuleLoader === defaultCentrifugeModuleLoader &&\n (import.meta as { env?: { SSR?: boolean } }).env?.SSR\n ) {\n return Promise.reject(new Error(\"Realtime subscriptions are browser-only during SSR.\"));\n }\n\n if (!centrifugeCtorPromise) {\n const loadAttempt = Promise.resolve().then(centrifugeModuleLoader);\n const retryableLoad = loadAttempt.then(\n (mod) => {\n loadedCentrifugeCtor = mod.Centrifuge;\n return mod.Centrifuge;\n },\n (error) => {\n if (centrifugeCtorPromise === retryableLoad) centrifugeCtorPromise = null;\n throw error;\n },\n );\n centrifugeCtorPromise = retryableLoad;\n }\n return centrifugeCtorPromise;\n}\n\nexport interface RealtimeAuthRequest {\n url: string | URL;\n method: string;\n}\n\nexport interface RealtimeConfig {\n wsUrl: string;\n tokenEndpoint: string;\n subscribeEndpoint: string;\n /** Private WebSocket endpoint for account order streams (`/v1/ws/private`). */\n privateWsUrl: string;\n getAuthHeaders?: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth?: () => boolean;\n}\n\ntype ResolvedRealtimeConfig = Pick<\n RealtimeConfig,\n \"wsUrl\" | \"tokenEndpoint\" | \"subscribeEndpoint\" | \"privateWsUrl\"\n> & {\n getAuthHeaders: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth: () => boolean;\n};\n\nexport type { ConnectChannelParams, PolyesterRealtime, SubscribeHandlers } from \"./types.js\";\n\ntype PublicationHandler<T = unknown> = (data: T) => void;\ntype ErrorHandler = (ctx: SdkSubscriptionErrorContext) => void;\ntype RealtimeClientKind = \"public\" | \"private\";\n\nconst DISCONNECTED: RealtimeConnectionStatus = { state: \"disconnected\", error: null };\n/** Centrifuge client `error` types that mean a connect attempt failed; each retry emits one. */\nconst CONNECT_FAILURE_TYPES = new Set([\"transport\", \"connect\", \"connectToken\", \"connectData\"]);\n\ninterface SharedSubscription {\n channel: string;\n sub: Subscription | null;\n client: Centrifuge | null;\n attachmentEpoch: number;\n consumers: number;\n subscriptionEpoch: number;\n publicationHandlers: Set<PublicationHandler>;\n subscribedHandlers: Set<(epoch: number) => void>;\n unsubscribedHandlers: Set<() => void>;\n errorHandlers: Set<ErrorHandler>;\n}\n\n/**\n * Shared Centrifuge realtime client that multiplexes public and private protobuf subscriptions across SDK services.\n */\nexport class RealtimeClient implements PolyesterRealtime {\n #publicClient: Centrifuge | null = null;\n #privateClient: Centrifuge | null = null;\n #sharedSubs = new Map<string, SharedSubscription>();\n #pendingTeardowns = new Map<string, SharedSubscription>();\n // Loaded on first use: the stream's protobuf graph (orders included) stays out of the app shell.\n #privateOrdersLoading: Promise<PrivateOrderStream> | null = null;\n #privateOrders: PrivateOrderStream | null = null;\n #privateOrdersEpoch = 0;\n #connection: RealtimeConnection = { public: DISCONNECTED, private: DISCONNECTED };\n #connectionListeners = new Set<(connection: RealtimeConnection) => void>();\n /** Outage errors already sent to channels as `\"transport\"`; replayed to late subscribers. */\n #transportErrors = new WeakSet<Error>();\n /** The non-retryable connection token failure that stops the private socket (code 1). */\n #privateTokenFailure: Error | null = null;\n /** Token requests wait until then after a 429 with `Retry-After`. */\n #tokenRetryAt = 0;\n readonly #config: ResolvedRealtimeConfig;\n\n constructor(config: RealtimeConfig) {\n this.#config = {\n wsUrl: config.wsUrl,\n tokenEndpoint: config.tokenEndpoint,\n subscribeEndpoint: config.subscribeEndpoint,\n privateWsUrl: config.privateWsUrl,\n getAuthHeaders: config.getAuthHeaders ?? (() => ({})),\n hasAuth: config.hasAuth ?? (() => false),\n };\n }\n\n async #getAuthHeaders(request: RealtimeAuthRequest): Promise<HeadersInit> {\n return this.#config.getAuthHeaders(request);\n }\n\n /**\n * Every realtime token request (connection, subscription, private order stream)\n * comes through here, so one wait honors `Retry-After` for all of them; the\n * transport's own reconnect backoff still applies on top.\n */\n async #fetchToken(url: string | URL, kind: \"connection\" | \"subscription\"): Promise<string> {\n // Recheck after each await: another request's 429 may have pushed the deadline out.\n let headers: HeadersInit;\n do {\n for (let wait; (wait = this.#tokenRetryAt - Date.now()) > 0;) {\n await new Promise((resolve) => setTimeout(resolve, wait));\n }\n headers = await this.#getAuthHeaders({ url, method: \"GET\" });\n } while (this.#tokenRetryAt > Date.now());\n const res = await realtimeFetch(url, { headers });\n if (!res.ok) {\n const retryAfterMs = parseRetryAfterHeader(res.headers.get(\"retry-after\"));\n if (res.status === 429 && retryAfterMs !== undefined) {\n this.#tokenRetryAt = Math.max(\n this.#tokenRetryAt,\n Date.now() + Math.min(retryAfterMs, MAX_RETRY_AFTER_MS),\n );\n }\n throw errorFromHttpStatus(res.status, `Failed to fetch ${kind} token: ${res.status}`, {\n status: res.status,\n retryAfterMs,\n });\n }\n const json = (await res.json()) as { token?: string };\n if (!json?.token) {\n throw new InternalServerError(\n `${kind === \"connection\" ? \"Connection\" : \"Subscription\"} token response had no token`,\n );\n }\n return json.token;\n }\n\n #fetchSubscriptionToken(channel: string): Promise<string> {\n const url = new URL(this.#config.subscribeEndpoint);\n url.searchParams.set(\"channel\", channel);\n return this.#fetchToken(url, \"subscription\");\n }\n\n /**\n * Delivers to the consumers registered when it starts: one a handler adds (a resubscribe)\n * is not part of it, and one a handler removes is skipped.\n */\n #emitErrors(recipients: SharedSubscription[], type: string, error: unknown): void {\n const deliveries = recipients.map((shared) => ({\n shared,\n ctx: createSdkSubscriptionErrorContext(shared.channel, type, error),\n handlers: Array.from(shared.errorHandlers),\n }));\n for (const { shared, ctx, handlers } of deliveries) {\n for (const handler of handlers) {\n if (shared.errorHandlers.has(handler)) handler(ctx);\n }\n }\n }\n\n #emitSubscriptionError(shared: SharedSubscription, type: string, error: unknown): void {\n this.#emitErrors([shared], type, error);\n }\n\n #emitConnectionTokenError(error: unknown): void {\n const privateSubs = [...this.#sharedSubs.values()].filter(\n (shared) => this.#channelKind(shared.channel) === \"private\",\n );\n this.#emitErrors(privateSubs, \"connection_token\", error);\n }\n\n #subscriptionOpts(\n Centrifuge: CentrifugeCtor,\n shared: SharedSubscription,\n attachmentEpoch: number,\n ) {\n if (this.#channelKind(shared.channel) !== \"private\") return undefined;\n return {\n getToken: async () => {\n try {\n return await this.#fetchSubscriptionToken(shared.channel);\n } catch (error) {\n if (shared.attachmentEpoch === attachmentEpoch) {\n this.#emitSubscriptionError(shared, \"subscription_token\", error);\n }\n if (error instanceof PolyesterError && !error.retryable) {\n throw new Centrifuge.UnauthorizedError(error.message);\n }\n throw error;\n }\n },\n };\n }\n\n #hasAuth(): boolean {\n return this.#config.hasAuth();\n }\n\n #channelKind(channel: string): RealtimeClientKind {\n return channel.startsWith(\"private:\") ? \"private\" : \"public\";\n }\n\n #createPublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n const client = new Centrifuge(this.#config.wsUrl);\n this.#publicClient = client;\n this.#watchClient(client, \"public\");\n client.connect();\n return client;\n }\n\n #createPrivateClient(Centrifuge: CentrifugeCtor): Centrifuge {\n let client: Centrifuge;\n const opts = {\n getToken: async () => {\n try {\n return await this.#fetchToken(this.#config.tokenEndpoint, \"connection\");\n } catch (error) {\n if (this.#privateClient === client) {\n this.#emitConnectionTokenError(error);\n }\n if (error instanceof PolyesterError && !error.retryable) {\n if (this.#privateClient === client) this.#privateTokenFailure = error;\n throw new Centrifuge.UnauthorizedError(error.message);\n }\n throw error;\n }\n },\n };\n\n client = new Centrifuge(this.#config.wsUrl, opts);\n this.#privateClient = client;\n this.#privateTokenFailure = null;\n this.#watchClient(client, \"private\");\n client.connect();\n return client;\n }\n\n #currentClient(kind: RealtimeClientKind): Centrifuge | null {\n return kind === \"private\" ? this.#privateClient : this.#publicClient;\n }\n\n #setConnection(kind: RealtimeClientKind, status: RealtimeConnectionStatus): void {\n const current = this.#connection[kind];\n if (current.state === status.state && current.error === status.error) return;\n this.#connection = { ...this.#connection, [kind]: status };\n const connection = this.#connection;\n // Notify once Centrifuge has finished its transition, so a listener can disconnect or\n // subscribe safely. A newer status replaces this one, even mid-delivery.\n // Snapshot: a listener added during delivery (one replacing itself) waits for the next change.\n queueMicrotask(() => {\n for (const listener of Array.from(this.#connectionListeners)) {\n if (this.#connection !== connection) return;\n if (!this.#connectionListeners.has(listener)) continue;\n try {\n listener(connection);\n } catch {\n // Keep one listener from starving the others.\n }\n }\n });\n }\n\n #watchClient(client: Centrifuge, kind: RealtimeClientKind): void {\n this.#setConnection(kind, { state: \"connecting\", error: null });\n\n client.on(\"state\", ({ newState, oldState }) => {\n // `disconnected` is recorded by the handlers below, which know the reason.\n if (this.#currentClient(kind) !== client || newState === \"disconnected\") return;\n // A restart after a terminal close starts a new outage.\n const { error } = this.#connection[kind];\n this.#setConnection(kind, {\n state: newState,\n error: newState === \"connected\" || oldState === \"disconnected\" ? null : error,\n });\n });\n\n // Centrifuge stays in \"connecting\" across failed attempts, so the `connecting`\n // event fires once; each failed attempt arrives as a client `error` instead.\n client.on(\"error\", (ctx: ErrorContext) => {\n if (this.#currentClient(kind) !== client || !CONNECT_FAILURE_TYPES.has(ctx.type))\n return;\n const { code, message } = ctx.error as { code?: unknown; message?: unknown };\n // 109: the cached token expired; Centrifuge fetches a new one and reconnects.\n if (ctx.type === \"connect\" && code === 109) return;\n // Report the first failure of an outage only, not every reconnect retry. A token\n // failure only marks the status (private channels get \"connection_token\" from\n // getToken), so a socket failure after one is still sent to channels.\n const current = this.#connection[kind].error;\n if (current && (ctx.type === \"connectToken\" || this.#transportErrors.has(current)))\n return;\n const error = new RealtimeError(\n `Realtime ${kind} connection failed: ${typeof message === \"string\" && message ? message : ctx.type}`,\n { realtimeCode: typeof code === \"number\" ? code : 0, retryable: true },\n );\n this.#setConnection(kind, { state: \"connecting\", error });\n // Private channels already receive connection token failures as \"connection_token\".\n if (ctx.type === \"connectToken\") return;\n this.#transportErrors.add(error);\n // A consumer added by a handler gets the replay in subscribe() instead.\n const affected = [...this.#sharedSubs.values()].filter(\n (shared) => shared.client === client,\n );\n this.#emitErrors(affected, \"transport\", error);\n });\n\n client.on(\"disconnected\", (ctx) => {\n // Code 0 (disconnectCalled) comes from our own teardown, which drops the client first.\n if (this.#currentClient(kind) !== client || ctx.code === 0) return;\n // Centrifuge reports a rejected private token as \"unauthorized\"; record the real failure.\n const tokenFailure =\n kind === \"private\" && ctx.code === 1 ? this.#privateTokenFailure : null;\n if (kind === \"private\") this.#privateTokenFailure = null;\n this.#setConnection(kind, {\n state: \"disconnected\",\n error:\n tokenFailure ??\n new RealtimeError(ctx.reason || \"Realtime connection closed\", {\n realtimeCode: ctx.code,\n }),\n });\n // Code 1 (unauthorized) on the private socket: channels already got the token\n // error, and an explicit subscribe() restarts this client, so keep it. The public\n // socket has no token to fix, so there it is terminal like any other close.\n if (ctx.code === 1 && kind === \"private\") return;\n if (kind === \"private\") this.#privateClient = null;\n else this.#publicClient = null;\n this.#terminateSubscriptions(\n [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()].filter(\n (shared) => shared.client === client,\n ),\n \"disconnected\",\n ctx,\n );\n });\n }\n\n #ensurePublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n return this.#publicClient ?? this.#createPublicClient(Centrifuge);\n }\n\n #assertChannelAuth(channel: string): void {\n if (this.#channelKind(channel) === \"private\" && !this.#hasAuth()) {\n throw new AuthenticationError(\n `Cannot subscribe to private channel \"${channel}\" without authentication`,\n );\n }\n }\n\n #ensureClientForChannel(Centrifuge: CentrifugeCtor, channel: string): Centrifuge {\n if (this.#channelKind(channel) === \"private\") {\n return this.#privateClient ?? this.#createPrivateClient(Centrifuge);\n }\n\n return this.#ensurePublicClient(Centrifuge);\n }\n\n #attachSubscription(shared: SharedSubscription): void {\n if (shared.sub) return;\n\n // Auth failures must surface synchronously to subscribe() callers, as\n // they did when centrifuge was imported statically.\n this.#assertChannelAuth(shared.channel);\n\n const attachmentEpoch = shared.attachmentEpoch + 1;\n shared.attachmentEpoch = attachmentEpoch;\n\n // Once the transport module is loaded, attachment stays fully\n // synchronous — only the very first attach pays the dynamic import.\n if (loadedCentrifugeCtor) {\n this.#attachSubscriptionNow(loadedCentrifugeCtor, shared, attachmentEpoch);\n return;\n }\n void this.#attachSubscriptionWhenLoaded(shared, attachmentEpoch);\n }\n\n async #attachSubscriptionWhenLoaded(\n shared: SharedSubscription,\n attachmentEpoch: number,\n ): Promise<void> {\n let Centrifuge: CentrifugeCtor;\n try {\n Centrifuge = await loadCentrifuge();\n } catch (error) {\n if (shared.attachmentEpoch !== attachmentEpoch) return;\n if (this.#sharedSubs.get(shared.channel) === shared) {\n this.#sharedSubs.delete(shared.channel);\n }\n this.#emitSubscriptionError(shared, \"transport_load\", error);\n return;\n }\n\n // The subscription may have been torn down or re-attached while the\n // transport module was loading.\n if (shared.attachmentEpoch !== attachmentEpoch || shared.sub) return;\n if (this.#sharedSubs.get(shared.channel) !== shared) return;\n\n try {\n this.#assertChannelAuth(shared.channel);\n this.#attachSubscriptionNow(Centrifuge, shared, attachmentEpoch);\n } catch (error) {\n this.#sharedSubs.delete(shared.channel);\n this.#emitSubscriptionError(shared, \"auth\", error);\n }\n }\n\n #attachSubscriptionNow(\n Centrifuge: CentrifugeCtor,\n shared: SharedSubscription,\n attachmentEpoch: number,\n ): void {\n const client = this.#ensureClientForChannel(Centrifuge, shared.channel);\n\n const sub = client.newSubscription(\n shared.channel,\n this.#subscriptionOpts(Centrifuge, shared, attachmentEpoch),\n );\n shared.sub = sub;\n shared.client = client;\n\n sub.on(\"publication\", (ctx: PublicationContext) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n for (const handler of shared.publicationHandlers) handler(ctx.data);\n });\n sub.on(\"subscribed\", () => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n const subscriptionEpoch = ++shared.subscriptionEpoch;\n for (const handler of shared.subscribedHandlers) handler(subscriptionEpoch);\n });\n sub.on(\"unsubscribed\", (ctx) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n if (ctx.code >= 2000 && ctx.code < 2500) {\n this.#terminateSubscriptions([shared], \"unsubscribed\", ctx);\n return;\n }\n for (const handler of shared.unsubscribedHandlers) handler();\n });\n sub.on(\"error\", (ctx: SubscriptionErrorContext) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n const sdkCtx = fromCentrifugeSubscriptionError(ctx);\n for (const handler of shared.errorHandlers) handler(sdkCtx);\n });\n\n sub.subscribe();\n }\n\n #getOrCreateSubscription(channel: string): SharedSubscription {\n const existing = this.#sharedSubs.get(channel);\n if (existing) return existing;\n\n const pending = this.#pendingTeardowns.get(channel);\n if (pending) {\n this.#pendingTeardowns.delete(channel);\n this.#sharedSubs.set(channel, pending);\n if (!pending.sub) {\n this.#attachSubscription(pending);\n } else if (pending.sub.state !== \"subscribed\") {\n pending.sub.subscribe();\n }\n return pending;\n }\n\n const shared: SharedSubscription = {\n channel,\n sub: null,\n client: null,\n attachmentEpoch: 0,\n consumers: 0,\n subscriptionEpoch: 0,\n publicationHandlers: new Set(),\n subscribedHandlers: new Set(),\n unsubscribedHandlers: new Set(),\n errorHandlers: new Set(),\n };\n\n this.#sharedSubs.set(channel, shared);\n try {\n this.#attachSubscription(shared);\n } catch (error) {\n this.#sharedSubs.delete(channel);\n throw error;\n }\n return shared;\n }\n\n #callErrorHandler(handler: ErrorHandler | undefined, ctx: SdkSubscriptionErrorContext): void {\n if (!handler) return;\n\n try {\n handler(ctx);\n } catch {\n // Keep error reporting isolated from other subscription consumers.\n }\n }\n\n #callConsumerHandler(\n channel: string,\n type: string,\n handler: () => void,\n onError?: ErrorHandler,\n ): void {\n try {\n handler();\n } catch (error) {\n this.#callErrorHandler(\n onError,\n createSdkSubscriptionErrorContext(channel, type, error),\n );\n }\n }\n\n #terminateSubscriptions(\n subscriptions: SharedSubscription[],\n type: \"disconnected\" | \"unsubscribed\",\n ctx: { code: number; reason: string },\n ): void {\n const notifications = subscriptions.map((shared) => ({\n error: createSdkSubscriptionErrorContext(shared.channel, type, {\n code: ctx.code,\n message: ctx.reason,\n }),\n errorHandlers: [...shared.errorHandlers],\n closeHandlers: [...shared.unsubscribedHandlers],\n }));\n\n // Finish cleanup for every affected channel before callbacks can resubscribe.\n for (const shared of subscriptions) {\n if (this.#sharedSubs.get(shared.channel) === shared) {\n this.#sharedSubs.delete(shared.channel);\n }\n if (this.#pendingTeardowns.get(shared.channel) === shared) {\n this.#pendingTeardowns.delete(shared.channel);\n }\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n\n for (const { error, errorHandlers, closeHandlers } of notifications) {\n for (const handler of errorHandlers) handler(error);\n for (const handler of closeHandlers) handler();\n }\n }\n\n /** Forgets a dropped channel's consumers, so an error delivery in progress skips them. */\n #dropConsumers(shared: SharedSubscription): void {\n shared.publicationHandlers.clear();\n shared.subscribedHandlers.clear();\n shared.unsubscribedHandlers.clear();\n shared.errorHandlers.clear();\n }\n\n #teardownSubscription(shared: SharedSubscription): void {\n const sub = shared.sub;\n const client = shared.client;\n const kind = this.#channelKind(shared.channel);\n shared.sub = null;\n shared.client = null;\n shared.attachmentEpoch++;\n if (!sub) return;\n\n try {\n if (sub.state !== \"unsubscribed\") {\n sub.unsubscribe();\n }\n } catch {\n // noop\n }\n try {\n client?.removeSubscription?.(sub);\n } catch {\n // noop\n }\n this.#disconnectClientIfIdle(kind);\n }\n\n #hasChannelsForKind(kind: RealtimeClientKind): boolean {\n for (const shared of this.#sharedSubs.values()) {\n if (this.#channelKind(shared.channel) === kind) return true;\n }\n for (const shared of this.#pendingTeardowns.values()) {\n if (this.#channelKind(shared.channel) === kind) return true;\n }\n return false;\n }\n\n #disconnectClientIfIdle(kind: RealtimeClientKind): void {\n if (this.#hasChannelsForKind(kind)) return;\n\n const client = this.#currentClient(kind);\n if (kind === \"private\") {\n this.#privateClient = null;\n } else {\n this.#publicClient = null;\n }\n // A terminal close already recorded its error and dropped the client.\n if (client) this.#setConnection(kind, DISCONNECTED);\n\n try {\n client?.disconnect();\n } catch {\n // noop\n }\n }\n\n /** Consumers still waiting for the stream module see the new epoch and never connect. */\n #disconnectPrivateOrders(): void {\n this.#privateOrdersEpoch++;\n this.#privateOrders?.disconnect();\n }\n\n #disconnect(): void {\n this.#disconnectPrivateOrders();\n this.#disconnectCentrifuge();\n }\n\n /** Leaves private order streams alone: they run on their own socket. */\n #disconnectCentrifuge(): void {\n const publicClient = this.#publicClient;\n const privateClient = this.#privateClient;\n\n for (const shared of [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()]) {\n this.#dropConsumers(shared);\n }\n this.#pendingTeardowns.clear();\n this.#sharedSubs.clear();\n this.#publicClient = null;\n this.#privateClient = null;\n if (publicClient) this.#setConnection(\"public\", DISCONNECTED);\n if (privateClient) this.#setConnection(\"private\", DISCONNECTED);\n\n try {\n publicClient?.disconnect();\n } catch {\n // noop\n }\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n }\n\n #disconnectPrivate(): void {\n this.#disconnectPrivateOrders();\n const privateClient = this.#privateClient;\n this.#privateClient = null;\n if (privateClient) this.#setConnection(\"private\", DISCONNECTED);\n\n for (const [channel, shared] of this.#sharedSubs) {\n if (this.#channelKind(channel) !== \"private\") continue;\n this.#sharedSubs.delete(channel);\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n for (const [channel, shared] of this.#pendingTeardowns) {\n if (this.#channelKind(channel) !== \"private\") continue;\n this.#pendingTeardowns.delete(channel);\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n }\n\n /**\n * Subscribes to a realtime channel and returns an unsubscribe function. Missing\n * authentication is reported to `onError`, or thrown synchronously when no error\n * observer is provided. Non-retryable token failures stop automatic retries;\n * calling subscribe again after correcting the failure restarts private realtime.\n */\n subscribe<T>(channel: string, handlers: SubscribeHandlers<T>): () => void {\n let shared: SharedSubscription;\n try {\n shared = this.#getOrCreateSubscription(channel);\n } catch (error) {\n if (!(error instanceof AuthenticationError)) throw error;\n if (!handlers.onError) throw error;\n\n const ctx = createSdkSubscriptionErrorContext(channel, \"auth\", error);\n queueMicrotask(() => this.#callErrorHandler(handlers.onError, ctx));\n return () => {};\n }\n shared.consumers++;\n\n const publicationHandler = handlers.onPublication;\n const errorHandler = handlers.onError;\n const subscribedHandler = handlers.onSubscribed;\n const unsubscribedHandler = handlers.onUnsubscribed;\n\n // Set by the returned unsubscribe: a delivery already under way skips this consumer.\n let closed = false;\n const onError: ErrorHandler | undefined = errorHandler\n ? (ctx) => {\n if (!closed) this.#callErrorHandler(errorHandler, ctx);\n }\n : undefined;\n const onPub: PublicationHandler = (data) => {\n this.#callConsumerHandler(\n channel,\n \"publication_handler\",\n () => publicationHandler(data as T),\n onError,\n );\n };\n let lastSubscribedEpoch = -1;\n const onSubscribed = subscribedHandler\n ? (subscriptionEpoch: number) => {\n if (subscriptionEpoch <= lastSubscribedEpoch) return;\n lastSubscribedEpoch = subscriptionEpoch;\n this.#callConsumerHandler(\n channel,\n \"subscribed_handler\",\n subscribedHandler,\n onError,\n );\n }\n : undefined;\n const onUnsubscribed = unsubscribedHandler\n ? () => {\n if (closed) return;\n this.#callConsumerHandler(\n channel,\n \"unsubscribed_handler\",\n unsubscribedHandler,\n onError,\n );\n }\n : undefined;\n\n shared.publicationHandlers.add(onPub);\n\n if (onSubscribed) shared.subscribedHandlers.add(onSubscribed);\n if (onUnsubscribed) shared.unsubscribedHandlers.add(onUnsubscribed);\n if (onError) shared.errorHandlers.add(onError);\n\n // Only an explicit subscribe restarts terminal private token failures.\n if (this.#channelKind(channel) === \"private\") {\n const reconnect = shared.client?.state === \"disconnected\";\n const resubscribe = shared.sub?.state === \"unsubscribed\";\n // hasAuth() reads the token provider, so only call it when a restart is possible.\n if ((reconnect || resubscribe) && this.#hasAuth()) {\n if (reconnect) shared.client?.connect();\n if (resubscribe) shared.sub?.subscribe();\n }\n }\n\n // Joining a socket that is already failing: this consumer missed the outage's one report.\n const outage = this.#connection[this.#channelKind(channel)].error;\n if (onError && outage && this.#transportErrors.has(outage)) {\n const ctx = createSdkSubscriptionErrorContext(channel, \"transport\", outage);\n queueMicrotask(() => {\n if (closed || this.#connection[this.#channelKind(channel)].error !== outage) return;\n onError(ctx);\n });\n }\n if (onSubscribed && shared.sub?.state === \"subscribed\") {\n const subscriptionEpoch = shared.subscriptionEpoch;\n queueMicrotask(() => {\n if (closed || shared.sub?.state !== \"subscribed\") return;\n onSubscribed(subscriptionEpoch);\n });\n }\n\n return () => {\n if (closed) return;\n closed = true;\n\n shared.publicationHandlers.delete(onPub);\n if (onSubscribed) shared.subscribedHandlers.delete(onSubscribed);\n if (onUnsubscribed) shared.unsubscribedHandlers.delete(onUnsubscribed);\n if (onError) shared.errorHandlers.delete(onError);\n\n shared.consumers--;\n if (shared.consumers <= 0) {\n const currentShared = this.#sharedSubs.get(channel);\n if (currentShared !== shared) return;\n\n this.#sharedSubs.delete(channel);\n this.#pendingTeardowns.set(channel, shared);\n\n queueMicrotask(() => {\n if (this.#pendingTeardowns.get(channel) !== shared) return;\n this.#pendingTeardowns.delete(channel);\n\n this.#teardownSubscription(shared);\n\n if (this.#sharedSubs.size === 0 && this.#pendingTeardowns.size === 0) {\n this.#disconnectCentrifuge();\n }\n });\n }\n };\n }\n\n /**\n * Connects to a realtime channel with a custom message decoder.\n */\n connectChannel<T extends DescMessage>(params: ConnectChannelParams<T>): () => void {\n return this.subscribe<Uint8Array>(params.channel, {\n onPublication: (data) => {\n let decoded: MessageShape<T>;\n try {\n decoded = fromBinary(params.schema, data);\n } catch (error) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(params.channel, \"decode\", error),\n );\n return;\n }\n params.onPublication(decoded);\n },\n onSubscribed: params.onConnected,\n onUnsubscribed: params.onDisconnected,\n onError: params.onError,\n });\n }\n\n /**\n * Connects to a realtime channel that emits protobuf messages.\n */\n connectProtoChannel<T extends DescMessage>(params: ConnectChannelParams<T>): () => void {\n return this.subscribe<Uint8Array | MessageShape<T>>(params.channel, {\n onPublication: (data) => {\n let msg: MessageShape<T> | null;\n try {\n msg = decodeProtoFrame(params.schema, data);\n } catch (error) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(params.channel, \"decode\", error),\n );\n return;\n }\n if (!msg) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(\n params.channel,\n \"decode\",\n \"Unable to decode protobuf frame\",\n ),\n );\n return;\n }\n params.onPublication(msg);\n },\n onSubscribed: params.onConnected,\n onUnsubscribed: params.onDisconnected,\n onError: params.onError,\n });\n }\n\n /**\n * Streams one account's orders over the private WebSocket. Missing authentication\n * is reported to `onError`, or thrown synchronously when no error observer is provided.\n * Throws ValidationError when `accountId` is not a base58 public ID.\n */\n connectPrivateOrders(params: ConnectPrivateOrdersParams): () => void {\n idToBigInt(params.accountId, \"accountId\");\n const channel = `private:spot:orders:${params.accountId}`;\n if (!this.#hasAuth()) {\n const error = new AuthenticationError(\n `Cannot subscribe to private channel \"${channel}\" without authentication`,\n );\n if (!params.onError) throw error;\n const ctx = createSdkSubscriptionErrorContext(channel, \"auth\", error);\n queueMicrotask(() => this.#callErrorHandler(params.onError, ctx));\n return () => {};\n }\n // Once loaded, connect at once: an unsubscribe and resubscribe in one tick keeps the stream.\n if (this.#privateOrders) return this.#privateOrders.connect(params);\n const loading = (this.#privateOrdersLoading ??= import(\"./private-orders.js\").then(\n ({ PrivateOrderStream }) =>\n (this.#privateOrders = new PrivateOrderStream({\n url: this.#config.privateWsUrl,\n fetchConnectToken: () =>\n this.#fetchToken(this.#config.tokenEndpoint, \"connection\"),\n fetchSubscribeToken: (ch) => this.#fetchSubscriptionToken(ch),\n })),\n ));\n const epoch = this.#privateOrdersEpoch;\n let closed = false;\n let stop: (() => void) | undefined;\n loading.then(\n (stream) => {\n if (!closed && epoch === this.#privateOrdersEpoch) stop = stream.connect(params);\n },\n (error) => {\n if (this.#privateOrdersLoading === loading) this.#privateOrdersLoading = null;\n if (closed || epoch !== this.#privateOrdersEpoch) return;\n const ctx = createSdkSubscriptionErrorContext(channel, \"transport_load\", error);\n this.#callErrorHandler(params.onError, ctx);\n this.#callConsumerHandler(\n channel,\n \"unsubscribed_handler\",\n () => params.onDisconnected?.(),\n params.onError,\n );\n },\n );\n return () => {\n closed = true;\n stop?.();\n };\n }\n\n /**\n * Disconnects the realtime client from all active channels.\n */\n disconnect(): void {\n this.#disconnect();\n }\n\n /**\n * Disconnects authenticated realtime state without touching public channels.\n */\n disconnectPrivate(): void {\n this.#disconnectPrivate();\n }\n\n /**\n * Status of the public and private sockets. A socket that cannot connect stays\n * `\"connecting\"` with `error` set, and every channel on it gets one `\"transport\"`\n * error per outage. Private order streams run on their own socket and are not included.\n */\n get connection(): RealtimeConnection {\n return this.#connection;\n }\n\n /** Calls `listener` with the current {@link connection} after it changes, in a microtask; a status replaced before then is skipped. Returns an unsubscribe function. */\n onConnectionChange(listener: (connection: RealtimeConnection) => void): () => void {\n this.#connectionListeners.add(listener);\n return () => this.#connectionListeners.delete(listener);\n }\n\n get activeChannels(): number {\n return this.#sharedSubs.size + (this.#privateOrders?.activeChannels ?? 0);\n }\n\n get totalConsumers(): number {\n let total = this.#privateOrders?.totalConsumers ?? 0;\n for (const shared of this.#sharedSubs.values()) {\n total += shared.consumers;\n }\n return total;\n }\n}\n"],"mappings":";;;;;;;;AAkCA,MAAM,gBAAgB,UAAU;AAEhC,MAAM,qBAAqB;AAK3B,MAAM,sCACF,OAAO;AAMX,IAAI,wBAAwD;AAC5D,IAAI,uBAA8C;AAClD,IAAI,yBAAyB;AAa7B,SAAS,iBAA0C;CAC/C,IACI,2BAA2B,iCAC1B,YAA4C,KAAK,KAElD,OAAO,QAAQ,uBAAO,IAAI,MAAM,qDAAqD,CAA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kBAAkB,KAAK;GAC9E,KAAKL,kBAAkB,OAAO,SAAS,GAAG;GAC1C,KAAKU,qBACD,SACA,8BACM,OAAO,iBAAiB,GAC9B,OAAO,OACX;EACJ,CACJ;EACA,aAAa;GACT,SAAS;GACT,OAAO;EACX;CACJ;;;;CAKA,aAAmB;EACf,KAAKE,YAAY;CACrB;;;;CAKA,oBAA0B;EACtB,KAAKC,mBAAmB;CAC5B;;;;;;CAOA,IAAI,aAAiC;EACjC,OAAO,KAAK9B;CAChB;;CAGA,mBAAmB,UAAgE;EAC/E,KAAKC,qBAAqB,IAAI,QAAQ;EACtC,aAAa,KAAKA,qBAAqB,OAAO,QAAQ;CAC1D;CAEA,IAAI,iBAAyB;EACzB,OAAO,KAAKV,YAAY,QAAQ,KAAKgC,gBAAgB,kBAAkB;CAC3E;CAEA,IAAI,iBAAyB;EACzB,IAAI,QAAQ,KAAKA,gBAAgB,kBAAkB;EACnD,KAAK,MAAM,UAAU,KAAKhC,YAAY,OAAO,GACzC,SAAS,OAAO;EAEpB,OAAO;CACX;AACJ"}
@@ -1,4 +1,4 @@
1
1
  import { ConnectPrivateOrdersParams, PrivateOrdersEvent } from "./private-orders.js";
2
- import { ConnectChannelParams, PolyesterRealtime, SubscribeHandlers } from "./types.js";
2
+ import { ConnectChannelParams, PolyesterRealtime, RealtimeConnection, RealtimeConnectionState, RealtimeConnectionStatus, SubscribeHandlers } from "./types.js";
3
3
  import { RealtimeConfig } from "./client.js";
4
- export type { ConnectChannelParams, ConnectPrivateOrdersParams, PolyesterRealtime, PrivateOrdersEvent, RealtimeConfig, SubscribeHandlers };
4
+ export type { ConnectChannelParams, ConnectPrivateOrdersParams, PolyesterRealtime, PrivateOrdersEvent, RealtimeConfig, RealtimeConnection, RealtimeConnectionState, RealtimeConnectionStatus, SubscribeHandlers };
@@ -18,6 +18,22 @@ interface ConnectChannelParams<T extends DescMessage> {
18
18
  /** Observes subscription failures. Missing authentication throws when omitted. */
19
19
  onError?: (ctx: SdkSubscriptionErrorContext) => void;
20
20
  }
21
+ type RealtimeConnectionState = "connecting" | "connected" | "disconnected";
22
+ interface RealtimeConnectionStatus {
23
+ /** `"disconnected"` also means no socket is open because no channel needs one. */
24
+ readonly state: RealtimeConnectionState;
25
+ /**
26
+ * Why the socket is not connected, or `null`. Set on the first failure of an outage
27
+ * while the socket keeps retrying in `"connecting"` (a socket failure after a connection
28
+ * token failure replaces it), or after it closed for good; cleared once it connects.
29
+ */
30
+ readonly error: Error | null;
31
+ }
32
+ /** Status of the public and the private Centrifuge sockets. Replaced, never mutated. */
33
+ interface RealtimeConnection {
34
+ readonly public: RealtimeConnectionStatus;
35
+ readonly private: RealtimeConnectionStatus;
36
+ }
21
37
  /**
22
38
  * Structural realtime contract consumed by SDK services. The default
23
39
  * implementation is the Centrifuge-backed {@link ../realtime/client.js RealtimeClient};
@@ -37,10 +53,13 @@ interface PolyesterRealtime {
37
53
  disconnect(): void;
38
54
  /** Disconnects authenticated realtime state without touching public channels. */
39
55
  disconnectPrivate(): void;
40
- readonly isConnected: boolean;
56
+ /** Socket status; private order streams run on their own socket and are not included. */
57
+ readonly connection: RealtimeConnection;
58
+ /** Calls `listener` with the current {@link RealtimeConnection} after it changes, in a microtask; a status replaced before then is skipped. Returns an unsubscribe function. */
59
+ onConnectionChange(listener: (connection: RealtimeConnection) => void): () => void;
41
60
  readonly activeChannels: number;
42
61
  readonly totalConsumers: number;
43
62
  }
44
63
  //#endregion
45
- export { ConnectChannelParams, PolyesterRealtime, SubscribeHandlers };
64
+ export { ConnectChannelParams, PolyesterRealtime, RealtimeConnection, RealtimeConnectionState, RealtimeConnectionStatus, SubscribeHandlers };
46
65
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../../src/realtime/types.ts"],"mappings":";;;;UAIiB,kBAAkB;EAC/B,gBAAgB,MAAM;EACtB;EACA;;EAEA,WAAW,KAAK;;UAGH,qBAAqB,UAAU;EAC5C;EACA,QAAQ;EACR,gBAAgB,MAAM,aAAa;EACnC;EACA;;EAEA,WAAW,KAAK;;;;;;;;UASH;;EAEb,UAAU,GAAG,iBAAiB,UAAU,kBAAkB;;EAE1D,eAAe,UAAU,aAAa,QAAQ,qBAAqB;;EAEnE,oBAAoB,UAAU,aAAa,QAAQ,qBAAqB;;EAExE,qBAAqB,QAAQ;;EAE7B;;EAEA;WACS;WACA;WACA"}
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../../src/realtime/types.ts"],"mappings":";;;;UAIiB,kBAAkB;EAC/B,gBAAgB,MAAM;EACtB;EACA;;EAEA,WAAW,KAAK;;UAGH,qBAAqB,UAAU;EAC5C;EACA,QAAQ;EACR,gBAAgB,MAAM,aAAa;EACnC;EACA;;EAEA,WAAW,KAAK;;KAGR;UAEK;;WAEJ,OAAO;;;;;;WAMP,OAAO;;;UAIH;WACJ,QAAQ;WACR,SAAS;;;;;;;;UASL;;EAEb,UAAU,GAAG,iBAAiB,UAAU,kBAAkB;;EAE1D,eAAe,UAAU,aAAa,QAAQ,qBAAqB;;EAEnE,oBAAoB,UAAU,aAAa,QAAQ,qBAAqB;;EAExE,qBAAqB,QAAQ;;EAE7B;;EAEA;;WAES,YAAY;;EAErB,mBAAmB,WAAW,YAAY;WACjC;WACA"}
@@ -11,7 +11,7 @@ type TimestampInit = {
11
11
  };
12
12
  declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
13
13
  readonly symbolId: v.NumberSchema<undefined>;
14
- readonly timeframe: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "3m" | "5m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">>]>;
14
+ readonly timeframe: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">>]>;
15
15
  readonly tsSec: v.BigintSchema<undefined>;
16
16
  readonly open: v.BigintSchema<undefined>;
17
17
  readonly high: v.BigintSchema<undefined>;
@@ -22,7 +22,7 @@ declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<read
22
22
  readonly isClosed: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
23
23
  }, undefined>, v.TransformAction<{
24
24
  symbolId: number;
25
- timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "3m" | "5m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
25
+ timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
26
26
  tsSec: bigint;
27
27
  open: bigint;
28
28
  high: bigint;
@@ -33,7 +33,7 @@ declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<read
33
33
  isClosed: boolean;
34
34
  }, {
35
35
  symbolId: number;
36
- timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "3m" | "5m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
36
+ timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
37
37
  time: number;
38
38
  open: string;
39
39
  high: string;
@@ -46,7 +46,7 @@ declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<read
46
46
  declare const createCandleRowIntSchema: typeof createCandleRowSchema;
47
47
  declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
48
48
  readonly symbolId: v.NumberSchema<undefined>;
49
- readonly timeframe: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "3m" | "5m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">>]>;
49
+ readonly timeframe: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">>]>;
50
50
  readonly tsSec: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
51
51
  readonly open: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
52
52
  readonly high: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
@@ -63,7 +63,7 @@ declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe
63
63
  readonly nextPageToken: v.OptionalSchema<v.StringSchema<undefined>, "">;
64
64
  }, undefined>, v.TransformAction<{
65
65
  symbolId: number;
66
- timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "3m" | "5m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
66
+ timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
67
67
  tsSec: bigint[];
68
68
  open: bigint[];
69
69
  high: bigint[];
@@ -80,7 +80,7 @@ declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe
80
80
  nextPageToken: string;
81
81
  }, {
82
82
  symbolId: number;
83
- timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "3m" | "5m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
83
+ timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
84
84
  time: number[];
85
85
  open: string[];
86
86
  high: string[];
@@ -100,7 +100,7 @@ declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe
100
100
  }>]>;
101
101
  declare function createCandleColumnarIntSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
102
102
  readonly symbolId: v.NumberSchema<undefined>;
103
- readonly timeframe: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "3m" | "5m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">>]>;
103
+ readonly timeframe: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">>]>;
104
104
  readonly tsSec: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
105
105
  readonly open: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
106
106
  readonly high: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
@@ -117,7 +117,7 @@ declare function createCandleColumnarIntSchema(scales: SdkScales): v.SchemaWithP
117
117
  readonly nextPageToken: v.OptionalSchema<v.StringSchema<undefined>, "">;
118
118
  }, undefined>, v.TransformAction<{
119
119
  symbolId: number;
120
- timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "3m" | "5m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
120
+ timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
121
121
  tsSec: bigint[];
122
122
  open: bigint[];
123
123
  high: bigint[];
@@ -134,7 +134,7 @@ declare function createCandleColumnarIntSchema(scales: SdkScales): v.SchemaWithP
134
134
  nextPageToken: string;
135
135
  }, {
136
136
  symbolId: number;
137
- timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "3m" | "5m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
137
+ timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
138
138
  tsSec: number[];
139
139
  open: string[];
140
140
  high: string[];
@@ -158,7 +158,7 @@ type CandleColumnar = v.InferOutput<ReturnType<typeof createCandleColumnarSchema
158
158
  type CandleColumnarInt = v.InferOutput<ReturnType<typeof createCandleColumnarIntSchema>>;
159
159
  declare function createListCandlesInputSchema(): v.SchemaWithPipe<readonly [v.ObjectSchema<{
160
160
  readonly symbolId: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 4294967295, undefined>]>;
161
- readonly timeframe: v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["1s", "1m", "3m", "5m", "15m", "30m", "1h", "2h", "4h", "6h", "8h", "12h", "1d", "3d", "1w", "1mo"], undefined>, v.TransformAction<"1d" | "1h" | "1w" | "1m" | "1s" | "3m" | "5m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo", Timeframe$1.SEC_1 | Timeframe$1.MIN_1 | Timeframe$1.MIN_3 | Timeframe$1.MIN_5 | Timeframe$1.MIN_15 | Timeframe$1.MIN_30 | Timeframe$1.HOUR_1 | Timeframe$1.HOUR_2 | Timeframe$1.HOUR_4 | Timeframe$1.HOUR_6 | Timeframe$1.HOUR_8 | Timeframe$1.HOUR_12 | Timeframe$1.DAY_1 | Timeframe$1.DAY_3 | Timeframe$1.WEEK_1 | Timeframe$1.MONTH_1>]>;
161
+ readonly timeframe: v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["1s", "1m", "3m", "5m", "15m", "30m", "1h", "2h", "4h", "6h", "8h", "12h", "1d", "3d", "1w", "1mo"], undefined>, v.TransformAction<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo", Timeframe$1.SEC_1 | Timeframe$1.MIN_1 | Timeframe$1.MIN_3 | Timeframe$1.MIN_5 | Timeframe$1.MIN_15 | Timeframe$1.MIN_30 | Timeframe$1.HOUR_1 | Timeframe$1.HOUR_2 | Timeframe$1.HOUR_4 | Timeframe$1.HOUR_6 | Timeframe$1.HOUR_8 | Timeframe$1.HOUR_12 | Timeframe$1.DAY_1 | Timeframe$1.DAY_3 | Timeframe$1.WEEK_1 | Timeframe$1.MONTH_1>]>;
162
162
  readonly limit: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 10000, undefined>]>, undefined>;
163
163
  readonly includeIncomplete: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
164
164
  readonly includeReference: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
@@ -49,7 +49,7 @@ declare const CheckpointBiggestTradeSchema: v.SchemaWithPipe<readonly [v.ObjectS
49
49
  side: number;
50
50
  at: number;
51
51
  }, {
52
- side: "unspecified" | "buy" | "sell";
52
+ side: "buy" | "sell" | "unspecified";
53
53
  symbolId: number;
54
54
  symbol: string;
55
55
  at: number;
@@ -229,7 +229,7 @@ declare const CheckpointSchema: v.ObjectSchema<{
229
229
  side: number;
230
230
  at: number;
231
231
  }, {
232
- side: "unspecified" | "buy" | "sell";
232
+ side: "buy" | "sell" | "unspecified";
233
233
  symbolId: number;
234
234
  symbol: string;
235
235
  at: number;
@@ -418,6 +418,12 @@ declare const CheckpointSchema: v.ObjectSchema<{
418
418
  readonly outflowUsd: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
419
419
  readonly netInflowUsd: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
420
420
  readonly finalValueUsd: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
421
+ /**
422
+ * Holdings restored when the season opened, valued at season end like `finalValueUsd`;
423
+ * `"0"` when the season opened with no balances.
424
+ */
425
+ readonly openingValueUsd: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
426
+ /** `finalValueUsd` minus `openingValueUsd` minus `netInflowUsd`; absent when any of them is. */
421
427
  readonly seasonResultUsd: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
422
428
  readonly subaccounts: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.MaxValueAction<bigint, bigint, undefined>, v.TransformAction<any, number>]>;
423
429
  /** Values computed from partial evidence; show them with an approximation marker. */
@@ -1 +1 @@
1
- {"version":3,"file":"checkpoints.schemas.d.ts","names":[],"sources":["../../../src/services/checkpoints/checkpoints.schemas.ts"],"mappings":";;cA2Ba,6BAA2B,EAAA;;;;;;;;;;;;KAO5B,wBAAwB,EAAE,mBAAmB;cAE5C,qCAAmC,EAAA;;;;;;;;;;;KAMpC,gCAAgC,EAAE,mBACnC;cAcE,8BAA4B,EAAA;;;;;;KAO7B,yBAAyB,EAAE,mBAAmB;cAE7C,8BAA4B,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;KAa7B,yBAAyB,EAAE,mBAAmB;cAE7C,iCAA+B,EAAA;;;;KAKhC,4BAA4B,EAAE,mBAAmB;cAEhD,mCAAiC,EAAA;;;;;;KAOlC,8BAA8B,EAAE,mBAAmB;cAElD,iCAA+B,EAAA;;;;;;;KAQhC,4BAA4B,EAAE,mBAAmB;cAEhD,+BAA6B,EAAA;;;;KAK9B,0BAA0B,EA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AKhC,4BAA4B,EAAE,mBAAmB;cAEhD,mCAAiC,EAAA;;;;;;KAOlC,8BAA8B,EAAE,mBAAmB;cAElD,iCAA+B,EAAA;;;;;;;KAQhC,4BAA4B,EAAE,mBAAmB;cAEhD,+BAA6B,EAAA;;;;KAK9B,0BAA0B,EAAE,mBAAmB;cAE9C,6BAA2B,EAAA;;;;;;;;;;KAK5B,wBAAwB,EAAE,mBAAmB;;;;;;cAO5C,6BAA2B,EAAA,yBAAA,EAAA;;;;;;;;;;;KAa5B,wBAAwB,EAAE,mBAAmB;;cAG5C,2BAAyB,EAAA;;;;KAK1B,sBAAsB,EAAE,mBAAmB;cAI1C,2BAAyB,EAAA;;;;;;;;;;KAM1B,sBAAsB,EAAE,mBAAmB;cAE1C,oCAAkC,EAAA;;;;;;;;;;;;;;;;;;;;;;;;KAMnC,+BAA+B,EAAE,mBAAmB;cAInD,4BAA0B,EAAA;;;;;KAM3B,uBAAuB,EAAE,mBAAmB;cAE3C,kBAAgB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAgFjB,aAAa,EAAE,mBAAmB;cAOjC,4BAA0B,EAAA;;;KAO3B,uBAAuB,EAAE,kBAAkB"}
@@ -163,6 +163,12 @@ const CheckpointSchema = v.object({
163
163
  outflowUsd: v.optional(UnsignedDecimalSchema),
164
164
  netInflowUsd: v.optional(SignedDecimalSchema),
165
165
  finalValueUsd: v.optional(SignedDecimalSchema),
166
+ /**
167
+ * Holdings restored when the season opened, valued at season end like `finalValueUsd`;
168
+ * `"0"` when the season opened with no balances.
169
+ */
170
+ openingValueUsd: v.optional(UnsignedDecimalSchema),
171
+ /** `finalValueUsd` minus `openingValueUsd` minus `netInflowUsd`; absent when any of them is. */
166
172
  seasonResultUsd: v.optional(SignedDecimalSchema),
167
173
  subaccounts: CountSchema,
168
174
  /** Values computed from partial evidence; show them with an approximation marker. */
@@ -1 +1 @@
1
- {"version":3,"file":"checkpoints.schemas.js","names":[],"sources":["../../../src/services/checkpoints/checkpoints.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { enumLabel, enumLabelSchema } from \"../../shared/proto-enum-codec.js\";\nimport {\n OptionalTimestampMsSchema,\n optionalSubaccountIdInputSchema,\n TimestampMsSchema,\n} from \"../../shared/schemas.js\";\nimport { OrderSideCodec } from \"../orders/order-enums.codecs.js\";\nimport { CheckpointBadgeCodec, CheckpointFieldCodec } from \"./checkpoints.codecs.js\";\n\n// Money values and ratios stay base-10 decimal strings so consumers parse them\n// with a decimal type; the contract marks which ones may be negative.\nconst UnsignedDecimalSchema = v.pipe(v.string(), v.regex(/^\\d+(\\.\\d+)?$/));\nconst SignedDecimalSchema = v.pipe(v.string(), v.regex(/^-?\\d+(\\.\\d+)?$/));\nconst RatioSchema = v.pipe(v.string(), v.regex(/^(0(\\.\\d+)?|1(\\.0+)?)$/));\nconst UtcDateSchema = v.pipe(v.string(), v.isoDate());\n\n// uint64 counts surface as numbers; a count past 2^53 would lose precision, so it fails instead.\nconst CountSchema = v.pipe(\n v.bigint(),\n v.maxValue(BigInt(Number.MAX_SAFE_INTEGER)),\n v.transform(Number),\n);\n\nconst VipTierSchema = v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(10));\nconst UtcHourSchema = v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(23));\n\nexport const CheckpointVolumePointSchema = v.object({\n day: TimestampMsSchema,\n usd: UnsignedDecimalSchema,\n approximate: v.boolean(),\n trades: CountSchema,\n});\n\nexport type CheckpointVolumePoint = v.InferOutput<typeof CheckpointVolumePointSchema>;\n\nexport const CheckpointPortfolioValuePointSchema = v.object({\n hour: TimestampMsSchema,\n usd: SignedDecimalSchema,\n approximate: v.boolean(),\n});\n\nexport type CheckpointPortfolioValuePoint = v.InferOutput<\n typeof CheckpointPortfolioValuePointSchema\n>;\n\n// Monday first; each row holds UTC hours 0 through 23.\nconst TradesByWeekdayHourSchema = v.pipe(\n v.array(\n v.pipe(\n v.object({ hours: v.pipe(v.array(CountSchema), v.length(24)) }),\n v.transform(({ hours }) => hours),\n ),\n ),\n v.length(7),\n);\n\nexport const CheckpointPairActivitySchema = v.object({\n symbolId: v.number(),\n symbol: v.string(),\n volumeUsd: UnsignedDecimalSchema,\n trades: CountSchema,\n});\n\nexport type CheckpointPairActivity = v.InferOutput<typeof CheckpointPairActivitySchema>;\n\nexport const CheckpointBiggestTradeSchema = v.pipe(\n v.object({\n symbolId: v.number(),\n symbol: v.string(),\n side: v.number(),\n at: TimestampMsSchema,\n }),\n v.transform(({ side, ...trade }) => ({\n ...trade,\n side: enumLabel(OrderSideCodec.protoToOutput, side),\n })),\n);\n\nexport type CheckpointBiggestTrade = v.InferOutput<typeof CheckpointBiggestTradeSchema>;\n\nexport const CheckpointOrderTypeCountsSchema = v.object({\n limit: CountSchema,\n market: CountSchema,\n});\n\nexport type CheckpointOrderTypeCounts = v.InferOutput<typeof CheckpointOrderTypeCountsSchema>;\n\nexport const CheckpointTimeInForceCountsSchema = v.object({\n gtc: CountSchema,\n ioc: CountSchema,\n fok: CountSchema,\n gtd: CountSchema,\n});\n\nexport type CheckpointTimeInForceCounts = v.InferOutput<typeof CheckpointTimeInForceCountsSchema>;\n\nexport const CheckpointOrderToolCountsSchema = v.object({\n stopLoss: CountSchema,\n takeProfit: CountSchema,\n trailingStop: CountSchema,\n twap: CountSchema,\n ladder: CountSchema,\n});\n\nexport type CheckpointOrderToolCounts = v.InferOutput<typeof CheckpointOrderToolCountsSchema>;\n\nexport const CheckpointVipTierChangeSchema = v.object({\n date: UtcDateSchema,\n tier: VipTierSchema,\n});\n\nexport type CheckpointVipTierChange = v.InferOutput<typeof CheckpointVipTierChangeSchema>;\n\nexport const CheckpointEarnedBadgeSchema = v.object({\n badge: enumLabelSchema(CheckpointBadgeCodec.protoToOutput),\n earnedAt: TimestampMsSchema,\n});\n\nexport type CheckpointEarnedBadge = v.InferOutput<typeof CheckpointEarnedBadgeSchema>;\n\n/**\n * `usd` is `undefined` when the asset had no USD price at the required time; it is not zero.\n * `excludedFromValue` marks an asset that is not account equity, such as a testnet faucet\n * token: it is listed by amount only, never has `usd`, and is left out of every USD total.\n */\nexport const CheckpointAssetAmountSchema = v.pipe(\n v.object({\n asset: v.string(),\n amount: SignedDecimalSchema,\n usd: v.optional(SignedDecimalSchema),\n excludedFromValue: v.boolean(),\n }),\n v.check(\n (amount) => !amount.excludedFromValue || amount.usd === undefined,\n \"usd: must be absent for an asset excluded from value\",\n ),\n);\n\nexport type CheckpointAssetAmount = v.InferOutput<typeof CheckpointAssetAmountSchema>;\n\n/** `usd` is `undefined` when any operation had no USD value; it is not zero. */\nexport const CheckpointFlowTotalSchema = v.object({\n count: CountSchema,\n usd: v.optional(UnsignedDecimalSchema),\n});\n\nexport type CheckpointFlowTotal = v.InferOutput<typeof CheckpointFlowTotalSchema>;\n\nconst EmptyFlowTotal = { count: 0n };\n\nexport const CheckpointChainFlowSchema = v.object({\n polyesterChainId: v.number(),\n chainName: v.string(),\n total: v.optional(CheckpointFlowTotalSchema, EmptyFlowTotal),\n});\n\nexport type CheckpointChainFlow = v.InferOutput<typeof CheckpointChainFlowSchema>;\n\nexport const CheckpointFundingFlowSummarySchema = v.object({\n count: CountSchema,\n chains: v.optional(v.array(CheckpointChainFlowSchema), []),\n amounts: v.optional(v.array(CheckpointAssetAmountSchema), []),\n});\n\nexport type CheckpointFundingFlowSummary = v.InferOutput<typeof CheckpointFundingFlowSummarySchema>;\n\nconst EmptyFundingFlowSummary = { count: 0n };\n\nexport const CheckpointFundingDaySchema = v.object({\n date: UtcDateSchema,\n depositUsd: v.optional(UnsignedDecimalSchema),\n withdrawalUsd: v.optional(UnsignedDecimalSchema),\n});\n\nexport type CheckpointFundingDay = v.InferOutput<typeof CheckpointFundingDaySchema>;\n\nexport const CheckpointSchema = v.object({\n number: v.pipe(v.number(), v.integer(), v.minValue(1)),\n seasonStart: TimestampMsSchema,\n seasonEnd: TimestampMsSchema,\n takenAt: TimestampMsSchema,\n volumeUsd: UnsignedDecimalSchema,\n trades: CountSchema,\n orders: CountSchema,\n daysActive: v.number(),\n longestStreak: v.number(),\n topPairs: v.optional(v.array(CheckpointPairActivitySchema), []),\n marketsTraded: v.number(),\n makerTrades: CountSchema,\n takerTrades: CountSchema,\n selfTrades: CountSchema,\n tradesByWeekdayHour: TradesByWeekdayHourSchema,\n dailyVolume: v.optional(v.array(CheckpointVolumePointSchema), []),\n biggestTradeUsd: UnsignedDecimalSchema,\n biggestTrade: v.optional(CheckpointBiggestTradeSchema),\n orderTypes: v.optional(CheckpointOrderTypeCountsSchema, { limit: 0n, market: 0n }),\n timeInForce: v.optional(CheckpointTimeInForceCountsSchema, {\n gtc: 0n,\n ioc: 0n,\n fok: 0n,\n gtd: 0n,\n }),\n tools: v.optional(CheckpointOrderToolCountsSchema, {\n stopLoss: 0n,\n takeProfit: 0n,\n trailingStop: 0n,\n twap: 0n,\n ladder: 0n,\n }),\n postOnly: CountSchema,\n amends: CountSchema,\n filledOrders: CountSchema,\n partiallyFilledOrders: CountSchema,\n canceledOrders: CountSchema,\n rejectedOrders: CountSchema,\n fillRate: RatioSchema,\n cancelRatio: RatioSchema,\n medianLimitRestMs: v.optional(CountSchema),\n firstTradeAt: OptionalTimestampMsSchema,\n busiestDay: v.optional(UtcDateSchema),\n mostActiveHourUtc: v.optional(UtcHourSchema),\n vipTierAtCheckpoint: VipTierSchema,\n peakVipTier: VipTierSchema,\n vipTimeline: v.optional(v.array(CheckpointVipTierChangeSchema), []),\n badges: v.optional(v.array(CheckpointEarnedBadgeSchema), []),\n portfolioValue: v.optional(v.array(CheckpointPortfolioValuePointSchema), []),\n tradingBalances: v.optional(v.array(CheckpointAssetAmountSchema), []),\n fundingBalances: v.optional(v.array(CheckpointAssetAmountSchema), []),\n deposits: v.optional(CheckpointFundingFlowSummarySchema, EmptyFundingFlowSummary),\n withdrawals: v.optional(CheckpointFundingFlowSummarySchema, EmptyFundingFlowSummary),\n fundingByDay: v.optional(v.array(CheckpointFundingDaySchema), []),\n transfersIn: v.optional(CheckpointFlowTotalSchema, EmptyFlowTotal),\n transfersOut: v.optional(CheckpointFlowTotalSchema, EmptyFlowTotal),\n internalTransfers: CountSchema,\n dailyClaims: CountSchema,\n dailyClaimAmounts: v.optional(v.array(CheckpointAssetAmountSchema), []),\n inflowUsd: v.optional(UnsignedDecimalSchema),\n outflowUsd: v.optional(UnsignedDecimalSchema),\n netInflowUsd: v.optional(SignedDecimalSchema),\n finalValueUsd: v.optional(SignedDecimalSchema),\n seasonResultUsd: v.optional(SignedDecimalSchema),\n subaccounts: CountSchema,\n /** Values computed from partial evidence; show them with an approximation marker. */\n incomplete: v.optional(v.array(enumLabelSchema(CheckpointFieldCodec.protoToOutput)), []),\n});\n\n/**\n * One frozen season recap of a root account and all of its subaccounts. An absent USD value\n * means the value was unavailable, not zero.\n */\nexport type Checkpoint = v.InferOutput<typeof CheckpointSchema>;\n\nexport const ListCheckpointsResultSchema = v.object({\n checkpoints: v.optional(v.array(CheckpointSchema), []),\n});\n\n// A present `subaccountId` of zero names no subaccount, so it fails here instead of reaching the server.\nexport const ListCheckpointsInputSchema = v.strictObject({\n subaccountId: v.pipe(\n optionalSubaccountIdInputSchema(),\n v.check((value) => value !== 0n, \"subaccountId: must be greater than zero\"),\n ),\n});\n\nexport type ListCheckpointsInput = v.InferInput<typeof ListCheckpointsInputSchema>;\n"],"mappings":";;;;;;AAYA,MAAM,wBAAwB,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,MAAM,eAAe,CAAC;AACzE,MAAM,sBAAsB,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,gBAAgB,EAAE,SAAS,EAAE,MAAM,mCAAmC,GAAG,CAAC,CAAC;CAC3E,iBAAiB,EAAE,SAAS,EAAE,MAAM,2BAA2B,GAAG,CAAC,CAAC;CACpE,iBAAiB,EAAE,SAAS,EAAE,MAAM,2BAA2B,GAAG,CAAC,CAAC;CACpE,UAAU,EAAE,SAAS,oCAAoC,uBAAuB;CAChF,aAAa,EAAE,SAAS,oCAAoC,uBAAuB;CACnF,cAAc,EAAE,SAAS,EAAE,MAAM,0BAA0B,GAAG,CAAC,CAAC;CAChE,aAAa,EAAE,SAAS,2BAA2B,cAAc;CACjE,cAAc,EAAE,SAAS,2BAA2B,cAAc;CAClE,mBAAmB;CACnB,aAAa;CACb,mBAAmB,EAAE,SAAS,EAAE,MAAM,2BAA2B,GAAG,CAAC,CAAC;CACtE,WAAW,EAAE,SAAS,qBAAqB;CAC3C,YAAY,EAAE,SAAS,qBAAqB;CAC5C,cAAc,EAAE,SAAS,mBAAmB;CAC5C,eAAe,EAAE,SAAS,mBAAmB;CAC7C,iBAAiB,EAAE,SAAS,mBAAmB;CAC/C,aAAa;;CAEb,YAAY,EAAE,SAAS,EAAE,MAAM,gBAAgB,qBAAqB,aAAa,CAAC,GAAG,CAAC,CAAC;AAC3F,CAAC;AAQD,MAAa,8BAA8B,EAAE,OAAO,EAChD,aAAa,EAAE,SAAS,EAAE,MAAM,gBAAgB,GAAG,CAAC,CAAC,EACzD,CAAC;AAGD,MAAa,6BAA6B,EAAE,aAAa,EACrD,cAAc,EAAE,KACZ,gCAAgC,GAChC,EAAE,OAAO,UAAU,UAAU,IAAI,yCAAyC,CAC9E,EACJ,CAAC"}
1
+ {"version":3,"file":"checkpoints.schemas.js","names":[],"sources":["../../../src/services/checkpoints/checkpoints.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { enumLabel, enumLabelSchema } from \"../../shared/proto-enum-codec.js\";\nimport {\n OptionalTimestampMsSchema,\n optionalSubaccountIdInputSchema,\n TimestampMsSchema,\n} from \"../../shared/schemas.js\";\nimport { OrderSideCodec } from \"../orders/order-enums.codecs.js\";\nimport { CheckpointBadgeCodec, CheckpointFieldCodec } from \"./checkpoints.codecs.js\";\n\n// Money values and ratios stay base-10 decimal strings so consumers parse them\n// with a decimal type; the contract marks which ones may be negative.\nconst UnsignedDecimalSchema = v.pipe(v.string(), v.regex(/^\\d+(\\.\\d+)?$/));\nconst SignedDecimalSchema = v.pipe(v.string(), v.regex(/^-?\\d+(\\.\\d+)?$/));\nconst RatioSchema = v.pipe(v.string(), v.regex(/^(0(\\.\\d+)?|1(\\.0+)?)$/));\nconst UtcDateSchema = v.pipe(v.string(), v.isoDate());\n\n// uint64 counts surface as numbers; a count past 2^53 would lose precision, so it fails instead.\nconst CountSchema = v.pipe(\n v.bigint(),\n v.maxValue(BigInt(Number.MAX_SAFE_INTEGER)),\n v.transform(Number),\n);\n\nconst VipTierSchema = v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(10));\nconst UtcHourSchema = v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(23));\n\nexport const CheckpointVolumePointSchema = v.object({\n day: TimestampMsSchema,\n usd: UnsignedDecimalSchema,\n approximate: v.boolean(),\n trades: CountSchema,\n});\n\nexport type CheckpointVolumePoint = v.InferOutput<typeof CheckpointVolumePointSchema>;\n\nexport const CheckpointPortfolioValuePointSchema = v.object({\n hour: TimestampMsSchema,\n usd: SignedDecimalSchema,\n approximate: v.boolean(),\n});\n\nexport type CheckpointPortfolioValuePoint = v.InferOutput<\n typeof CheckpointPortfolioValuePointSchema\n>;\n\n// Monday first; each row holds UTC hours 0 through 23.\nconst TradesByWeekdayHourSchema = v.pipe(\n v.array(\n v.pipe(\n v.object({ hours: v.pipe(v.array(CountSchema), v.length(24)) }),\n v.transform(({ hours }) => hours),\n ),\n ),\n v.length(7),\n);\n\nexport const CheckpointPairActivitySchema = v.object({\n symbolId: v.number(),\n symbol: v.string(),\n volumeUsd: UnsignedDecimalSchema,\n trades: CountSchema,\n});\n\nexport type CheckpointPairActivity = v.InferOutput<typeof CheckpointPairActivitySchema>;\n\nexport const CheckpointBiggestTradeSchema = v.pipe(\n v.object({\n symbolId: v.number(),\n symbol: v.string(),\n side: v.number(),\n at: TimestampMsSchema,\n }),\n v.transform(({ side, ...trade }) => ({\n ...trade,\n side: enumLabel(OrderSideCodec.protoToOutput, side),\n })),\n);\n\nexport type CheckpointBiggestTrade = v.InferOutput<typeof CheckpointBiggestTradeSchema>;\n\nexport const CheckpointOrderTypeCountsSchema = v.object({\n limit: CountSchema,\n market: CountSchema,\n});\n\nexport type CheckpointOrderTypeCounts = v.InferOutput<typeof CheckpointOrderTypeCountsSchema>;\n\nexport const CheckpointTimeInForceCountsSchema = v.object({\n gtc: CountSchema,\n ioc: CountSchema,\n fok: CountSchema,\n gtd: CountSchema,\n});\n\nexport type CheckpointTimeInForceCounts = v.InferOutput<typeof CheckpointTimeInForceCountsSchema>;\n\nexport const CheckpointOrderToolCountsSchema = v.object({\n stopLoss: CountSchema,\n takeProfit: CountSchema,\n trailingStop: CountSchema,\n twap: CountSchema,\n ladder: CountSchema,\n});\n\nexport type CheckpointOrderToolCounts = v.InferOutput<typeof CheckpointOrderToolCountsSchema>;\n\nexport const CheckpointVipTierChangeSchema = v.object({\n date: UtcDateSchema,\n tier: VipTierSchema,\n});\n\nexport type CheckpointVipTierChange = v.InferOutput<typeof CheckpointVipTierChangeSchema>;\n\nexport const CheckpointEarnedBadgeSchema = v.object({\n badge: enumLabelSchema(CheckpointBadgeCodec.protoToOutput),\n earnedAt: TimestampMsSchema,\n});\n\nexport type CheckpointEarnedBadge = v.InferOutput<typeof CheckpointEarnedBadgeSchema>;\n\n/**\n * `usd` is `undefined` when the asset had no USD price at the required time; it is not zero.\n * `excludedFromValue` marks an asset that is not account equity, such as a testnet faucet\n * token: it is listed by amount only, never has `usd`, and is left out of every USD total.\n */\nexport const CheckpointAssetAmountSchema = v.pipe(\n v.object({\n asset: v.string(),\n amount: SignedDecimalSchema,\n usd: v.optional(SignedDecimalSchema),\n excludedFromValue: v.boolean(),\n }),\n v.check(\n (amount) => !amount.excludedFromValue || amount.usd === undefined,\n \"usd: must be absent for an asset excluded from value\",\n ),\n);\n\nexport type CheckpointAssetAmount = v.InferOutput<typeof CheckpointAssetAmountSchema>;\n\n/** `usd` is `undefined` when any operation had no USD value; it is not zero. */\nexport const CheckpointFlowTotalSchema = v.object({\n count: CountSchema,\n usd: v.optional(UnsignedDecimalSchema),\n});\n\nexport type CheckpointFlowTotal = v.InferOutput<typeof CheckpointFlowTotalSchema>;\n\nconst EmptyFlowTotal = { count: 0n };\n\nexport const CheckpointChainFlowSchema = v.object({\n polyesterChainId: v.number(),\n chainName: v.string(),\n total: v.optional(CheckpointFlowTotalSchema, EmptyFlowTotal),\n});\n\nexport type CheckpointChainFlow = v.InferOutput<typeof CheckpointChainFlowSchema>;\n\nexport const CheckpointFundingFlowSummarySchema = v.object({\n count: CountSchema,\n chains: v.optional(v.array(CheckpointChainFlowSchema), []),\n amounts: v.optional(v.array(CheckpointAssetAmountSchema), []),\n});\n\nexport type CheckpointFundingFlowSummary = v.InferOutput<typeof CheckpointFundingFlowSummarySchema>;\n\nconst EmptyFundingFlowSummary = { count: 0n };\n\nexport const CheckpointFundingDaySchema = v.object({\n date: UtcDateSchema,\n depositUsd: v.optional(UnsignedDecimalSchema),\n withdrawalUsd: v.optional(UnsignedDecimalSchema),\n});\n\nexport type CheckpointFundingDay = v.InferOutput<typeof CheckpointFundingDaySchema>;\n\nexport const CheckpointSchema = v.object({\n number: v.pipe(v.number(), v.integer(), v.minValue(1)),\n seasonStart: TimestampMsSchema,\n seasonEnd: TimestampMsSchema,\n takenAt: TimestampMsSchema,\n volumeUsd: UnsignedDecimalSchema,\n trades: CountSchema,\n orders: CountSchema,\n daysActive: v.number(),\n longestStreak: v.number(),\n topPairs: v.optional(v.array(CheckpointPairActivitySchema), []),\n marketsTraded: v.number(),\n makerTrades: CountSchema,\n takerTrades: CountSchema,\n selfTrades: CountSchema,\n tradesByWeekdayHour: TradesByWeekdayHourSchema,\n dailyVolume: v.optional(v.array(CheckpointVolumePointSchema), []),\n biggestTradeUsd: UnsignedDecimalSchema,\n biggestTrade: v.optional(CheckpointBiggestTradeSchema),\n orderTypes: v.optional(CheckpointOrderTypeCountsSchema, { limit: 0n, market: 0n }),\n timeInForce: v.optional(CheckpointTimeInForceCountsSchema, {\n gtc: 0n,\n ioc: 0n,\n fok: 0n,\n gtd: 0n,\n }),\n tools: v.optional(CheckpointOrderToolCountsSchema, {\n stopLoss: 0n,\n takeProfit: 0n,\n trailingStop: 0n,\n twap: 0n,\n ladder: 0n,\n }),\n postOnly: CountSchema,\n amends: CountSchema,\n filledOrders: CountSchema,\n partiallyFilledOrders: CountSchema,\n canceledOrders: CountSchema,\n rejectedOrders: CountSchema,\n fillRate: RatioSchema,\n cancelRatio: RatioSchema,\n medianLimitRestMs: v.optional(CountSchema),\n firstTradeAt: OptionalTimestampMsSchema,\n busiestDay: v.optional(UtcDateSchema),\n mostActiveHourUtc: v.optional(UtcHourSchema),\n vipTierAtCheckpoint: VipTierSchema,\n peakVipTier: VipTierSchema,\n vipTimeline: v.optional(v.array(CheckpointVipTierChangeSchema), []),\n badges: v.optional(v.array(CheckpointEarnedBadgeSchema), []),\n portfolioValue: v.optional(v.array(CheckpointPortfolioValuePointSchema), []),\n tradingBalances: v.optional(v.array(CheckpointAssetAmountSchema), []),\n fundingBalances: v.optional(v.array(CheckpointAssetAmountSchema), []),\n deposits: v.optional(CheckpointFundingFlowSummarySchema, EmptyFundingFlowSummary),\n withdrawals: v.optional(CheckpointFundingFlowSummarySchema, EmptyFundingFlowSummary),\n fundingByDay: v.optional(v.array(CheckpointFundingDaySchema), []),\n transfersIn: v.optional(CheckpointFlowTotalSchema, EmptyFlowTotal),\n transfersOut: v.optional(CheckpointFlowTotalSchema, EmptyFlowTotal),\n internalTransfers: CountSchema,\n dailyClaims: CountSchema,\n dailyClaimAmounts: v.optional(v.array(CheckpointAssetAmountSchema), []),\n inflowUsd: v.optional(UnsignedDecimalSchema),\n outflowUsd: v.optional(UnsignedDecimalSchema),\n netInflowUsd: v.optional(SignedDecimalSchema),\n finalValueUsd: v.optional(SignedDecimalSchema),\n /**\n * Holdings restored when the season opened, valued at season end like `finalValueUsd`;\n * `\"0\"` when the season opened with no balances.\n */\n openingValueUsd: v.optional(UnsignedDecimalSchema),\n /** `finalValueUsd` minus `openingValueUsd` minus `netInflowUsd`; absent when any of them is. */\n seasonResultUsd: v.optional(SignedDecimalSchema),\n subaccounts: CountSchema,\n /** Values computed from partial evidence; show them with an approximation marker. */\n incomplete: v.optional(v.array(enumLabelSchema(CheckpointFieldCodec.protoToOutput)), []),\n});\n\n/**\n * One frozen season recap of a root account and all of its subaccounts. An absent USD value\n * means the value was unavailable, not zero.\n */\nexport type Checkpoint = v.InferOutput<typeof CheckpointSchema>;\n\nexport const ListCheckpointsResultSchema = v.object({\n checkpoints: v.optional(v.array(CheckpointSchema), []),\n});\n\n// A present `subaccountId` of zero names no subaccount, so it fails here instead of reaching the server.\nexport const ListCheckpointsInputSchema = v.strictObject({\n subaccountId: v.pipe(\n optionalSubaccountIdInputSchema(),\n v.check((value) => value !== 0n, \"subaccountId: must be greater than zero\"),\n ),\n});\n\nexport type ListCheckpointsInput = v.InferInput<typeof ListCheckpointsInputSchema>;\n"],"mappings":";;;;;;AAYA,MAAM,wBAAwB,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,MAAM,eAAe,CAAC;AACzE,MAAM,sBAAsB,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,MAAM,iBAAiB,CAAC;AACzE,MAAM,cAAc,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,MAAM,wBAAwB,CAAC;AACxE,MAAM,gBAAgB,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC;AAGpD,MAAM,cAAc,EAAE,KAClB,EAAE,OAAO,GACT,EAAE,SAAS,OAAO,OAAO,gBAAgB,CAAC,GAC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SAAS,EAAE,MAAM,0BAA0B,GAAG,CAAC,CAAC;CAChE,aAAa,EAAE,SAAS,2BAA2B,cAAc;CACjE,cAAc,EAAE,SAAS,2BAA2B,cAAc;CAClE,mBAAmB;CACnB,aAAa;CACb,mBAAmB,EAAE,SAAS,EAAE,MAAM,2BAA2B,GAAG,CAAC,CAAC;CACtE,WAAW,EAAE,SAAS,qBAAqB;CAC3C,YAAY,EAAE,SAAS,qBAAqB;CAC5C,cAAc,EAAE,SAAS,mBAAmB;CAC5C,eAAe,EAAE,SAAS,mBAAmB;;;;;CAK7C,iBAAiB,EAAE,SAAS,qBAAqB;;CAEjD,iBAAiB,EAAE,SAAS,mBAAmB;CAC/C,aAAa;;CAEb,YAAY,EAAE,SAAS,EAAE,MAAM,gBAAgB,qBAAqB,aAAa,CAAC,GAAG,CAAC,CAAC;AAC3F,CAAC;AAQD,MAAa,8BAA8B,EAAE,OAAO,EAChD,aAAa,EAAE,SAAS,EAAE,MAAM,gBAAgB,GAAG,CAAC,CAAC,EACzD,CAAC;AAGD,MAAa,6BAA6B,EAAE,aAAa,EACrD,cAAc,EAAE,KACZ,gCAAgC,GAChC,EAAE,OAAO,UAAU,UAAU,IAAI,yCAAyC,CAC9E,EACJ,CAAC"}
@@ -14,7 +14,7 @@ type TimestampInit = {
14
14
  declare const GetOrderbookHeatmapInputSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
15
15
  readonly symbolId: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 4294967295, undefined>]>;
16
16
  readonly interval: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["1s", "1m", "5m", "1h"], undefined>, "1s">, v.TransformAction<"1h" | "1m" | "1s" | "5m", HeatmapInterval>]>;
17
- readonly depth: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly [1, 5, 10, 20, 50, 100, 200, 500, 1000], undefined>, 50>, v.TransformAction<1 | 5 | 10 | 20 | 100 | 500 | 1000 | 200 | 50, HeatmapDepth>]>;
17
+ readonly depth: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly [1, 5, 10, 20, 50, 100, 200, 500, 1000], undefined>, 50>, v.TransformAction<1 | 5 | 10 | 20 | 100 | 500 | 200 | 1000 | 50, HeatmapDepth>]>;
18
18
  readonly quantityMode: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["close", "peak"], undefined>, "close">, v.TransformAction<"close" | "peak", HeatmapQuantityMode>]>;
19
19
  readonly limit: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 20000, undefined>]>;
20
20
  readonly startTsSec: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>, v.MaxValueAction<number, number, undefined>, v.TransformAction<number, bigint>]>, undefined>;
@@ -227,7 +227,7 @@ type OrderbookHeatmapDeltaChain = ReturnType<typeof convertHeatmapDeltaChain>;
227
227
  declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
228
228
  readonly symbolId: v.NumberSchema<undefined>;
229
229
  readonly interval: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1h" | "1m" | "1s" | "5m">>]>;
230
- readonly depth: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, 1 | 5 | 10 | 20 | "unspecified" | 100 | 500 | 1000 | 200 | 50>]>;
230
+ readonly depth: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, 1 | 5 | 10 | 20 | "unspecified" | 100 | 500 | 200 | 1000 | 50>]>;
231
231
  readonly chain: v.OptionalSchema<v.ObjectSchema<{
232
232
  readonly baseKeyframe: v.OptionalSchema<v.ObjectSchema<{
233
233
  readonly tsSec: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, number>]>;
@@ -287,7 +287,7 @@ declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.Sche
287
287
  }, undefined>, v.TransformAction<{
288
288
  symbolId: number;
289
289
  interval: DecodedEnum<"1h" | "1m" | "1s" | "5m">;
290
- depth: 1 | 5 | 10 | 20 | "unspecified" | 100 | 500 | 1000 | 200 | 50;
290
+ depth: 1 | 5 | 10 | 20 | "unspecified" | 100 | 500 | 200 | 1000 | 50;
291
291
  chain?: {
292
292
  baseKeyframe?: {
293
293
  tsSec: number;
@@ -347,7 +347,7 @@ declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.Sche
347
347
  }, {
348
348
  symbolId: number;
349
349
  interval: DecodedEnum<"1h" | "1m" | "1s" | "5m">;
350
- depth: 1 | 5 | 10 | 20 | "unspecified" | 100 | 500 | 1000 | 200 | 50;
350
+ depth: 1 | 5 | 10 | 20 | "unspecified" | 100 | 500 | 200 | 1000 | 50;
351
351
  chain: {
352
352
  baseKeyframe: {
353
353
  tsSec: number;