@k256/sdk 0.2.1 → 0.3.0

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/src/index.ts CHANGED
@@ -24,9 +24,40 @@
24
24
  * ```
25
25
  */
26
26
 
27
- // WebSocket module
27
+ // WebSocket module (K2 data — pools, fees, quotes)
28
28
  export * from './ws';
29
29
 
30
+ // Leader Schedule WebSocket module (leader schedule, gossip, routing)
31
+ // Explicit re-exports to avoid name collisions with ./ws (e.g. ConnectionState)
32
+ export {
33
+ LeaderWebSocketClient,
34
+ LeaderWebSocketError,
35
+ decodeLeaderMessage,
36
+ LeaderMessageTag,
37
+ LeaderChannel,
38
+ ALL_LEADER_CHANNELS,
39
+ } from './leader-ws';
40
+ export type {
41
+ LeaderWebSocketClientConfig,
42
+ LeaderErrorCode,
43
+ ConnectionState as LeaderConnectionState,
44
+ LeaderChannelValue,
45
+ MessageKind,
46
+ MessageSchemaEntry,
47
+ LeaderDecodedMessage,
48
+ LeaderSubscribedMessage,
49
+ LeaderScheduleMessage,
50
+ GossipSnapshotMessage,
51
+ GossipDiffMessage,
52
+ GossipPeer,
53
+ SlotUpdateMessage,
54
+ RoutingHealthMessage,
55
+ SkipEventMessage,
56
+ IpChangeMessage,
57
+ LeaderHeartbeatMessage,
58
+ LeaderErrorMessage,
59
+ } from './leader-ws';
60
+
30
61
  // Types module
31
62
  export * from './types';
32
63
 
@@ -0,0 +1,377 @@
1
+ /**
2
+ * Leader Schedule WebSocket Client
3
+ *
4
+ * Connects to the K256 leader-schedule service via the Gateway.
5
+ * Binary mode by default (wincode protocol, matching K2 pattern).
6
+ * JSON mode opt-in via mode: 'json' (gateway decodes wincode to JSON).
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { LeaderWebSocketClient } from '@k256/sdk/leader-ws';
11
+ *
12
+ * const client = new LeaderWebSocketClient({
13
+ * apiKey: 'your-api-key',
14
+ * onSlotUpdate: (msg) => console.log('Slot:', msg.data.slot, 'Leader:', msg.data.leader),
15
+ * onRoutingHealth: (msg) => console.log('Coverage:', msg.data.coverage),
16
+ * onGossipDiff: (msg) => console.log('Peers changed:', msg.data.added.length, 'added'),
17
+ * });
18
+ *
19
+ * await client.connect();
20
+ * ```
21
+ */
22
+
23
+ import { decodeLeaderMessage } from './decoder';
24
+ import {
25
+ ALL_LEADER_CHANNELS,
26
+ type LeaderChannelValue,
27
+ type LeaderDecodedMessage,
28
+ type LeaderSubscribedMessage,
29
+ type LeaderScheduleMessage,
30
+ type GossipSnapshotMessage,
31
+ type GossipDiffMessage,
32
+ type SlotUpdateMessage,
33
+ type RoutingHealthMessage,
34
+ type SkipEventMessage,
35
+ type IpChangeMessage,
36
+ type LeaderHeartbeatMessage,
37
+ type LeaderErrorMessage,
38
+ } from './types';
39
+
40
+ /**
41
+ * Connection state
42
+ */
43
+ export type ConnectionState =
44
+ | 'disconnected'
45
+ | 'connecting'
46
+ | 'connected'
47
+ | 'reconnecting'
48
+ | 'closed';
49
+
50
+ /**
51
+ * Leader WebSocket client configuration
52
+ */
53
+ export interface LeaderWebSocketClientConfig {
54
+ /** API key for authentication */
55
+ apiKey: string;
56
+ /** Gateway URL (default: wss://gateway.k256.xyz/v1/leader-ws) */
57
+ url?: string;
58
+ /** Message format: 'binary' (default, efficient) or 'json' (debugging via gateway) */
59
+ mode?: 'binary' | 'json';
60
+ /** Channels to subscribe to (default: all channels) */
61
+ channels?: LeaderChannelValue[];
62
+
63
+ // Reconnection settings
64
+ /** Enable automatic reconnection (default: true) */
65
+ autoReconnect?: boolean;
66
+ /** Initial reconnect delay in ms (default: 1000) */
67
+ reconnectDelayMs?: number;
68
+ /** Max reconnect delay in ms (default: 30000) */
69
+ maxReconnectDelayMs?: number;
70
+ /** Max reconnect attempts (default: Infinity) */
71
+ maxReconnectAttempts?: number;
72
+
73
+ // Event callbacks
74
+ /** Called when connection state changes */
75
+ onStateChange?: (state: ConnectionState, prevState: ConnectionState) => void;
76
+ /** Called on successful connection */
77
+ onConnect?: () => void;
78
+ /** Called on disconnection */
79
+ onDisconnect?: (code: number, reason: string, wasClean: boolean) => void;
80
+ /** Called on reconnection attempt */
81
+ onReconnecting?: (attempt: number, delayMs: number) => void;
82
+ /** Called on any error */
83
+ onError?: (error: LeaderWebSocketError) => void;
84
+
85
+ // Message callbacks
86
+ /** Called on subscription confirmed (includes protocol schema) */
87
+ onSubscribed?: (msg: LeaderSubscribedMessage) => void;
88
+ /** Called on full leader schedule (snapshot — replaces previous) */
89
+ onLeaderSchedule?: (msg: LeaderScheduleMessage) => void;
90
+ /** Called on full gossip peer snapshot (snapshot — key: identity) */
91
+ onGossipSnapshot?: (msg: GossipSnapshotMessage) => void;
92
+ /** Called on gossip diff (diff — merge into snapshot using identity) */
93
+ onGossipDiff?: (msg: GossipDiffMessage) => void;
94
+ /** Called on slot update (snapshot — each replaces previous) */
95
+ onSlotUpdate?: (msg: SlotUpdateMessage) => void;
96
+ /** Called on routing health (snapshot — each replaces previous) */
97
+ onRoutingHealth?: (msg: RoutingHealthMessage) => void;
98
+ /** Called on skip event (event — block production stats) */
99
+ onSkipEvent?: (msg: SkipEventMessage) => void;
100
+ /** Called on IP change event */
101
+ onIpChange?: (msg: IpChangeMessage) => void;
102
+ /** Called on heartbeat (every 10s) */
103
+ onHeartbeat?: (msg: LeaderHeartbeatMessage) => void;
104
+ /** Called on any message (raw) */
105
+ onMessage?: (msg: LeaderDecodedMessage) => void;
106
+ }
107
+
108
+ /**
109
+ * Error codes for leader WebSocket
110
+ */
111
+ export type LeaderErrorCode =
112
+ | 'CONNECTION_FAILED'
113
+ | 'CONNECTION_LOST'
114
+ | 'AUTH_FAILED'
115
+ | 'SERVER_ERROR'
116
+ | 'INVALID_MESSAGE'
117
+ | 'RECONNECT_FAILED';
118
+
119
+ /**
120
+ * WebSocket error with context
121
+ */
122
+ export class LeaderWebSocketError extends Error {
123
+ constructor(
124
+ public readonly code: LeaderErrorCode,
125
+ message: string,
126
+ public readonly closeCode?: number,
127
+ public readonly closeReason?: string,
128
+ ) {
129
+ super(message);
130
+ this.name = 'LeaderWebSocketError';
131
+ }
132
+
133
+ get isRecoverable(): boolean {
134
+ return this.code !== 'AUTH_FAILED';
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Leader Schedule WebSocket Client
140
+ *
141
+ * Connects to the leader-schedule service via the Gateway.
142
+ * Binary mode by default (wincode protocol). JSON mode opt-in via gateway.
143
+ * Automatically subscribes to configured channels on connect/reconnect.
144
+ */
145
+ export class LeaderWebSocketClient {
146
+ private ws: WebSocket | null = null;
147
+ private readonly config: Required<Pick<LeaderWebSocketClientConfig,
148
+ 'apiKey' | 'url' | 'mode' | 'channels' | 'autoReconnect' | 'reconnectDelayMs' | 'maxReconnectDelayMs' | 'maxReconnectAttempts'
149
+ >> & LeaderWebSocketClientConfig;
150
+
151
+ private _state: ConnectionState = 'disconnected';
152
+ private reconnectAttempts = 0;
153
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
154
+ private isIntentionallyClosed = false;
155
+
156
+ /** Current connection state */
157
+ get state(): ConnectionState { return this._state; }
158
+
159
+ /** Whether currently connected */
160
+ get isConnected(): boolean {
161
+ return this._state === 'connected' && this.ws?.readyState === WebSocket.OPEN;
162
+ }
163
+
164
+ constructor(config: LeaderWebSocketClientConfig) {
165
+ this.config = {
166
+ url: 'wss://gateway.k256.xyz/v1/leader-ws',
167
+ mode: 'binary',
168
+ channels: ALL_LEADER_CHANNELS,
169
+ autoReconnect: true,
170
+ reconnectDelayMs: 1000,
171
+ maxReconnectDelayMs: 30000,
172
+ maxReconnectAttempts: Infinity,
173
+ ...config,
174
+ };
175
+ }
176
+
177
+ /**
178
+ * Connect to the leader-schedule WebSocket
179
+ */
180
+ async connect(): Promise<void> {
181
+ if (this._state === 'connected' || this._state === 'connecting') return;
182
+
183
+ this.isIntentionallyClosed = false;
184
+ this.setState('connecting');
185
+
186
+ return new Promise((resolve, reject) => {
187
+ try {
188
+ const url = `${this.config.url}?apiKey=${encodeURIComponent(this.config.apiKey)}`;
189
+ this.ws = new WebSocket(url);
190
+
191
+ // Binary mode needs arraybuffer
192
+ if (this.config.mode === 'binary') {
193
+ this.ws.binaryType = 'arraybuffer';
194
+ }
195
+
196
+ this.ws.onopen = () => {
197
+ this.setState('connected');
198
+ this.reconnectAttempts = 0;
199
+
200
+ if (this.config.mode === 'binary') {
201
+ // Binary mode: send 0x01 tag + JSON payload
202
+ const payload = JSON.stringify({ channels: this.config.channels });
203
+ const bytes = new TextEncoder().encode(payload);
204
+ const msg = new Uint8Array(1 + bytes.length);
205
+ msg[0] = 0x01; // MSG_SUBSCRIBE
206
+ msg.set(bytes, 1);
207
+ this.ws!.send(msg.buffer);
208
+ } else {
209
+ // JSON mode: send text (gateway decodes wincode to JSON)
210
+ this.ws!.send(JSON.stringify({
211
+ type: 'subscribe',
212
+ channels: this.config.channels,
213
+ format: 'json',
214
+ }));
215
+ }
216
+
217
+ this.config.onConnect?.();
218
+ resolve();
219
+ };
220
+
221
+ this.ws.onmessage = (event) => {
222
+ if (this.config.mode === 'binary' && event.data instanceof ArrayBuffer) {
223
+ // Binary mode: decode wincode with SDK decoder
224
+ const decoded = decodeLeaderMessage(event.data);
225
+ if (decoded) {
226
+ this.dispatchMessage(decoded);
227
+ }
228
+ } else if (typeof event.data === 'string') {
229
+ // JSON mode: parse text frames from gateway
230
+ this.handleJsonMessage(event.data);
231
+ }
232
+ };
233
+
234
+ this.ws.onclose = (event) => {
235
+ const wasConnected = this._state === 'connected';
236
+ this.ws = null;
237
+
238
+ if (this.isIntentionallyClosed) {
239
+ this.setState('closed');
240
+ this.config.onDisconnect?.(event.code, event.reason, event.wasClean);
241
+ return;
242
+ }
243
+
244
+ this.config.onDisconnect?.(event.code, event.reason, event.wasClean);
245
+
246
+ // Check for auth failure (don't reconnect)
247
+ if (event.code === 1008 || event.code === 4001 || event.code === 4003) {
248
+ this.setState('closed');
249
+ this.config.onError?.(new LeaderWebSocketError(
250
+ 'AUTH_FAILED', `Authentication failed: ${event.reason}`, event.code, event.reason
251
+ ));
252
+ if (!wasConnected) reject(new LeaderWebSocketError('AUTH_FAILED', event.reason, event.code));
253
+ return;
254
+ }
255
+
256
+ // Auto-reconnect
257
+ if (this.config.autoReconnect && this.reconnectAttempts < this.config.maxReconnectAttempts) {
258
+ this.scheduleReconnect();
259
+ } else {
260
+ this.setState('disconnected');
261
+ }
262
+
263
+ if (!wasConnected) reject(new LeaderWebSocketError('CONNECTION_FAILED', 'WebSocket closed before connect'));
264
+ };
265
+
266
+ this.ws.onerror = () => {
267
+ this.config.onError?.(new LeaderWebSocketError('CONNECTION_FAILED', 'WebSocket connection error'));
268
+ };
269
+ } catch (err) {
270
+ this.setState('disconnected');
271
+ reject(err);
272
+ }
273
+ });
274
+ }
275
+
276
+ /**
277
+ * Disconnect from the WebSocket
278
+ */
279
+ disconnect(): void {
280
+ this.isIntentionallyClosed = true;
281
+ this.clearTimers();
282
+
283
+ if (this.ws) {
284
+ if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
285
+ this.ws.close(1000, 'Client disconnect');
286
+ }
287
+ this.ws = null;
288
+ }
289
+
290
+ this.setState('closed');
291
+ }
292
+
293
+ // ── Private ──
294
+
295
+ /** Handle JSON text frame (from gateway JSON mode) */
296
+ private handleJsonMessage(raw: string): void {
297
+ try {
298
+ const msg = JSON.parse(raw) as LeaderDecodedMessage;
299
+ this.dispatchMessage(msg);
300
+ } catch {
301
+ this.config.onError?.(new LeaderWebSocketError('INVALID_MESSAGE', 'Failed to parse message'));
302
+ }
303
+ }
304
+
305
+ /** Dispatch a decoded message to typed callbacks */
306
+ private dispatchMessage(msg: LeaderDecodedMessage): void {
307
+ switch (msg.type) {
308
+ case 'subscribed':
309
+ this.config.onSubscribed?.(msg as LeaderSubscribedMessage);
310
+ break;
311
+ case 'leader_schedule':
312
+ this.config.onLeaderSchedule?.(msg as LeaderScheduleMessage);
313
+ break;
314
+ case 'gossip_snapshot':
315
+ this.config.onGossipSnapshot?.(msg as GossipSnapshotMessage);
316
+ break;
317
+ case 'gossip_diff':
318
+ this.config.onGossipDiff?.(msg as GossipDiffMessage);
319
+ break;
320
+ case 'slot_update':
321
+ this.config.onSlotUpdate?.(msg as SlotUpdateMessage);
322
+ break;
323
+ case 'routing_health':
324
+ this.config.onRoutingHealth?.(msg as RoutingHealthMessage);
325
+ break;
326
+ case 'skip_event':
327
+ this.config.onSkipEvent?.(msg as SkipEventMessage);
328
+ break;
329
+ case 'ip_change':
330
+ this.config.onIpChange?.(msg as IpChangeMessage);
331
+ break;
332
+ case 'heartbeat':
333
+ this.config.onHeartbeat?.(msg as LeaderHeartbeatMessage);
334
+ break;
335
+ case 'error':
336
+ this.config.onError?.(new LeaderWebSocketError(
337
+ 'SERVER_ERROR', (msg as LeaderErrorMessage).data.message
338
+ ));
339
+ break;
340
+ }
341
+
342
+ // Generic handler
343
+ this.config.onMessage?.(msg);
344
+ }
345
+
346
+ private setState(state: ConnectionState): void {
347
+ const prev = this._state;
348
+ if (prev === state) return;
349
+ this._state = state;
350
+ this.config.onStateChange?.(state, prev);
351
+ }
352
+
353
+ private scheduleReconnect(): void {
354
+ this.setState('reconnecting');
355
+ this.reconnectAttempts++;
356
+
357
+ const delay = Math.min(
358
+ this.config.reconnectDelayMs * Math.pow(2, this.reconnectAttempts - 1),
359
+ this.config.maxReconnectDelayMs
360
+ );
361
+
362
+ this.config.onReconnecting?.(this.reconnectAttempts, delay);
363
+
364
+ this.reconnectTimer = setTimeout(() => {
365
+ this.connect().catch(() => {
366
+ // Error handled in onclose/onerror
367
+ });
368
+ }, delay);
369
+ }
370
+
371
+ private clearTimers(): void {
372
+ if (this.reconnectTimer) {
373
+ clearTimeout(this.reconnectTimer);
374
+ this.reconnectTimer = null;
375
+ }
376
+ }
377
+ }