@polyester/sdk 0.36.0-devnet-20261119050221 → 0.36.0-devnet-20261119184734
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.
- package/CHANGELOG.md +15 -1
- package/dist/gen/ai/v1/assistant_pb.d.ts +1 -1
- package/dist/gen/ai/v1/assistant_pb.js +1 -1
- package/dist/gen/alerts/v1/price_alerts_pb.d.ts +1 -1
- package/dist/gen/auth/v1/activity_pb.d.ts +1 -1
- package/dist/gen/auth/v1/address_book_pb.d.ts +1 -1
- package/dist/gen/auth/v1/api_keys_pb.d.ts +1 -1
- package/dist/gen/auth/v1/auth_pb.d.ts +1 -1
- package/dist/gen/auth/v1/connected_apps_pb.d.ts +1 -1
- package/dist/gen/auth/v1/mfa_pb.d.ts +1 -1
- package/dist/gen/auth/v1/policies_pb.d.ts +1 -1
- package/dist/gen/auth/v1/profile_pb.d.ts +1 -1
- package/dist/gen/auth/v1/resolve_pb.d.ts +1 -1
- package/dist/gen/auth/v1/social_verification_pb.d.ts +1 -1
- package/dist/gen/auth/v1/subaccounts_pb.d.ts +1 -1
- package/dist/gen/auth/v1/subaccounts_pb.js +1 -1
- package/dist/gen/chain/analytics/v1/analytics_read_pb.d.ts +1 -1
- package/dist/gen/chain/deposit/v1/deposit_pb.d.ts +1 -1
- package/dist/gen/chain/guard/v1/guard_signer_pb.d.ts +1 -1
- package/dist/gen/chain/lifecycle/v1/lifecycle_read_pb.d.ts +1 -1
- package/dist/gen/chain/lifecycle/v1/types_pb.d.ts +1 -1
- package/dist/gen/chain/withdraw/v1/auto_withdraw_pb.d.ts +1 -1
- package/dist/gen/chain/withdraw/v1/withdraw_pb.d.ts +1 -1
- package/dist/gen/chain/zipper/v1/reason_pb.d.ts +1 -1
- package/dist/gen/chain/zipper/v1/zipper_pb.d.ts +1 -1
- package/dist/gen/changelog/v1/changelog_pb.d.ts +1 -1
- package/dist/gen/checkpoints/v1/checkpoints_pb.d.ts +1 -1
- package/dist/gen/claims/v1/claims_pb.d.ts +1 -1
- package/dist/gen/fees/v1/fees_pb.d.ts +1 -1
- package/dist/gen/index.js +24 -24
- package/dist/gen/ledger/read/v1/ledger_read_pb.d.ts +1 -1
- package/dist/gen/ledger/read/v1/statement_export_pb.d.ts +1 -1
- package/dist/gen/marketdata/v1/asset_info_pb.d.ts +1 -1
- package/dist/gen/marketdata/v1/heatmap_pb.d.ts +1 -1
- package/dist/gen/marketdata/v1/marketdata_pb.d.ts +1 -1
- package/dist/gen/marketoverview/v1/marketoverview_pb.d.ts +1 -1
- package/dist/gen/notifications/v1/notifications_pb.d.ts +1 -1
- package/dist/gen/orderbook/v1/orderbook_pb.d.ts +1 -1
- package/dist/gen/orders/v1/orders_pb.d.ts +1 -1
- package/dist/gen/orders/v1/orders_read_pb.d.ts +1 -1
- package/dist/gen/polyester/api/v1/request_error_pb.d.ts +1 -1
- package/dist/gen/polyester/ratelimit/v1/types_pb.d.ts +1 -1
- package/dist/gen/polyester/type/v1/u128_pb.d.ts +1 -1
- package/dist/gen/privatews/v1/private_ws_pb.d.ts +1 -1
- package/dist/gen/ratelimit/v1/ratelimit_pb.d.ts +1 -1
- package/dist/gen/rewards/v1/rewards_pb.d.ts +1 -1
- package/dist/gen/swap/quickswap/v1/quickswap_broker_pb.d.ts +1 -1
- package/dist/gen/swap/quickswap/v1/quickswap_explorer_pb.d.ts +1 -1
- package/dist/gen/swap/quickswap/v1/quickswap_pb.d.ts +1 -1
- package/dist/gen/swap/quickswap/v1/quickswap_referral_pb.d.ts +1 -1
- package/dist/gen/swap/v1/swap_pb.d.ts +1 -1
- package/dist/gen/system/v1/system_pb.d.ts +1 -1
- package/dist/gen/tradews/v1/trade_ws_pb.d.ts +1 -1
- package/dist/gen/transfer/v1/dust_conversion_pb.d.ts +1 -1
- package/dist/gen/transfer/v1/internal_transfer_pb.d.ts +1 -1
- package/dist/gen/triggers/v1/triggers_pb.d.ts +1 -1
- package/dist/gen/vip/v1/vip_pb.d.ts +1 -1
- package/dist/realtime/client.js +7 -1
- package/dist/realtime/client.js.map +1 -1
- package/dist/services/account-activity/account-activity.js +1 -1
- package/dist/services/account-activity/account-activity.schemas.d.ts +6 -6
- package/dist/services/accounts/accounts.js +1 -1
- package/dist/services/accounts/accounts.schemas.js +1 -1
- package/dist/services/address-book/address-book.schemas.d.ts +2 -2
- package/dist/services/api-keys/api-keys.schemas.d.ts +3 -3
- package/dist/services/assistant/assistant-events.schemas.d.ts +35 -35
- package/dist/services/assistant/assistant.js +1 -1
- package/dist/services/assistant/assistant.schemas.d.ts +2 -2
- package/dist/services/auth/account-signer-auth.d.ts.map +1 -1
- package/dist/services/auth/account-signer-auth.js +10 -2
- package/dist/services/auth/account-signer-auth.js.map +1 -1
- package/dist/services/auth/profile/profile.js +1 -1
- package/dist/services/auto-withdraw/auto-withdraw.js +1 -1
- package/dist/services/auto-withdraw/auto-withdraw.schemas.d.ts +16 -16
- package/dist/services/auto-withdraw/auto-withdraw.schemas.js +1 -1
- package/dist/services/candles/candles.js +1 -1
- package/dist/services/candles/candles.schemas.d.ts +10 -10
- package/dist/services/chain-analytics/chain-analytics.js +1 -1
- package/dist/services/changelog/changelog.js +1 -1
- package/dist/services/changelog/changelog.schemas.d.ts +38 -38
- package/dist/services/checkpoints/checkpoints.js +1 -1
- package/dist/services/checkpoints/checkpoints.schemas.d.ts +1 -1
- package/dist/services/claims/claims.js +1 -1
- package/dist/services/claims/claims.schemas.d.ts +2 -2
- package/dist/services/claims/claims.schemas.js +1 -1
- package/dist/services/connected-apps/connected-apps.js +1 -1
- package/dist/services/deposit/deposit.js +1 -1
- package/dist/services/dust-conversion/dust-conversion.js +1 -1
- package/dist/services/dust-conversion/dust-conversion.schemas.d.ts +8 -8
- package/dist/services/dust-conversion/dust-conversion.schemas.js +1 -1
- package/dist/services/fees/fees.js +1 -1
- package/dist/services/guard-signer/guard-signer.js +1 -1
- package/dist/services/heatmap/heatmap.js +1 -1
- package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
- package/dist/services/internal-transfers/internal-transfers.js +1 -1
- package/dist/services/internal-transfers/internal-transfers.schemas.d.ts +6 -6
- package/dist/services/lifecycle/lifecycle.js +1 -1
- package/dist/services/lifecycle/lifecycle.schemas.d.ts +91 -91
- package/dist/services/lifecycle/lifecycle.schemas.js +2 -2
- package/dist/services/market-data/market-data.js +1 -1
- package/dist/services/market-overview/market-overview.js +9 -2
- package/dist/services/market-overview/market-overview.js.map +1 -1
- package/dist/services/market-overview/market-overview.schemas.js +1 -1
- package/dist/services/notifications/notifications.js +1 -1
- package/dist/services/notifications/notifications.schemas.d.ts +4 -4
- package/dist/services/orderbook/orderbook.d.ts +1 -1
- package/dist/services/orderbook/orderbook.js +9 -3
- package/dist/services/orderbook/orderbook.js.map +1 -1
- package/dist/services/orders/order-errors.schemas.d.ts +9 -9
- package/dist/services/orders/order-errors.schemas.js +1 -1
- package/dist/services/orders/orders-batch.schemas.d.ts +110 -110
- package/dist/services/orders/orders-batch.schemas.js +1 -1
- package/dist/services/orders/orders-identifiers.schemas.js +2 -2
- package/dist/services/orders/orders-identifiers.schemas.js.map +1 -1
- package/dist/services/orders/orders-input.schemas.d.ts +24 -24
- package/dist/services/orders/orders-input.schemas.js +1 -1
- package/dist/services/orders/orders-modify.schemas.d.ts +3 -3
- package/dist/services/orders/orders-modify.schemas.js +1 -1
- package/dist/services/orders/orders-output.schemas.d.ts +14 -14
- package/dist/services/orders/orders-risk.schemas.js +2 -2
- package/dist/services/orders/orders.js +2 -2
- package/dist/services/policies/api-key-policies/api-key-policies.schemas.d.ts +1 -1
- package/dist/services/policies/api-key-policies/api-key-policies.schemas.d.ts.map +1 -1
- package/dist/services/policies/api-key-policies/api-key-policies.schemas.js +1 -1
- package/dist/services/policies/api-key-policies/api-key-policies.schemas.js.map +1 -1
- package/dist/services/price-alerts/price-alerts.js +1 -1
- package/dist/services/price-alerts/price-alerts.schemas.d.ts +10 -10
- package/dist/services/rate-limits/rate-limits.js +1 -1
- package/dist/services/rewards/rewards.js +1 -1
- package/dist/services/social-verification/social-verification.js +1 -1
- package/dist/services/social-verification/social-verification.schemas.js +1 -1
- package/dist/services/statement-exports/statement-exports.js +1 -1
- package/dist/services/statement-exports/statement-exports.schemas.d.ts +6 -6
- package/dist/services/subaccounts/subaccounts.schemas.d.ts +16 -16
- package/dist/services/system/system.js +1 -1
- package/dist/services/system/system.schemas.d.ts +13 -13
- package/dist/services/trades/trades.js +1 -1
- package/dist/services/trades/trades.schemas.d.ts +1 -1
- package/dist/services/trading-withdraws/trading-withdraws.js +1 -1
- package/dist/services/trading-withdraws/trading-withdraws.schemas.js +1 -1
- package/dist/services/trading-withdraws/wallet-message.js +1 -1
- package/dist/services/triggers/trigger-child-order.schemas.js +2 -2
- package/dist/services/triggers/trigger-input.schemas.d.ts +3 -3
- package/dist/services/triggers/trigger-input.schemas.js +2 -2
- package/dist/services/triggers/triggers-output.schemas.d.ts +60 -60
- package/dist/services/triggers/triggers.js +1 -1
- package/dist/services/vip/vip.js +1 -1
- package/dist/services/vip/vip.schemas.js +1 -1
- package/dist/services/zipper/zipper.js +1 -1
- package/dist/services/zipper/zipper.schemas.js +1 -1
- package/dist/shared/connect-error-mapping.js +17 -1
- package/dist/shared/connect-error-mapping.js.map +1 -1
- package/dist/shared/error-details/alerts.js +1 -1
- package/dist/shared/error-details/assistant.js +1 -1
- package/dist/shared/error-details/auth.js +1 -1
- package/dist/shared/error-details/claims.js +1 -1
- package/dist/shared/error-details/internal-transfer.js +1 -1
- package/dist/shared/error-details/ledger.js +1 -1
- package/dist/shared/error-details/market-overview.js +1 -1
- package/dist/shared/error-details/notifications.js +1 -1
- package/dist/shared/error-details/orders.js +1 -1
- package/dist/shared/error-details/profile.js +1 -1
- package/dist/shared/error-details/rate-limit.js +1 -1
- package/dist/shared/error-details/withdraw.js +1 -1
- package/dist/shared/rate-limit.schemas.d.ts +1 -1
- package/dist/shared/rate-limit.schemas.js +1 -1
- package/dist/wired-services.js +19 -19
- package/package.json +1 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import "../../gen/chain/lifecycle/v1/types_pb.js";
|
|
2
|
-
import "../../gen/chain/lifecycle/v1/lifecycle_read_pb.js";
|
|
3
1
|
import { enumLabelSchema } from "../../shared/proto-enum-codec.js";
|
|
4
2
|
import { fromU128 } from "../../utils/u128.js";
|
|
5
3
|
import { scaledToDecimalOutput } from "../../shared/decimal-surface.js";
|
|
6
4
|
import { AccountScopeInputEntries, accountScopeToSubaccountId } from "../../shared/account-scope.js";
|
|
5
|
+
import "../../gen/chain/lifecycle/v1/types_pb.js";
|
|
6
|
+
import "../../gen/chain/lifecycle/v1/lifecycle_read_pb.js";
|
|
7
7
|
import { LIFECYCLE_FLOW_KIND_VALUES, LIFECYCLE_FLOW_PARTICIPATION_VALUES, LIFECYCLE_FLOW_STATE_VALUES, LIFECYCLE_LIST_ORDER_BY_VALUES, LIFECYCLE_LIST_SCOPE_VALUES, LIFECYCLE_SORT_VALUES, LIFECYCLE_TX_LOOKUP_KIND_VALUES, LifecycleFlowDomainCodec, LifecycleFlowKindCodec, LifecycleFlowParticipationCodec, LifecycleFlowStateCodec, LifecycleFlowStepActivityKindCodec, LifecycleFlowStepCodec, LifecycleFlowTimelineStatusCodec, LifecycleListOrderByCodec, LifecycleListScopeCodec, LifecycleRequestFeeStatusCodec, LifecycleSortCodec, LifecycleSourceCodec, LifecycleTxLookupKindCodec, lifecycleReasonFromCode, zipperReasonFromCode } from "./lifecycle.codecs.js";
|
|
8
8
|
import * as v from "valibot";
|
|
9
9
|
//#region src/services/lifecycle/lifecycle.schemas.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { MarketDataService as MarketDataService$1, MarketTradeBatchSchema } from "../../gen/marketdata/v1/marketdata_pb.js";
|
|
2
1
|
import { parse } from "../../shared/validation.js";
|
|
3
2
|
import { toConnectCallOptions } from "../../shared/request-options.js";
|
|
4
3
|
import { deliverBatch } from "../../shared/subscription-errors.js";
|
|
5
4
|
import { SymbolIdInputSchema } from "../shared.js";
|
|
5
|
+
import { MarketDataService as MarketDataService$1, MarketTradeBatchSchema } from "../../gen/marketdata/v1/marketdata_pb.js";
|
|
6
6
|
import { connectReadyGatedProtoChannel } from "../../realtime/ready-gated-subscription.js";
|
|
7
7
|
import { isDev } from "../../utils/is-dev.js";
|
|
8
8
|
import { AssetInfoSchema, GetMarketTradesInputSchema, ListAssetInfoInputSchema, SpotConfigSchema, TradeBackfillSchema, formatMarketTrade } from "./market-data.schemas.js";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { MarketOverviewBatchSchema, MarketOverviewService as MarketOverviewService$1 } from "../../gen/marketoverview/v1/marketoverview_pb.js";
|
|
2
1
|
import { parse } from "../../shared/validation.js";
|
|
3
2
|
import { toConnectCallOptions } from "../../shared/request-options.js";
|
|
4
3
|
import { CatalogLookupError } from "../../catalogs/types.js";
|
|
5
4
|
import { isDev } from "../../utils/is-dev.js";
|
|
5
|
+
import { MarketOverviewBatchSchema, MarketOverviewService as MarketOverviewService$1 } from "../../gen/marketoverview/v1/marketoverview_pb.js";
|
|
6
6
|
import { snapshotThenStream } from "../../realtime/snapshot-then-stream.js";
|
|
7
7
|
import { CurrencyConversionConfigSchema, CurrencyConversionRatesSchema, ListMarketOverviewInputSchema, SpotVolumeHistoryInputSchema, SpotVolumeHistoryResponseSchema, createMarketOverviewSchema } from "./market-overview.schemas.js";
|
|
8
8
|
import { createClient } from "@connectrpc/connect";
|
|
@@ -94,7 +94,14 @@ var MarketOverviewService = class {
|
|
|
94
94
|
return symbolIds.size === 0 || symbolIds.has(market.symbolId);
|
|
95
95
|
}
|
|
96
96
|
function applyMarkets(markets) {
|
|
97
|
-
for (const market of markets)
|
|
97
|
+
for (const market of markets) {
|
|
98
|
+
if (!matchesSymbol(market)) continue;
|
|
99
|
+
const sparklines = bySymbolId.get(market.symbolId)?.sparklines;
|
|
100
|
+
bySymbolId.set(market.symbolId, market.sparklines.length === 0 && sparklines ? {
|
|
101
|
+
...market,
|
|
102
|
+
sparklines
|
|
103
|
+
} : market);
|
|
104
|
+
}
|
|
98
105
|
}
|
|
99
106
|
async function fetchSnapshot() {
|
|
100
107
|
return (await listMarketOverview({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"market-overview.js","names":["#client","Proto.MarketOverviewService","#realtime","#scales","#marketOverviewSchema","#decodeMarkets","Proto.MarketOverviewBatchSchema"],"sources":["../../../src/services/market-overview/market-overview.ts"],"sourcesContent":["import * as Proto from \"../../gen/marketoverview/v1/marketoverview_pb.js\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport { parse } from \"../../shared/validation.js\";\nimport { CatalogLookupError } from \"../../catalogs/types.js\";\nimport { isDev } from \"../../utils/is-dev.js\";\nimport type { PolyesterRealtime } from \"../../realtime/types.js\";\nimport { snapshotThenStream } from \"../../realtime/snapshot-then-stream.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport {\n toConnectCallOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport type { SdkScales } from \"../../shared/decimal-surface.js\";\nimport type { PublicApiTransports } from \"../../shared/transports.js\";\nimport {\n CurrencyConversionConfigSchema,\n CurrencyConversionRatesSchema,\n type CurrencyConversionConfig,\n type CurrencyConversionRates,\n SpotVolumeHistoryInputSchema,\n SpotVolumeHistoryResponseSchema,\n type SpotVolumeHistoryInput,\n type SpotVolumeHistoryResponse,\n ListMarketOverviewInputSchema,\n createMarketOverviewSchema,\n type SparklineIntervalName,\n type ListMarketOverviewInput,\n type MarketOverview,\n} from \"./market-overview.schemas.js\";\n\ninterface SubscribeMarketOverviewInput extends BaseSubscribeInput<MarketOverview[]> {\n symbolIds?: number[];\n includeSparklines?: boolean;\n sparklineIntervals?: SparklineIntervalName[];\n}\n\n/**\n * Provides ticker-style per-market stats and a live merged overview stream.\n */\nexport class MarketOverviewService {\n #client: Client<typeof Proto.MarketOverviewService>;\n #realtime: PolyesterRealtime;\n #scales: SdkScales;\n #marketOverviewSchema: ReturnType<typeof createMarketOverviewSchema>;\n\n constructor(transports: PublicApiTransports, realtime: PolyesterRealtime, scales: SdkScales) {\n this.#client = createClient(Proto.MarketOverviewService, transports.publicApi);\n this.#realtime = realtime;\n this.#scales = scales;\n this.#marketOverviewSchema = createMarketOverviewSchema(scales);\n }\n\n /**\n * Returns market overview rows with last and index prices, 24h stats, top-of-book values, listing timestamp, and optional sparklines. Supports symbol ID filtering, sorting, pagination, and sparkline interval selection. A symbol ID that names no configured market is rejected as an invalid argument instead of returning an empty page.\n */\n async list(\n input: ListMarketOverviewInput = {},\n options?: PolyesterRequestOptions,\n ): Promise<{ markets: MarketOverview[]; nextPageToken: string }> {\n const validatedInput = parse(ListMarketOverviewInputSchema, input);\n await this.#scales.ready();\n const res = await this.#client.listMarketOverview(\n validatedInput,\n toConnectCallOptions(options),\n );\n return {\n markets: this.#decodeMarkets(res.markets),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Returns 97 aligned trailing-24h USD volume samples at 15-minute intervals.\n * Empty symbolIds selects all pairs. Samples overlap and must not be summed\n * as period volume. Unavailable valuations reject the request.\n */\n async getSpotVolumeHistory(\n input: SpotVolumeHistoryInput = {},\n options?: PolyesterRequestOptions,\n ): Promise<SpotVolumeHistoryResponse> {\n const validated = parse(SpotVolumeHistoryInputSchema, input);\n const response = await this.#client.getSpotVolumeHistory(\n validated,\n toConnectCallOptions(options),\n );\n return parse(SpotVolumeHistoryResponseSchema, response);\n }\n\n /** Returns cacheable display metadata, even before rates have been observed. */\n async getCurrencyConversionConfig(\n options?: PolyesterRequestOptions,\n ): Promise<CurrencyConversionConfig> {\n const response = await this.#client.getCurrencyConversionConfig(\n {},\n toConnectCallOptions(options),\n );\n return parse(CurrencyConversionConfigSchema, response);\n }\n\n /**\n * Returns exact decimal rates with observation times and backend staleness flags.\n * Fiat is units per USD; stablecoins are USD per unit. Unobserved rates remain absent.\n * Rejects as unavailable before any observation exists.\n */\n async getCurrencyConversionRates(\n options?: PolyesterRequestOptions,\n ): Promise<CurrencyConversionRates> {\n const response = await this.#client.getCurrencyConversionRates(\n {},\n toConnectCallOptions(options),\n );\n return parse(CurrencyConversionRatesSchema, response);\n }\n\n /**\n * Decodes market rows, skipping any whose symbolId the catalog cannot resolve\n * (unknown or disabled pairs the backend still reports). Other errors propagate.\n */\n #decodeMarkets(markets: readonly Proto.MarketOverview[]): MarketOverview[] {\n const decoded: MarketOverview[] = [];\n const skipped: number[] = [];\n for (const m of markets) {\n try {\n decoded.push(parse(this.#marketOverviewSchema, m));\n } catch (error) {\n if (\n error instanceof CatalogLookupError &&\n error.domain === \"market\" &&\n error.lookup === \"symbolId\"\n ) {\n skipped.push(m.symbolId);\n continue;\n }\n throw error;\n }\n }\n if (skipped.length > 0 && isDev()) {\n console.warn(\n `[market-overview] skipped ${skipped.length} row(s) with unknown symbolId: ${skipped.join(\", \")}`,\n );\n }\n return decoded;\n }\n\n /**\n * Subscribes to public:spot:market_overview:updates:proto, fetches an initial snapshot, buffers updates until ready, and emits the merged set of latest market rows. On reconnect it refetches the snapshot before resuming updates.\n */\n subscribe(input: SubscribeMarketOverviewInput): () => void {\n const channel = \"public:spot:market_overview:updates:proto\";\n const bySymbolId = new Map<number, MarketOverview>();\n const symbolIds = new Set(input.symbolIds);\n const includeSparklines = input.includeSparklines ?? true;\n const sparklineIntervals = input.sparklineIntervals ?? [\"24h\"];\n const listMarketOverview = this.list.bind(this);\n const parseMarkets = this.#decodeMarkets.bind(this);\n function emit(): void {\n input.onEvent(Array.from(bySymbolId.values()));\n }\n\n function matchesSymbol(market: { symbolId: number }): boolean {\n return symbolIds.size === 0 || symbolIds.has(market.symbolId);\n }\n\n function applyMarkets(markets: readonly MarketOverview[]): void {\n for (const market of markets) {\n if (matchesSymbol(market)) bySymbolId.set(market.symbolId, market);\n }\n }\n\n async function fetchSnapshot(): Promise<MarketOverview[]> {\n const result = await listMarketOverview({\n symbolIds: input.symbolIds,\n includeSparklines,\n sparklineIntervals,\n });\n return result.markets;\n }\n\n const stream = snapshotThenStream({\n realtime: this.#realtime,\n channel,\n schema: Proto.MarketOverviewBatchSchema,\n maxBufferedPublications: 2000,\n snapshotErrorLog: \"Failed to fetch market overview\",\n fetchSnapshot,\n readPublication: (batch) => batch.markets.filter(matchesSymbol),\n bufferPublicationKey: (market) => market.symbolId,\n applySnapshot: (markets, bufferedMarkets) => {\n bySymbolId.clear();\n applyMarkets(markets);\n applyMarkets(parseMarkets(bufferedMarkets));\n emit();\n },\n applyLivePublications: (markets) => {\n applyMarkets(parseMarkets(markets));\n emit();\n },\n onOpen: input.onOpen,\n onClose: input.onClose,\n onError: input.onError,\n });\n\n function dispose(): void {\n stream.unsubscribe();\n }\n\n return dispose;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAuCA,IAAa,wBAAb,MAAmC;CAC/B;CACA;CACA;CACA;CAEA,YAAY,YAAiC,UAA6B,QAAmB;EACzF,KAAKA,UAAU,aAAaC,yBAA6B,WAAW,SAAS;EAC7E,KAAKC,YAAY;EACjB,KAAKC,UAAU;EACf,KAAKC,wBAAwB,2BAA2B,MAAM;CAClE;;;;CAKA,MAAM,KACF,QAAiC,CAAC,GAClC,SAC6D;EAC7D,MAAM,iBAAiB,MAAM,+BAA+B,KAAK;EACjE,MAAM,KAAKD,QAAQ,MAAM;EACzB,MAAM,MAAM,MAAM,KAAKH,QAAQ,mBAC3B,gBACA,qBAAqB,OAAO,CAChC;EACA,OAAO;GACH,SAAS,KAAKK,eAAe,IAAI,OAAO;GACxC,eAAe,IAAI;EACvB;CACJ;;;;;;CAOA,MAAM,qBACF,QAAgC,CAAC,GACjC,SACkC;EAClC,MAAM,YAAY,MAAM,8BAA8B,KAAK;EAC3D,MAAM,WAAW,MAAM,KAAKL,QAAQ,qBAChC,WACA,qBAAqB,OAAO,CAChC;EACA,OAAO,MAAM,iCAAiC,QAAQ;CAC1D;;CAGA,MAAM,4BACF,SACiC;EACjC,MAAM,WAAW,MAAM,KAAKA,QAAQ,4BAChC,CAAC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BAA2C;GAMtD,QAAO,MALc,mBAAmB;IACpC,WAAW,MAAM;IACjB;IACA;GACJ,CAAC,EAAA,CACa;EAClB;EAEA,MAAM,SAAS,mBAAmB;GAC9B,UAAU,KAAKH;GACf;GACA,QAAQI;GACR,yBAAyB;GACzB,kBAAkB;GAClB;GACA,kBAAkB,UAAU,MAAM,QAAQ,OAAO,aAAa;GAC9D,uBAAuB,WAAW,OAAO;GACzC,gBAAgB,SAAS,oBAAoB;IACzC,WAAW,MAAM;IACjB,aAAa,OAAO;IACpB,aAAa,aAAa,eAAe,CAAC;IAC1C,KAAK;GACT;GACA,wBAAwB,YAAY;IAChC,aAAa,aAAa,OAAO,CAAC;IAClC,KAAK;GACT;GACA,QAAQ,MAAM;GACd,SAAS,MAAM;GACf,SAAS,MAAM;EACnB,CAAC;EAED,SAAS,UAAgB;GACrB,OAAO,YAAY;EACvB;EAEA,OAAO;CACX;AACJ"}
|
|
1
|
+
{"version":3,"file":"market-overview.js","names":["#client","Proto.MarketOverviewService","#realtime","#scales","#marketOverviewSchema","#decodeMarkets","Proto.MarketOverviewBatchSchema"],"sources":["../../../src/services/market-overview/market-overview.ts"],"sourcesContent":["import * as Proto from \"../../gen/marketoverview/v1/marketoverview_pb.js\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport { parse } from \"../../shared/validation.js\";\nimport { CatalogLookupError } from \"../../catalogs/types.js\";\nimport { isDev } from \"../../utils/is-dev.js\";\nimport type { PolyesterRealtime } from \"../../realtime/types.js\";\nimport { snapshotThenStream } from \"../../realtime/snapshot-then-stream.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport {\n toConnectCallOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport type { SdkScales } from \"../../shared/decimal-surface.js\";\nimport type { PublicApiTransports } from \"../../shared/transports.js\";\nimport {\n CurrencyConversionConfigSchema,\n CurrencyConversionRatesSchema,\n type CurrencyConversionConfig,\n type CurrencyConversionRates,\n SpotVolumeHistoryInputSchema,\n SpotVolumeHistoryResponseSchema,\n type SpotVolumeHistoryInput,\n type SpotVolumeHistoryResponse,\n ListMarketOverviewInputSchema,\n createMarketOverviewSchema,\n type SparklineIntervalName,\n type ListMarketOverviewInput,\n type MarketOverview,\n} from \"./market-overview.schemas.js\";\n\ninterface SubscribeMarketOverviewInput extends BaseSubscribeInput<MarketOverview[]> {\n symbolIds?: number[];\n includeSparklines?: boolean;\n sparklineIntervals?: SparklineIntervalName[];\n}\n\n/**\n * Provides ticker-style per-market stats and a live merged overview stream.\n */\nexport class MarketOverviewService {\n #client: Client<typeof Proto.MarketOverviewService>;\n #realtime: PolyesterRealtime;\n #scales: SdkScales;\n #marketOverviewSchema: ReturnType<typeof createMarketOverviewSchema>;\n\n constructor(transports: PublicApiTransports, realtime: PolyesterRealtime, scales: SdkScales) {\n this.#client = createClient(Proto.MarketOverviewService, transports.publicApi);\n this.#realtime = realtime;\n this.#scales = scales;\n this.#marketOverviewSchema = createMarketOverviewSchema(scales);\n }\n\n /**\n * Returns market overview rows with last and index prices, 24h stats, top-of-book values, listing timestamp, and optional sparklines. Supports symbol ID filtering, sorting, pagination, and sparkline interval selection. A symbol ID that names no configured market is rejected as an invalid argument instead of returning an empty page.\n */\n async list(\n input: ListMarketOverviewInput = {},\n options?: PolyesterRequestOptions,\n ): Promise<{ markets: MarketOverview[]; nextPageToken: string }> {\n const validatedInput = parse(ListMarketOverviewInputSchema, input);\n await this.#scales.ready();\n const res = await this.#client.listMarketOverview(\n validatedInput,\n toConnectCallOptions(options),\n );\n return {\n markets: this.#decodeMarkets(res.markets),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Returns 97 aligned trailing-24h USD volume samples at 15-minute intervals.\n * Empty symbolIds selects all pairs. Samples overlap and must not be summed\n * as period volume. Unavailable valuations reject the request.\n */\n async getSpotVolumeHistory(\n input: SpotVolumeHistoryInput = {},\n options?: PolyesterRequestOptions,\n ): Promise<SpotVolumeHistoryResponse> {\n const validated = parse(SpotVolumeHistoryInputSchema, input);\n const response = await this.#client.getSpotVolumeHistory(\n validated,\n toConnectCallOptions(options),\n );\n return parse(SpotVolumeHistoryResponseSchema, response);\n }\n\n /** Returns cacheable display metadata, even before rates have been observed. */\n async getCurrencyConversionConfig(\n options?: PolyesterRequestOptions,\n ): Promise<CurrencyConversionConfig> {\n const response = await this.#client.getCurrencyConversionConfig(\n {},\n toConnectCallOptions(options),\n );\n return parse(CurrencyConversionConfigSchema, response);\n }\n\n /**\n * Returns exact decimal rates with observation times and backend staleness flags.\n * Fiat is units per USD; stablecoins are USD per unit. Unobserved rates remain absent.\n * Rejects as unavailable before any observation exists.\n */\n async getCurrencyConversionRates(\n options?: PolyesterRequestOptions,\n ): Promise<CurrencyConversionRates> {\n const response = await this.#client.getCurrencyConversionRates(\n {},\n toConnectCallOptions(options),\n );\n return parse(CurrencyConversionRatesSchema, response);\n }\n\n /**\n * Decodes market rows, skipping any whose symbolId the catalog cannot resolve\n * (unknown or disabled pairs the backend still reports). Other errors propagate.\n */\n #decodeMarkets(markets: readonly Proto.MarketOverview[]): MarketOverview[] {\n const decoded: MarketOverview[] = [];\n const skipped: number[] = [];\n for (const m of markets) {\n try {\n decoded.push(parse(this.#marketOverviewSchema, m));\n } catch (error) {\n if (\n error instanceof CatalogLookupError &&\n error.domain === \"market\" &&\n error.lookup === \"symbolId\"\n ) {\n skipped.push(m.symbolId);\n continue;\n }\n throw error;\n }\n }\n if (skipped.length > 0 && isDev()) {\n console.warn(\n `[market-overview] skipped ${skipped.length} row(s) with unknown symbolId: ${skipped.join(\", \")}`,\n );\n }\n return decoded;\n }\n\n /**\n * Subscribes to public:spot:market_overview:updates:proto, fetches an initial snapshot, buffers updates until ready, and emits the merged set of latest market rows. On reconnect it refetches the snapshot before resuming updates.\n */\n subscribe(input: SubscribeMarketOverviewInput): () => void {\n const channel = \"public:spot:market_overview:updates:proto\";\n const bySymbolId = new Map<number, MarketOverview>();\n const symbolIds = new Set(input.symbolIds);\n const includeSparklines = input.includeSparklines ?? true;\n const sparklineIntervals = input.sparklineIntervals ?? [\"24h\"];\n const listMarketOverview = this.list.bind(this);\n const parseMarkets = this.#decodeMarkets.bind(this);\n function emit(): void {\n input.onEvent(Array.from(bySymbolId.values()));\n }\n\n function matchesSymbol(market: { symbolId: number }): boolean {\n return symbolIds.size === 0 || symbolIds.has(market.symbolId);\n }\n\n function applyMarkets(markets: readonly MarketOverview[]): void {\n for (const market of markets) {\n if (!matchesSymbol(market)) continue;\n // The live channel carries no sparklines; keep the snapshot's.\n const sparklines = bySymbolId.get(market.symbolId)?.sparklines;\n bySymbolId.set(\n market.symbolId,\n market.sparklines.length === 0 && sparklines\n ? { ...market, sparklines }\n : market,\n );\n }\n }\n\n async function fetchSnapshot(): Promise<MarketOverview[]> {\n const result = await listMarketOverview({\n symbolIds: input.symbolIds,\n includeSparklines,\n sparklineIntervals,\n });\n return result.markets;\n }\n\n const stream = snapshotThenStream({\n realtime: this.#realtime,\n channel,\n schema: Proto.MarketOverviewBatchSchema,\n maxBufferedPublications: 2000,\n snapshotErrorLog: \"Failed to fetch market overview\",\n fetchSnapshot,\n readPublication: (batch) => batch.markets.filter(matchesSymbol),\n bufferPublicationKey: (market) => market.symbolId,\n applySnapshot: (markets, bufferedMarkets) => {\n bySymbolId.clear();\n applyMarkets(markets);\n applyMarkets(parseMarkets(bufferedMarkets));\n emit();\n },\n applyLivePublications: (markets) => {\n applyMarkets(parseMarkets(markets));\n emit();\n },\n onOpen: input.onOpen,\n onClose: input.onClose,\n onError: input.onError,\n });\n\n function dispose(): void {\n stream.unsubscribe();\n }\n\n return dispose;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAuCA,IAAa,wBAAb,MAAmC;CAC/B;CACA;CACA;CACA;CAEA,YAAY,YAAiC,UAA6B,QAAmB;EACzF,KAAKA,UAAU,aAAaC,yBAA6B,WAAW,SAAS;EAC7E,KAAKC,YAAY;EACjB,KAAKC,UAAU;EACf,KAAKC,wBAAwB,2BAA2B,MAA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AY;EACvB;EAEA,OAAO;CACX;AACJ"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import "../../gen/marketoverview/v1/marketoverview_pb.js";
|
|
2
1
|
import { tsNsToMs } from "../../utils/time.js";
|
|
3
2
|
import { enumLabelSchema } from "../../shared/proto-enum-codec.js";
|
|
4
3
|
import { scaledToDecimalOutput } from "../../shared/decimal-surface.js";
|
|
5
4
|
import { PositiveUint32InputSchema, SymbolIdInputSchema } from "../shared.js";
|
|
5
|
+
import "../../gen/marketoverview/v1/marketoverview_pb.js";
|
|
6
6
|
import { MARKET_OVERVIEW_ORDER_BY_VALUES, MARKET_OVERVIEW_SORT_VALUES, MarketOverviewOrderByCodec, MarketOverviewSortCodec, SPARKLINE_INTERVAL_VALUES, SparklineIntervalCodec } from "./market-overview.codecs.js";
|
|
7
7
|
import * as v from "valibot";
|
|
8
8
|
//#region src/services/market-overview/market-overview.schemas.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { NotificationService } from "../../gen/notifications/v1/notifications_pb.js";
|
|
2
1
|
import { InternalServerError } from "../../shared/errors.js";
|
|
3
2
|
import { parse } from "../../shared/validation.js";
|
|
4
3
|
import { removeUndefined } from "../../utils/remove-undefined.js";
|
|
5
4
|
import { toConnectCallOptions } from "../../shared/request-options.js";
|
|
5
|
+
import { NotificationService } from "../../gen/notifications/v1/notifications_pb.js";
|
|
6
6
|
import { GetNotificationInputSchema, ListNotificationsInputSchema, MarkAllNotificationsReadInputSchema, MarkNotificationsInputSchema, formatNotification, formatNotificationCounts } from "./notifications.schemas.js";
|
|
7
7
|
import { createClient } from "@connectrpc/connect";
|
|
8
8
|
//#region src/services/notifications/notifications.ts
|
|
@@ -2,7 +2,7 @@ import { GetNotificationCountsResponse, Notification, NotificationCategory, Read
|
|
|
2
2
|
import * as v from "valibot";
|
|
3
3
|
//#region src/services/notifications/notifications.schemas.d.ts
|
|
4
4
|
declare const ListNotificationsInputSchema: v.SchemaWithPipe<readonly [v.StrictObjectSchema<{
|
|
5
|
-
readonly categories: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ArraySchema<v.PicklistSchema<readonly ["alerts", "security"], undefined>, undefined>, v.TransformAction<("
|
|
5
|
+
readonly categories: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ArraySchema<v.PicklistSchema<readonly ["alerts", "security"], undefined>, undefined>, v.TransformAction<("alerts" | "security")[], (NotificationCategory.ALERTS | NotificationCategory.SECURITY)[]>]>, undefined>;
|
|
6
6
|
/** Only read or only unread notifications; omit for both. */
|
|
7
7
|
readonly readState: v.OptionalSchema<v.PicklistSchema<readonly ["unread", "read"], undefined>, undefined>;
|
|
8
8
|
/** Epoch ms, inclusive. */
|
|
@@ -46,7 +46,7 @@ declare const MarkNotificationsInputSchema: v.StrictObjectSchema<{
|
|
|
46
46
|
}, undefined>;
|
|
47
47
|
type MarkNotificationsInput = v.InferInput<typeof MarkNotificationsInputSchema>;
|
|
48
48
|
declare const MarkAllNotificationsReadInputSchema: v.StrictObjectSchema<{
|
|
49
|
-
readonly categories: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ArraySchema<v.PicklistSchema<readonly ["alerts", "security"], undefined>, undefined>, v.TransformAction<("
|
|
49
|
+
readonly categories: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ArraySchema<v.PicklistSchema<readonly ["alerts", "security"], undefined>, undefined>, v.TransformAction<("alerts" | "security")[], (NotificationCategory.ALERTS | NotificationCategory.SECURITY)[]>]>, undefined>;
|
|
50
50
|
/**
|
|
51
51
|
* Mark only this notification and older ones. Pass the newest one shown, so one that arrives
|
|
52
52
|
* later stays unread; omit to mark every notification that exists when the call runs.
|
|
@@ -57,7 +57,7 @@ type MarkAllNotificationsReadInput = v.InferInput<typeof MarkAllNotificationsRea
|
|
|
57
57
|
declare function formatNotification(notification: Notification): {
|
|
58
58
|
notificationId: string;
|
|
59
59
|
type: "unspecified" | "price_alert" | "telegram_approval" | "broker_allowlist_change" | "telegram_linked" | "admin_key_action";
|
|
60
|
-
category: "unspecified" | "
|
|
60
|
+
category: "unspecified" | "alerts" | "security";
|
|
61
61
|
/** Plain-text title, the same for every notification of a type. */
|
|
62
62
|
title: string;
|
|
63
63
|
/** Plain-text summary; may span several lines. */
|
|
@@ -377,7 +377,7 @@ declare function formatNotificationCounts(counts: GetNotificationCountsResponse)
|
|
|
377
377
|
/** Every type in ascending enum order, including types with no notification. */
|
|
378
378
|
types: {
|
|
379
379
|
type: "unspecified" | "price_alert" | "telegram_approval" | "broker_allowlist_change" | "telegram_linked" | "admin_key_action";
|
|
380
|
-
category: "unspecified" | "
|
|
380
|
+
category: "unspecified" | "alerts" | "security";
|
|
381
381
|
total: number;
|
|
382
382
|
unread: number;
|
|
383
383
|
}[];
|
|
@@ -33,7 +33,7 @@ declare class OrderbookService {
|
|
|
33
33
|
*/
|
|
34
34
|
subscribe(input: SubscribeOrderbookInput): () => void;
|
|
35
35
|
/**
|
|
36
|
-
* Creates a stateful order book subscription that first fetches a snapshot, buffers proto deltas from public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto, applies each delta only when it chains onto the book, and refetches on reconnects. After a sequence gap the book holds its last state until the server's next reset, sent about every 30 seconds and after gaps. A snapshot whose book is not available fails with ServiceUnavailableError through onError and is retried
|
|
36
|
+
* Creates a stateful order book subscription that first fetches a snapshot, buffers proto deltas from public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto, applies each delta only when it chains onto the book, and refetches on reconnects. After a sequence gap the book holds its last state until the server's next reset, sent about every 30 seconds and after gaps. A snapshot whose book is not available fails with ServiceUnavailableError through onError and is retried. A snapshot error that is not retried (such as a 500) leaves the book to the server's next reset, which rebuilds it. The snapshot is fetched once the channel opens, so a socket that cannot connect reports a retryable RealtimeError with type "transport" through onError instead, once per outage; onOpen follows when it recovers. The returned handle can unsubscribe or change local price bucket aggregation without reconnecting.
|
|
37
37
|
*
|
|
38
38
|
* `depth` above 500 throws ValidationError, since only REST serves 1000 and 5000; other depths ride the smallest published channel depth that covers it (see ORDERBOOK_WS_DEPTHS); levels are sliced back to the requested depth locally.
|
|
39
39
|
*
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { ServiceUnavailableError, ValidationError } from "../../shared/errors.js";
|
|
1
|
+
import { PolyesterError, ServiceUnavailableError, ValidationError } from "../../shared/errors.js";
|
|
3
2
|
import { parse } from "../../shared/validation.js";
|
|
4
3
|
import { toConnectCallOptions } from "../../shared/request-options.js";
|
|
5
4
|
import { publicationHandlerErrorContext } from "../../shared/subscription-errors.js";
|
|
@@ -7,6 +6,7 @@ import { decimalInputToScaled } from "../../shared/decimal-surface.js";
|
|
|
7
6
|
import { isResourceNotFoundError } from "../../utils/errors.js";
|
|
8
7
|
import { DepthTierCodec } from "../../shared/depth-tier.js";
|
|
9
8
|
import { snapshotThenStream } from "../../realtime/snapshot-then-stream.js";
|
|
9
|
+
import { GetOrderBookResponseSchema, OrderBookDeltaSchema, OrderbookService as OrderbookService$1 } from "../../gen/orderbook/v1/orderbook_pb.js";
|
|
10
10
|
import { GetOrderbookInputSchema, createOrderbookDataSchema, formatOrderbookLevel } from "./orderbook.schemas.js";
|
|
11
11
|
import { orderbookWsChannelDepth } from "./orderbook.codecs.js";
|
|
12
12
|
import { create } from "@bufbuild/protobuf";
|
|
@@ -54,7 +54,7 @@ var OrderbookService = class {
|
|
|
54
54
|
return this.createSubscription(input).unsubscribe;
|
|
55
55
|
}
|
|
56
56
|
/**
|
|
57
|
-
* Creates a stateful order book subscription that first fetches a snapshot, buffers proto deltas from public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto, applies each delta only when it chains onto the book, and refetches on reconnects. After a sequence gap the book holds its last state until the server's next reset, sent about every 30 seconds and after gaps. A snapshot whose book is not available fails with ServiceUnavailableError through onError and is retried
|
|
57
|
+
* Creates a stateful order book subscription that first fetches a snapshot, buffers proto deltas from public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto, applies each delta only when it chains onto the book, and refetches on reconnects. After a sequence gap the book holds its last state until the server's next reset, sent about every 30 seconds and after gaps. A snapshot whose book is not available fails with ServiceUnavailableError through onError and is retried. A snapshot error that is not retried (such as a 500) leaves the book to the server's next reset, which rebuilds it. The snapshot is fetched once the channel opens, so a socket that cannot connect reports a retryable RealtimeError with type "transport" through onError instead, once per outage; onOpen follows when it recovers. The returned handle can unsubscribe or change local price bucket aggregation without reconnecting.
|
|
58
58
|
*
|
|
59
59
|
* `depth` above 500 throws ValidationError, since only REST serves 1000 and 5000; other depths ride the smallest published channel depth that covers it (see ORDERBOOK_WS_DEPTHS); levels are sliced back to the requested depth locally.
|
|
60
60
|
*
|
|
@@ -191,6 +191,12 @@ var OrderbookService = class {
|
|
|
191
191
|
delayMs: 1e3,
|
|
192
192
|
maxDelayMs: 8e3
|
|
193
193
|
},
|
|
194
|
+
snapshotFailureMode: (error) => {
|
|
195
|
+
if (!(error instanceof PolyesterError) || error.retryable) return "wait";
|
|
196
|
+
currentBookSeq = 0n;
|
|
197
|
+
awaitingReset = true;
|
|
198
|
+
return "live";
|
|
199
|
+
},
|
|
194
200
|
fetchSnapshot: inputServiceFetch,
|
|
195
201
|
readPublication: (delta) => [delta],
|
|
196
202
|
applySnapshot: (snapshot, bufferedDeltas) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orderbook.js","names":["#client","Proto.OrderbookService","#realtime","#scales","Proto.GetOrderBookResponseSchema","Proto.OrderBookDeltaSchema"],"sources":["../../../src/services/orderbook/orderbook.ts"],"sourcesContent":["import { create } from \"@bufbuild/protobuf\";\nimport * as Proto from \"../../gen/orderbook/v1/orderbook_pb.js\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport { publicationHandlerErrorContext } from \"../../shared/subscription-errors.js\";\nimport type { PolyesterRealtime } from \"../../realtime/types.js\";\nimport {\n snapshotThenStream,\n type SnapshotThenStreamSubscription,\n} from \"../../realtime/snapshot-then-stream.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport {\n toConnectCallOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport { decimalInputToScaled, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport {\n formatOrderbookLevel,\n GetOrderbookInputSchema,\n createOrderbookDataSchema,\n type OrderbookLevel,\n type OrderbookData,\n} from \"./orderbook.schemas.js\";\nimport { orderbookWsChannelDepth } from \"./orderbook.codecs.js\";\nimport { DepthTierCodec } from \"../../shared/depth-tier.js\";\nimport { isResourceNotFoundError } from \"../../utils/errors.js\";\nimport { ServiceUnavailableError, ValidationError } from \"../../shared/errors.js\";\nimport type * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport type { PublicApiTransports } from \"../../shared/transports.js\";\n\ninterface SubscribeOrderbookInput extends BaseSubscribeInput<OrderbookData> {\n symbolId: number;\n depth?: number;\n bucket?: string | null;\n}\n\nexport interface OrderbookStreamHandlers extends BaseSubscribeInput<OrderbookData> {}\n\nexport interface OrderbookSubscription {\n unsubscribe: () => void;\n setBucket: (bucket: string | null | undefined) => void;\n}\n\nexport interface CreateOrderbookSubscriptionInput\n extends\n OrderbookStreamHandlers,\n Pick<SubscribeOrderbookInput, \"symbolId\" | \"depth\" | \"bucket\"> {}\n\ntype BookSide = Map<bigint, bigint>;\n\n/**\n * Reads spot order book snapshots and maintains realtime local order book state from public delta channels.\n */\nexport class OrderbookService {\n #client: Client<typeof Proto.OrderbookService>;\n #realtime: PolyesterRealtime;\n #scales: SdkScales;\n\n constructor(transports: PublicApiTransports, realtime: PolyesterRealtime, scales: SdkScales) {\n this.#client = createClient(Proto.OrderbookService, transports.publicApi);\n this.#realtime = realtime;\n this.#scales = scales;\n }\n\n /**\n * Fetches a spot order book depth snapshot for a symbol ID and depth tier (`DEPTH_TIER_VALUES`, default 50), returning best bids and asks with the backend book sequence.\n * When `available` is false the book is being built or was invalidated: its levels are unknown, not empty, so read it again later instead of treating empty sides as no liquidity.\n */\n async get(\n input: v.InferInput<typeof GetOrderbookInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<OrderbookData> {\n const validated = parse(GetOrderbookInputSchema, input);\n await this.#scales.ready();\n const res = await this.#client.getOrderBook(\n { symbolId: validated.symbolId, depth: DepthTierCodec.inputToProto[validated.depth] },\n toConnectCallOptions(options),\n );\n // Servers that predate the served tier leave it unset; they served the requested one.\n const served = DepthTierCodec.protoToOutput[res.depth];\n return parse(createOrderbookDataSchema(this.#scales, validated.symbolId), {\n symbolId: res.symbolId,\n depth: typeof served === \"number\" ? served : validated.depth,\n bookSeq: res.bookSeq,\n bookEpoch: res.bookEpoch,\n available: isBookAvailable(res),\n bids: res.bids,\n asks: res.asks,\n ts: res.ts,\n });\n }\n\n /**\n * Subscribes to the managed order book stream for a symbol ID and forwards reconstructed snapshots to onEvent. This is a convenience wrapper around createSubscription().unsubscribe.\n */\n subscribe(input: SubscribeOrderbookInput): () => void {\n return this.createSubscription(input).unsubscribe;\n }\n\n /**\n * Creates a stateful order book subscription that first fetches a snapshot, buffers proto deltas from public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto, applies each delta only when it chains onto the book, and refetches on reconnects. After a sequence gap the book holds its last state until the server's next reset, sent about every 30 seconds and after gaps. A snapshot whose book is not available fails with ServiceUnavailableError through onError and is retried; no event is emitted until a snapshot is available. The snapshot is fetched once the channel opens, so a socket that cannot connect reports a retryable RealtimeError with type \"transport\" through onError instead, once per outage; onOpen follows when it recovers. The returned handle can unsubscribe or change local price bucket aggregation without reconnecting.\n *\n * `depth` above 500 throws ValidationError, since only REST serves 1000 and 5000; other depths ride the smallest published channel depth that covers it (see ORDERBOOK_WS_DEPTHS); levels are sliced back to the requested depth locally.\n *\n * A refetched snapshot from an older `bookEpoch` than the book's is discarded and retried.\n *\n * Refetching is driven by reconnect events only. A feed that stays subscribed but stops publishing is indistinguishable from a quiet market, so it does not trigger onError or a refetch. Callers that must detect a stalled book need their own idle watchdog plus a REST refetch.\n */\n createSubscription(input: CreateOrderbookSubscriptionInput): OrderbookSubscription {\n const { symbolId, depth } = parse(GetOrderbookInputSchema, {\n symbolId: input.symbolId,\n depth: input.depth,\n });\n if (depth > 500) {\n throw new ValidationError(\n `depth must be at most 500 for a managed order book, got ${depth}`,\n );\n }\n const channelDepth = orderbookWsChannelDepth(depth);\n const channel = `public:spot:orderbook:deltas:depth:${channelDepth}:${symbolId}:proto`;\n\n const client = this.#client;\n const scales = this.#scales;\n let bidsMap: BookSide = new Map();\n let asksMap: BookSide = new Map();\n let currentBookSeq = 0n;\n let currentBookEpoch = 0n;\n // Set when a delta does not chain onto the book; only the next reset recovers it.\n let awaitingReset = false;\n let bucketTicks: bigint | null = null;\n let stream: SnapshotThenStreamSubscription | undefined;\n\n function levelsToMap(levels: Proto.PriceLevel[] | undefined): BookSide {\n const map: BookSide = new Map();\n for (const l of levels ?? []) {\n if (l.qtyScaled === 0n) continue;\n map.set(l.priceTicks, l.qtyScaled);\n }\n return map;\n }\n\n function applySideDelta(map: BookSide, levels: Proto.PriceLevel[] | undefined): void {\n for (const l of levels ?? []) {\n if (l.qtyScaled === 0n) map.delete(l.priceTicks);\n else map.set(l.priceTicks, l.qtyScaled);\n }\n }\n\n function sideToUI(map: BookSide, side: \"bids\" | \"asks\", limit: number): OrderbookLevel[] {\n const entries = Array.from(map.entries());\n entries.sort(([pa], [pb]) => {\n if (pa === pb) return 0;\n return side === \"bids\" ? (pa > pb ? -1 : 1) : pa < pb ? -1 : 1;\n });\n return entries\n .slice(0, limit)\n .map(([priceTicks, qtyScaled]) =>\n formatOrderbookLevel({ priceTicks, qtyScaled }, scales, symbolId),\n );\n }\n\n function sideToUIBucketed(\n map: BookSide,\n side: \"bids\" | \"asks\",\n limit: number,\n bucket: bigint | null,\n ): OrderbookLevel[] {\n if (!bucket || bucket <= 0n) return sideToUI(map, side, limit);\n\n const agg: BookSide = new Map();\n for (const [priceTicks, qtyScaled] of map.entries()) {\n if (qtyScaled <= 0n) continue;\n const bucketFloor = (priceTicks / bucket) * bucket;\n const bucketPrice =\n side === \"asks\" && bucketFloor !== priceTicks\n ? bucketFloor + bucket\n : bucketFloor;\n agg.set(bucketPrice, (agg.get(bucketPrice) ?? 0n) + qtyScaled);\n }\n return sideToUI(agg, side, limit);\n }\n\n function emit(): void {\n try {\n input.onEvent({\n symbolId,\n depth,\n bookSeq: currentBookSeq.toString(),\n bookEpoch: currentBookEpoch.toString(),\n available: true,\n bids: sideToUIBucketed(bidsMap, \"bids\", depth, bucketTicks),\n asks: sideToUIBucketed(asksMap, \"asks\", depth, bucketTicks),\n });\n } catch (error) {\n input.onError?.(publicationHandlerErrorContext(channel, error));\n }\n }\n\n function setBucket(bucket: string | null | undefined): void {\n if (!bucket) {\n bucketTicks = null;\n } else {\n try {\n bucketTicks = decimalInputToScaled(\"bucket\", bucket, scales.price());\n } catch {\n bucketTicks = null;\n }\n }\n if (stream?.isReady()) emit();\n }\n\n async function inputServiceFetch(): Promise<Proto.GetOrderBookResponse> {\n await scales.ready();\n let res: Proto.GetOrderBookResponse;\n try {\n res = await client.getOrderBook({\n symbolId,\n depth: DepthTierCodec.inputToProto[channelDepth],\n });\n } catch (error: unknown) {\n if (!isResourceNotFoundError(error)) throw error;\n\n return create(Proto.GetOrderBookResponseSchema, {\n symbolId,\n bookSeq: 0n,\n available: true,\n bids: [],\n asks: [],\n });\n }\n // An unavailable book's levels are unknown, not empty: fail the snapshot so it is retried.\n if (!isBookAvailable(res)) {\n throw new ServiceUnavailableError(\n `Order book for symbol ${symbolId} is not available yet`,\n );\n }\n if (res.bookEpoch < currentBookEpoch) {\n throw new ServiceUnavailableError(\n `Order book snapshot for symbol ${symbolId} is from an older epoch`,\n );\n }\n return res;\n }\n\n /**\n * Applies a delta only when it chains onto the current book (`bookSeqStart` equals the\n * last applied `bookSeqEnd`) or is a reset. A delta that does not chain leaves the book\n * waiting for the next reset, which the server sends periodically and after a gap.\n */\n function handleDelta(delta: Proto.OrderBookDelta): void {\n if (delta.bookSeqEnd <= currentBookSeq) return;\n\n if (delta.reset) {\n bidsMap.clear();\n asksMap.clear();\n awaitingReset = false;\n } else if (awaitingReset || delta.bookSeqStart !== currentBookSeq) {\n awaitingReset = true;\n return;\n }\n\n applySideDelta(bidsMap, delta.bids);\n applySideDelta(asksMap, delta.asks);\n\n currentBookSeq = delta.bookSeqEnd;\n emit();\n }\n\n setBucket(input.bucket);\n stream = snapshotThenStream({\n realtime: this.#realtime,\n channel,\n schema: Proto.OrderBookDeltaSchema,\n maxBufferedPublications: 200,\n snapshotErrorLog: \"Failed to fetch orderbook\",\n // GetOrderBook answers unavailable while the book is (re)built; keep asking until it is ready.\n snapshotRetry: {\n maxAttempts: Number.POSITIVE_INFINITY,\n delayMs: 1_000,\n maxDelayMs: 8_000,\n },\n fetchSnapshot: inputServiceFetch,\n readPublication: (delta) => [delta],\n applySnapshot: (snapshot, bufferedDeltas) => {\n bidsMap = levelsToMap(snapshot.bids);\n asksMap = levelsToMap(snapshot.asks);\n currentBookSeq = snapshot.bookSeq;\n currentBookEpoch = snapshot.bookEpoch;\n awaitingReset = false;\n emit();\n for (const delta of bufferedDeltas) {\n if (stream?.isDisposed()) return;\n handleDelta(delta);\n }\n },\n applyLivePublications: (deltas) => {\n for (const delta of deltas) {\n if (stream?.isDisposed()) return;\n handleDelta(delta);\n }\n },\n onOpen: input.onOpen,\n onClose: input.onClose,\n onError: input.onError,\n });\n\n function dispose(): void {\n stream?.unsubscribe();\n }\n\n return { unsubscribe: dispose, setBucket };\n }\n}\n\n/**\n * Whether a snapshot's levels are the book. A snapshot carrying levels is current even with\n * `available` false, which is how servers that predate the field encode every snapshot.\n */\nfunction isBookAvailable(res: Proto.GetOrderBookResponse): boolean {\n return res.available || res.bids.length > 0 || res.asks.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqDA,IAAa,mBAAb,MAA8B;CAC1B;CACA;CACA;CAEA,YAAY,YAAiC,UAA6B,QAAmB;EACzF,KAAKA,UAAU,aAAaC,oBAAwB,WAAW,SAAS;EACxE,KAAKC,YAAY;EACjB,K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UAAU,CAAC,KAAK;GAClC,gBAAgB,UAAU,mBAAmB;IACzC,UAAU,YAAY,SAAS,IAAI;IACnC,UAAU,YAAY,SAAS,IAAI;IACnC,iBAAiB,SAAS;IAC1B,mBAAmB,SAAS;IAC5B,gBAAgB;IAChB,KAAK;IACL,KAAK,MAAM,SAAS,gBAAgB;KAChC,IAAI,QAAQ,WAAW,GAAG;KAC1B,YAAY,KAAK;IACrB;GACJ;GACA,wBAAwB,WAAW;IAC/B,KAAK,MAAM,SAAS,QAAQ;KACxB,IAAI,QAAQ,WAAW,GAAG;KAC1B,YAAY,KAAK;IACrB;GACJ;GACA,QAAQ,MAAM;GACd,SAAS,MAAM;GACf,SAAS,MAAM;EACnB,CAAC;EAED,SAAS,UAAgB;GACrB,QAAQ,YAAY;EACxB;EAEA,OAAO;GAAE,aAAa;GAAS;EAAU;CAC7C;AACJ;;;;;AAMA,SAAS,gBAAgB,KAA0C;CAC/D,OAAO,IAAI,aAAa,IAAI,KAAK,SAAS,KAAK,IAAI,KAAK,SAAS;AACrE"}
|
|
1
|
+
{"version":3,"file":"orderbook.js","names":["#client","Proto.OrderbookService","#realtime","#scales","Proto.GetOrderBookResponseSchema","Proto.OrderBookDeltaSchema"],"sources":["../../../src/services/orderbook/orderbook.ts"],"sourcesContent":["import { create } from \"@bufbuild/protobuf\";\nimport * as Proto from \"../../gen/orderbook/v1/orderbook_pb.js\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport { publicationHandlerErrorContext } from \"../../shared/subscription-errors.js\";\nimport type { PolyesterRealtime } from \"../../realtime/types.js\";\nimport {\n snapshotThenStream,\n type SnapshotThenStreamSubscription,\n} from \"../../realtime/snapshot-then-stream.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport {\n toConnectCallOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport { decimalInputToScaled, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport {\n formatOrderbookLevel,\n GetOrderbookInputSchema,\n createOrderbookDataSchema,\n type OrderbookLevel,\n type OrderbookData,\n} from \"./orderbook.schemas.js\";\nimport { orderbookWsChannelDepth } from \"./orderbook.codecs.js\";\nimport { DepthTierCodec } from \"../../shared/depth-tier.js\";\nimport { isResourceNotFoundError } from \"../../utils/errors.js\";\nimport { PolyesterError, ServiceUnavailableError, ValidationError } from \"../../shared/errors.js\";\nimport type * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport type { PublicApiTransports } from \"../../shared/transports.js\";\n\ninterface SubscribeOrderbookInput extends BaseSubscribeInput<OrderbookData> {\n symbolId: number;\n depth?: number;\n bucket?: string | null;\n}\n\nexport interface OrderbookStreamHandlers extends BaseSubscribeInput<OrderbookData> {}\n\nexport interface OrderbookSubscription {\n unsubscribe: () => void;\n setBucket: (bucket: string | null | undefined) => void;\n}\n\nexport interface CreateOrderbookSubscriptionInput\n extends\n OrderbookStreamHandlers,\n Pick<SubscribeOrderbookInput, \"symbolId\" | \"depth\" | \"bucket\"> {}\n\ntype BookSide = Map<bigint, bigint>;\n\n/**\n * Reads spot order book snapshots and maintains realtime local order book state from public delta channels.\n */\nexport class OrderbookService {\n #client: Client<typeof Proto.OrderbookService>;\n #realtime: PolyesterRealtime;\n #scales: SdkScales;\n\n constructor(transports: PublicApiTransports, realtime: PolyesterRealtime, scales: SdkScales) {\n this.#client = createClient(Proto.OrderbookService, transports.publicApi);\n this.#realtime = realtime;\n this.#scales = scales;\n }\n\n /**\n * Fetches a spot order book depth snapshot for a symbol ID and depth tier (`DEPTH_TIER_VALUES`, default 50), returning best bids and asks with the backend book sequence.\n * When `available` is false the book is being built or was invalidated: its levels are unknown, not empty, so read it again later instead of treating empty sides as no liquidity.\n */\n async get(\n input: v.InferInput<typeof GetOrderbookInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<OrderbookData> {\n const validated = parse(GetOrderbookInputSchema, input);\n await this.#scales.ready();\n const res = await this.#client.getOrderBook(\n { symbolId: validated.symbolId, depth: DepthTierCodec.inputToProto[validated.depth] },\n toConnectCallOptions(options),\n );\n // Servers that predate the served tier leave it unset; they served the requested one.\n const served = DepthTierCodec.protoToOutput[res.depth];\n return parse(createOrderbookDataSchema(this.#scales, validated.symbolId), {\n symbolId: res.symbolId,\n depth: typeof served === \"number\" ? served : validated.depth,\n bookSeq: res.bookSeq,\n bookEpoch: res.bookEpoch,\n available: isBookAvailable(res),\n bids: res.bids,\n asks: res.asks,\n ts: res.ts,\n });\n }\n\n /**\n * Subscribes to the managed order book stream for a symbol ID and forwards reconstructed snapshots to onEvent. This is a convenience wrapper around createSubscription().unsubscribe.\n */\n subscribe(input: SubscribeOrderbookInput): () => void {\n return this.createSubscription(input).unsubscribe;\n }\n\n /**\n * Creates a stateful order book subscription that first fetches a snapshot, buffers proto deltas from public:spot:orderbook:deltas:depth:{depth}:{symbolId}:proto, applies each delta only when it chains onto the book, and refetches on reconnects. After a sequence gap the book holds its last state until the server's next reset, sent about every 30 seconds and after gaps. A snapshot whose book is not available fails with ServiceUnavailableError through onError and is retried. A snapshot error that is not retried (such as a 500) leaves the book to the server's next reset, which rebuilds it. The snapshot is fetched once the channel opens, so a socket that cannot connect reports a retryable RealtimeError with type \"transport\" through onError instead, once per outage; onOpen follows when it recovers. The returned handle can unsubscribe or change local price bucket aggregation without reconnecting.\n *\n * `depth` above 500 throws ValidationError, since only REST serves 1000 and 5000; other depths ride the smallest published channel depth that covers it (see ORDERBOOK_WS_DEPTHS); levels are sliced back to the requested depth locally.\n *\n * A refetched snapshot from an older `bookEpoch` than the book's is discarded and retried.\n *\n * Refetching is driven by reconnect events only. A feed that stays subscribed but stops publishing is indistinguishable from a quiet market, so it does not trigger onError or a refetch. Callers that must detect a stalled book need their own idle watchdog plus a REST refetch.\n */\n createSubscription(input: CreateOrderbookSubscriptionInput): OrderbookSubscription {\n const { symbolId, depth } = parse(GetOrderbookInputSchema, {\n symbolId: input.symbolId,\n depth: input.depth,\n });\n if (depth > 500) {\n throw new ValidationError(\n `depth must be at most 500 for a managed order book, got ${depth}`,\n );\n }\n const channelDepth = orderbookWsChannelDepth(depth);\n const channel = `public:spot:orderbook:deltas:depth:${channelDepth}:${symbolId}:proto`;\n\n const client = this.#client;\n const scales = this.#scales;\n let bidsMap: BookSide = new Map();\n let asksMap: BookSide = new Map();\n let currentBookSeq = 0n;\n let currentBookEpoch = 0n;\n // Set when a delta does not chain onto the book; only the next reset recovers it.\n let awaitingReset = false;\n let bucketTicks: bigint | null = null;\n let stream: SnapshotThenStreamSubscription | undefined;\n\n function levelsToMap(levels: Proto.PriceLevel[] | undefined): BookSide {\n const map: BookSide = new Map();\n for (const l of levels ?? []) {\n if (l.qtyScaled === 0n) continue;\n map.set(l.priceTicks, l.qtyScaled);\n }\n return map;\n }\n\n function applySideDelta(map: BookSide, levels: Proto.PriceLevel[] | undefined): void {\n for (const l of levels ?? []) {\n if (l.qtyScaled === 0n) map.delete(l.priceTicks);\n else map.set(l.priceTicks, l.qtyScaled);\n }\n }\n\n function sideToUI(map: BookSide, side: \"bids\" | \"asks\", limit: number): OrderbookLevel[] {\n const entries = Array.from(map.entries());\n entries.sort(([pa], [pb]) => {\n if (pa === pb) return 0;\n return side === \"bids\" ? (pa > pb ? -1 : 1) : pa < pb ? -1 : 1;\n });\n return entries\n .slice(0, limit)\n .map(([priceTicks, qtyScaled]) =>\n formatOrderbookLevel({ priceTicks, qtyScaled }, scales, symbolId),\n );\n }\n\n function sideToUIBucketed(\n map: BookSide,\n side: \"bids\" | \"asks\",\n limit: number,\n bucket: bigint | null,\n ): OrderbookLevel[] {\n if (!bucket || bucket <= 0n) return sideToUI(map, side, limit);\n\n const agg: BookSide = new Map();\n for (const [priceTicks, qtyScaled] of map.entries()) {\n if (qtyScaled <= 0n) continue;\n const bucketFloor = (priceTicks / bucket) * bucket;\n const bucketPrice =\n side === \"asks\" && bucketFloor !== priceTicks\n ? bucketFloor + bucket\n : bucketFloor;\n agg.set(bucketPrice, (agg.get(bucketPrice) ?? 0n) + qtyScaled);\n }\n return sideToUI(agg, side, limit);\n }\n\n function emit(): void {\n try {\n input.onEvent({\n symbolId,\n depth,\n bookSeq: currentBookSeq.toString(),\n bookEpoch: currentBookEpoch.toString(),\n available: true,\n bids: sideToUIBucketed(bidsMap, \"bids\", depth, bucketTicks),\n asks: sideToUIBucketed(asksMap, \"asks\", depth, bucketTicks),\n });\n } catch (error) {\n input.onError?.(publicationHandlerErrorContext(channel, error));\n }\n }\n\n function setBucket(bucket: string | null | undefined): void {\n if (!bucket) {\n bucketTicks = null;\n } else {\n try {\n bucketTicks = decimalInputToScaled(\"bucket\", bucket, scales.price());\n } catch {\n bucketTicks = null;\n }\n }\n if (stream?.isReady()) emit();\n }\n\n async function inputServiceFetch(): Promise<Proto.GetOrderBookResponse> {\n await scales.ready();\n let res: Proto.GetOrderBookResponse;\n try {\n res = await client.getOrderBook({\n symbolId,\n depth: DepthTierCodec.inputToProto[channelDepth],\n });\n } catch (error: unknown) {\n if (!isResourceNotFoundError(error)) throw error;\n\n return create(Proto.GetOrderBookResponseSchema, {\n symbolId,\n bookSeq: 0n,\n available: true,\n bids: [],\n asks: [],\n });\n }\n // An unavailable book's levels are unknown, not empty: fail the snapshot so it is retried.\n if (!isBookAvailable(res)) {\n throw new ServiceUnavailableError(\n `Order book for symbol ${symbolId} is not available yet`,\n );\n }\n if (res.bookEpoch < currentBookEpoch) {\n throw new ServiceUnavailableError(\n `Order book snapshot for symbol ${symbolId} is from an older epoch`,\n );\n }\n return res;\n }\n\n /**\n * Applies a delta only when it chains onto the current book (`bookSeqStart` equals the\n * last applied `bookSeqEnd`) or is a reset. A delta that does not chain leaves the book\n * waiting for the next reset, which the server sends periodically and after a gap.\n */\n function handleDelta(delta: Proto.OrderBookDelta): void {\n if (delta.bookSeqEnd <= currentBookSeq) return;\n\n if (delta.reset) {\n bidsMap.clear();\n asksMap.clear();\n awaitingReset = false;\n } else if (awaitingReset || delta.bookSeqStart !== currentBookSeq) {\n awaitingReset = true;\n return;\n }\n\n applySideDelta(bidsMap, delta.bids);\n applySideDelta(asksMap, delta.asks);\n\n currentBookSeq = delta.bookSeqEnd;\n emit();\n }\n\n setBucket(input.bucket);\n stream = snapshotThenStream({\n realtime: this.#realtime,\n channel,\n schema: Proto.OrderBookDeltaSchema,\n maxBufferedPublications: 200,\n snapshotErrorLog: \"Failed to fetch orderbook\",\n // GetOrderBook answers unavailable while the book is (re)built; keep asking until it is ready.\n snapshotRetry: {\n maxAttempts: Number.POSITIVE_INFINITY,\n delayMs: 1_000,\n maxDelayMs: 8_000,\n },\n // A snapshot error that is not retried (a 500) leaves the book to the server's next\n // reset; seq 0 accepts that reset even from a new epoch. Retried errors keep buffering.\n snapshotFailureMode: (error) => {\n if (!(error instanceof PolyesterError) || error.retryable) return \"wait\";\n currentBookSeq = 0n;\n awaitingReset = true;\n return \"live\";\n },\n fetchSnapshot: inputServiceFetch,\n readPublication: (delta) => [delta],\n applySnapshot: (snapshot, bufferedDeltas) => {\n bidsMap = levelsToMap(snapshot.bids);\n asksMap = levelsToMap(snapshot.asks);\n currentBookSeq = snapshot.bookSeq;\n currentBookEpoch = snapshot.bookEpoch;\n awaitingReset = false;\n emit();\n for (const delta of bufferedDeltas) {\n if (stream?.isDisposed()) return;\n handleDelta(delta);\n }\n },\n applyLivePublications: (deltas) => {\n for (const delta of deltas) {\n if (stream?.isDisposed()) return;\n handleDelta(delta);\n }\n },\n onOpen: input.onOpen,\n onClose: input.onClose,\n onError: input.onError,\n });\n\n function dispose(): void {\n stream?.unsubscribe();\n }\n\n return { unsubscribe: dispose, setBucket };\n }\n}\n\n/**\n * Whether a snapshot's levels are the book. A snapshot carrying levels is current even with\n * `available` false, which is how servers that predate the field encode every snapshot.\n */\nfunction isBookAvailable(res: Proto.GetOrderBookResponse): boolean {\n return res.available || res.bids.length > 0 || res.asks.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqDA,IAAa,mBAAb,MAA8B;CAC1B;CACA;CACA;CAEA,YAAY,YAAiC,UAA6B,QA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