@pokertools/sdk 1.0.4

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.
@@ -0,0 +1,683 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+ import * as _pokertools_types from '@pokertools/types';
4
+ import { LoginRequest, LoginResponse, TableListItem, CreateTableRequest, PublicState, BuyInRequest, GameActionRequest, AddChipsRequest } from '@pokertools/types';
5
+
6
+ /**
7
+ * SDK-specific types and configuration
8
+ */
9
+ /**
10
+ * SDK configuration options
11
+ */
12
+ interface PokerSDKConfig {
13
+ /** Base URL of the PokerTools API (e.g., "https://api.poker.example.com") */
14
+ baseUrl: string;
15
+ /** WebSocket URL (defaults to baseUrl with ws:// protocol) */
16
+ wsUrl?: string;
17
+ /** JWT token for authentication */
18
+ token?: string;
19
+ /** Request timeout in milliseconds (default: 30000) */
20
+ timeout?: number;
21
+ /** Retry configuration */
22
+ retry?: {
23
+ /** Number of retries for failed requests (default: 3) */
24
+ count?: number;
25
+ /** Delay between retries in ms (default: 1000) */
26
+ delay?: number;
27
+ /** Exponential backoff multiplier (default: 2) */
28
+ backoff?: number;
29
+ };
30
+ /** Custom fetch implementation (for React Native or custom environments) */
31
+ fetch?: typeof fetch;
32
+ /** Custom WebSocket implementation (for React Native or Node.js) */
33
+ WebSocket?: typeof WebSocket;
34
+ /** Enable debug logging */
35
+ debug?: boolean;
36
+ }
37
+ /**
38
+ * User balance information
39
+ */
40
+ interface UserBalances {
41
+ main: number;
42
+ inPlay: number;
43
+ }
44
+ /**
45
+ * User profile with balances
46
+ */
47
+ interface UserProfile {
48
+ id: string;
49
+ username: string;
50
+ address: string;
51
+ role: "PLAYER" | "ADMIN" | "BOT";
52
+ createdAt: string;
53
+ balances: UserBalances;
54
+ }
55
+ /**
56
+ * Blockchain configuration
57
+ */
58
+ interface BlockchainInfo {
59
+ id: string;
60
+ name: string;
61
+ chainId: number;
62
+ tokens: TokenInfo[];
63
+ }
64
+ /**
65
+ * Token configuration
66
+ */
67
+ interface TokenInfo {
68
+ id: string;
69
+ symbol: string;
70
+ name: string;
71
+ decimals: number;
72
+ minDeposit: string;
73
+ }
74
+ /**
75
+ * Deposit session info
76
+ */
77
+ interface DepositSession {
78
+ address: string;
79
+ expiresAt: string;
80
+ message: string;
81
+ }
82
+ /**
83
+ * Deposit record
84
+ */
85
+ interface DepositRecord {
86
+ id: string;
87
+ txHash: string | null;
88
+ chain: string;
89
+ token: string;
90
+ amountRaw: string;
91
+ amountCredit: number;
92
+ status: "PENDING" | "PROCESSING" | "CONFIRMED" | "FAILED";
93
+ createdAt: string;
94
+ confirmedAt: string | null;
95
+ explorerUrl: string;
96
+ }
97
+ /**
98
+ * Withdrawal request
99
+ */
100
+ interface WithdrawalRequest {
101
+ amount: number;
102
+ blockchainId: string;
103
+ tokenId: string;
104
+ address: string;
105
+ message: string;
106
+ signature: `0x${string}`;
107
+ }
108
+ /**
109
+ * Withdrawal record
110
+ */
111
+ interface WithdrawalRecord {
112
+ id: string;
113
+ txHash: string | null;
114
+ chain: string;
115
+ token: string;
116
+ address: string;
117
+ amountRaw: string;
118
+ amountUSD: number;
119
+ status: "PENDING" | "PROCESSING" | "CONFIRMED" | "FAILED" | "REJECTED" | "CANCELLED";
120
+ createdAt: string;
121
+ confirmedAt: string | null;
122
+ explorerUrl: string | null;
123
+ }
124
+ /**
125
+ * Hand history entry (simplified)
126
+ */
127
+ interface HandHistoryEntry {
128
+ id: string;
129
+ amount: number;
130
+ type: "HAND_WIN" | "HAND_LOSS";
131
+ referenceId: string | null;
132
+ createdAt: string;
133
+ }
134
+ /**
135
+ * Player note
136
+ */
137
+ interface PlayerNote {
138
+ id: string;
139
+ targetId: string;
140
+ content: string;
141
+ label: string | null;
142
+ createdAt: string;
143
+ updatedAt: string;
144
+ target?: {
145
+ id: string;
146
+ username: string;
147
+ };
148
+ }
149
+ /**
150
+ * WebSocket connection state
151
+ */
152
+ type ConnectionState = "disconnected" | "connecting" | "connected" | "reconnecting";
153
+ /**
154
+ * Event emitter types
155
+ */
156
+ interface PokerSocketEvents {
157
+ connect: () => void;
158
+ disconnect: (reason?: string) => void;
159
+ reconnect: (attempt: number) => void;
160
+ error: (error: Error) => void;
161
+ stateUpdate: (tableId: string, state: _pokertools_types.PublicState) => void;
162
+ snapshot: (tableId: string, state: _pokertools_types.PublicState) => void;
163
+ action: (tableId: string, playerId: string, actionType: string, amount?: number) => void;
164
+ }
165
+
166
+ /**
167
+ * PokerClient - HTTP client for PokerTools REST API
168
+ *
169
+ * Provides type-safe methods for all API endpoints with automatic
170
+ * retry, authentication, and error handling.
171
+ */
172
+
173
+ /**
174
+ * PokerClient - Main HTTP client for PokerTools API
175
+ *
176
+ * @example
177
+ * ```typescript
178
+ * const client = new PokerClient({
179
+ * baseUrl: "https://api.poker.example.com",
180
+ * token: "jwt-token",
181
+ * });
182
+ *
183
+ * // Get tables
184
+ * const tables = await client.getTables();
185
+ *
186
+ * // Create a table
187
+ * const tableId = await client.createTable({
188
+ * name: "My Table",
189
+ * mode: "CASH",
190
+ * smallBlind: 5,
191
+ * bigBlind: 10,
192
+ * maxPlayers: 6,
193
+ * });
194
+ *
195
+ * // Buy in
196
+ * await client.buyIn(tableId, {
197
+ * amount: 500,
198
+ * seat: 3,
199
+ * idempotencyKey: crypto.randomUUID(),
200
+ * });
201
+ * ```
202
+ */
203
+ declare class PokerClient {
204
+ private readonly baseUrl;
205
+ private readonly timeout;
206
+ private readonly retry;
207
+ private readonly fetchFn;
208
+ private readonly debug;
209
+ private token;
210
+ constructor(config: PokerSDKConfig);
211
+ /**
212
+ * Set the authentication token
213
+ */
214
+ setToken(token: string | null): void;
215
+ /**
216
+ * Get current token
217
+ */
218
+ getToken(): string | null;
219
+ /**
220
+ * Check if client is authenticated
221
+ */
222
+ isAuthenticated(): boolean;
223
+ /**
224
+ * Get a nonce for SIWE authentication
225
+ */
226
+ getNonce(): Promise<string>;
227
+ /**
228
+ * Login with SIWE signature
229
+ */
230
+ login(request: LoginRequest): Promise<LoginResponse>;
231
+ /**
232
+ * Logout and revoke session
233
+ */
234
+ logout(): Promise<void>;
235
+ /**
236
+ * Get list of active tables
237
+ */
238
+ getTables(): Promise<TableListItem[]>;
239
+ /**
240
+ * Create a new table
241
+ */
242
+ createTable(config: CreateTableRequest): Promise<string>;
243
+ /**
244
+ * Get table state
245
+ * @param tableId - Table ID
246
+ * @param since - Optional version for conditional fetch (returns null if unchanged)
247
+ */
248
+ getTableState(tableId: string, since?: number): Promise<PublicState | null>;
249
+ /**
250
+ * Buy in to a table
251
+ */
252
+ buyIn(tableId: string, request: BuyInRequest): Promise<void>;
253
+ /**
254
+ * Execute a game action
255
+ */
256
+ action(tableId: string, request: GameActionRequest): Promise<PublicState>;
257
+ /**
258
+ * Add chips to stack (rebuy/top-up)
259
+ */
260
+ addChips(tableId: string, request: AddChipsRequest): Promise<void>;
261
+ /**
262
+ * Stand from table (leave and cash out)
263
+ */
264
+ stand(tableId: string): Promise<void>;
265
+ /**
266
+ * Fold hand
267
+ */
268
+ fold(tableId: string): Promise<PublicState>;
269
+ /**
270
+ * Check (pass action)
271
+ */
272
+ check(tableId: string): Promise<PublicState>;
273
+ /**
274
+ * Call current bet
275
+ */
276
+ call(tableId: string): Promise<PublicState>;
277
+ /**
278
+ * Place a bet
279
+ */
280
+ bet(tableId: string, amount: number): Promise<PublicState>;
281
+ /**
282
+ * Raise the current bet
283
+ */
284
+ raise(tableId: string, amount: number): Promise<PublicState>;
285
+ /**
286
+ * Deal new hand
287
+ */
288
+ deal(tableId: string): Promise<PublicState>;
289
+ /**
290
+ * Show cards at showdown
291
+ */
292
+ show(tableId: string, cardIndices?: number[]): Promise<PublicState>;
293
+ /**
294
+ * Muck cards at showdown
295
+ */
296
+ muck(tableId: string): Promise<PublicState>;
297
+ /**
298
+ * Use time bank
299
+ */
300
+ timeBank(tableId: string): Promise<PublicState>;
301
+ /**
302
+ * Get current user profile and balances
303
+ */
304
+ getProfile(): Promise<UserProfile>;
305
+ /**
306
+ * Get hand history
307
+ */
308
+ getHandHistory(): Promise<HandHistoryEntry[]>;
309
+ /**
310
+ * Request a withdrawal
311
+ */
312
+ withdraw(request: WithdrawalRequest): Promise<{
313
+ id: string;
314
+ status: string;
315
+ amount: number;
316
+ destination: string;
317
+ blockchain: string;
318
+ token: string;
319
+ }>;
320
+ /**
321
+ * Get withdrawal history
322
+ */
323
+ getWithdrawals(): Promise<WithdrawalRecord[]>;
324
+ /**
325
+ * Get supported blockchains and tokens
326
+ */
327
+ getChains(): Promise<BlockchainInfo[]>;
328
+ /**
329
+ * Start deposit monitoring session
330
+ */
331
+ startDeposit(): Promise<DepositSession>;
332
+ /**
333
+ * Get deposit address
334
+ */
335
+ getDepositAddress(): Promise<string>;
336
+ /**
337
+ * Get deposit history
338
+ */
339
+ getDeposits(): Promise<DepositRecord[]>;
340
+ /**
341
+ * Get all notes by current user
342
+ */
343
+ getNotes(): Promise<PlayerNote[]>;
344
+ /**
345
+ * Get note for specific player
346
+ */
347
+ getNote(targetId: string): Promise<PlayerNote | null>;
348
+ /**
349
+ * Save or update note
350
+ */
351
+ saveNote(targetId: string, content: string, label?: string): Promise<PlayerNote>;
352
+ /**
353
+ * Delete note
354
+ */
355
+ deleteNote(targetId: string): Promise<void>;
356
+ /**
357
+ * Health check
358
+ */
359
+ health(): Promise<{
360
+ status: string;
361
+ timestamp: number;
362
+ }>;
363
+ /**
364
+ * Make HTTP request with retry logic
365
+ */
366
+ private request;
367
+ /**
368
+ * Sleep helper
369
+ */
370
+ private sleep;
371
+ }
372
+
373
+ /**
374
+ * PokerSocket - WebSocket client for real-time game updates
375
+ *
376
+ * Provides automatic reconnection, heartbeat, and typed event handling
377
+ * for real-time poker game state synchronization.
378
+ */
379
+
380
+ /**
381
+ * WebSocket configuration
382
+ */
383
+ interface SocketConfig {
384
+ /** WebSocket URL */
385
+ url: string;
386
+ /** JWT token for authentication */
387
+ token: string;
388
+ /** Heartbeat interval in ms (default: 25000) */
389
+ heartbeatInterval?: number;
390
+ /** Reconnection attempts (default: 10) */
391
+ reconnectAttempts?: number;
392
+ /** Base reconnection delay in ms (default: 1000) */
393
+ reconnectDelay?: number;
394
+ /** Max reconnection delay in ms (default: 30000) */
395
+ maxReconnectDelay?: number;
396
+ /** Custom WebSocket implementation */
397
+ WebSocket?: typeof WebSocket;
398
+ /** Enable debug logging */
399
+ debug?: boolean;
400
+ }
401
+ /**
402
+ * PokerSocket - Real-time WebSocket client
403
+ *
404
+ * @example
405
+ * ```typescript
406
+ * const socket = new PokerSocket({
407
+ * url: "wss://api.poker.example.com/ws/play",
408
+ * token: "jwt-token",
409
+ * });
410
+ *
411
+ * // Listen for events
412
+ * socket.on("connect", () => console.log("Connected!"));
413
+ * socket.on("stateUpdate", (tableId, state) => {
414
+ * console.log("State updated:", state);
415
+ * });
416
+ *
417
+ * // Connect
418
+ * await socket.connect();
419
+ *
420
+ * // Join a table
421
+ * await socket.join("table-123");
422
+ *
423
+ * // Later: disconnect
424
+ * socket.disconnect();
425
+ * ```
426
+ */
427
+ declare class PokerSocket {
428
+ private readonly url;
429
+ private readonly token;
430
+ private readonly heartbeatInterval;
431
+ private readonly reconnectAttempts;
432
+ private readonly reconnectDelay;
433
+ private readonly maxReconnectDelay;
434
+ private readonly WebSocketImpl;
435
+ private readonly debug;
436
+ private ws;
437
+ private connectionState;
438
+ private reconnectCount;
439
+ private heartbeatTimer;
440
+ private pendingRequests;
441
+ private joinedTables;
442
+ private listeners;
443
+ private shouldReconnect;
444
+ private stateCache;
445
+ constructor(config: SocketConfig);
446
+ /**
447
+ * Create a PokerSocket from SDK config
448
+ */
449
+ static fromConfig(config: PokerSDKConfig): PokerSocket;
450
+ /**
451
+ * Connect to the WebSocket server
452
+ */
453
+ connect(): Promise<void>;
454
+ /**
455
+ * Disconnect from the WebSocket server
456
+ */
457
+ disconnect(): void;
458
+ /**
459
+ * Get current connection state
460
+ */
461
+ getState(): ConnectionState;
462
+ /**
463
+ * Check if connected
464
+ */
465
+ isConnected(): boolean;
466
+ /**
467
+ * Join a table to receive real-time updates
468
+ */
469
+ join(tableId: string): Promise<PublicState>;
470
+ /**
471
+ * Leave a table
472
+ */
473
+ leave(tableId: string): void;
474
+ /**
475
+ * Get currently joined tables
476
+ */
477
+ getJoinedTables(): string[];
478
+ /**
479
+ * Get cached state for a table
480
+ */
481
+ getCachedState(tableId: string): PublicState | undefined;
482
+ /**
483
+ * Subscribe to an event
484
+ */
485
+ on<E extends keyof PokerSocketEvents>(event: E, listener: PokerSocketEvents[E]): () => void;
486
+ /**
487
+ * Unsubscribe from an event
488
+ */
489
+ off<E extends keyof PokerSocketEvents>(event: E, listener: PokerSocketEvents[E]): void;
490
+ /**
491
+ * Subscribe to an event (once)
492
+ */
493
+ once<E extends keyof PokerSocketEvents>(event: E, listener: PokerSocketEvents[E]): () => void;
494
+ /**
495
+ * Send application-level ping (not WebSocket ping)
496
+ */
497
+ ping(): Promise<number>;
498
+ /**
499
+ * Send a message to the server
500
+ */
501
+ private send;
502
+ /**
503
+ * Handle incoming message
504
+ */
505
+ private handleMessage;
506
+ /**
507
+ * Handle disconnect
508
+ */
509
+ private handleDisconnect;
510
+ /**
511
+ * Attempt to reconnect
512
+ */
513
+ private reconnect;
514
+ /**
515
+ * Rejoin previously joined tables
516
+ */
517
+ private rejoinTables;
518
+ /**
519
+ * Start heartbeat timer
520
+ */
521
+ private startHeartbeat;
522
+ /**
523
+ * Stop heartbeat timer
524
+ */
525
+ private stopHeartbeat;
526
+ /**
527
+ * Clear all pending requests
528
+ */
529
+ private clearPendingRequests;
530
+ /**
531
+ * Emit event to listeners
532
+ */
533
+ private emit;
534
+ /**
535
+ * Generate unique request ID
536
+ */
537
+ private generateRequestId;
538
+ /**
539
+ * Sleep helper
540
+ */
541
+ private sleep;
542
+ /**
543
+ * Debug logger
544
+ */
545
+ private log;
546
+ }
547
+
548
+ interface PokerContextValue {
549
+ client: PokerClient;
550
+ socket: PokerSocket | null;
551
+ isAuthenticated: boolean;
552
+ connectionState: ConnectionState;
553
+ connect: () => Promise<void>;
554
+ disconnect: () => void;
555
+ }
556
+ /**
557
+ * Props for PokerProvider
558
+ */
559
+ interface PokerProviderProps {
560
+ /** SDK configuration */
561
+ config: PokerSDKConfig;
562
+ /** Children to render */
563
+ children: ReactNode;
564
+ /** Auto-connect WebSocket when authenticated (default: true) */
565
+ autoConnect?: boolean;
566
+ }
567
+ /**
568
+ * PokerProvider - Context provider for PokerTools SDK
569
+ *
570
+ * @example
571
+ * ```tsx
572
+ * import { PokerProvider } from "@pokertools/sdk/react";
573
+ *
574
+ * function App() {
575
+ * return (
576
+ * <PokerProvider config={{ baseUrl: "https://api.poker.example.com", token }}>
577
+ * <Game />
578
+ * </PokerProvider>
579
+ * );
580
+ * }
581
+ * ```
582
+ */
583
+ declare function PokerProvider({ config, children, autoConnect }: PokerProviderProps): react.JSX.Element;
584
+ /**
585
+ * Hook to access PokerTools context
586
+ */
587
+ declare function usePoker(): PokerContextValue;
588
+ /**
589
+ * Hook to get the PokerClient instance
590
+ */
591
+ declare function usePokerClient(): PokerClient;
592
+ /**
593
+ * Hook to get the PokerSocket instance
594
+ */
595
+ declare function usePokerSocket(): PokerSocket | null;
596
+ interface UseTableOptions {
597
+ /** Polling interval for state updates (ms, default: disabled) */
598
+ pollInterval?: number;
599
+ /** Auto-join via WebSocket (default: true) */
600
+ autoJoin?: boolean;
601
+ }
602
+ interface UseTableResult {
603
+ /** Current table state */
604
+ state: PublicState | null;
605
+ /** Loading state */
606
+ isLoading: boolean;
607
+ /** Error if any */
608
+ error: Error | null;
609
+ /** Refresh state from server */
610
+ refresh: () => Promise<void>;
611
+ /** Execute an action */
612
+ action: (type: string, amount?: number) => Promise<void>;
613
+ /** Leave the table */
614
+ leave: () => Promise<void>;
615
+ }
616
+ /**
617
+ * Hook to manage a poker table
618
+ *
619
+ * @example
620
+ * ```tsx
621
+ * function Table({ tableId }: { tableId: string }) {
622
+ * const { state, isLoading, error, action } = useTable(tableId);
623
+ *
624
+ * if (isLoading) return <div>Loading...</div>;
625
+ * if (error) return <div>Error: {error.message}</div>;
626
+ * if (!state) return <div>Table not found</div>;
627
+ *
628
+ * return (
629
+ * <div>
630
+ * <div>Pot: {state.pot}</div>
631
+ * <button onClick={() => action("FOLD")}>Fold</button>
632
+ * <button onClick={() => action("CALL")}>Call</button>
633
+ * </div>
634
+ * );
635
+ * }
636
+ * ```
637
+ */
638
+ declare function useTable(tableId: string, options?: UseTableOptions): UseTableResult;
639
+ interface UseUserResult {
640
+ /** User profile */
641
+ profile: UserProfile | null;
642
+ /** User balances */
643
+ balances: UserBalances | null;
644
+ /** Loading state */
645
+ isLoading: boolean;
646
+ /** Error if any */
647
+ error: Error | null;
648
+ /** Refresh profile */
649
+ refresh: () => Promise<void>;
650
+ }
651
+ /**
652
+ * Hook to get current user profile and balances
653
+ */
654
+ declare function useUser(): UseUserResult;
655
+ interface UseTablesResult {
656
+ /** List of tables */
657
+ tables: Awaited<ReturnType<PokerClient["getTables"]>>;
658
+ /** Loading state */
659
+ isLoading: boolean;
660
+ /** Error if any */
661
+ error: Error | null;
662
+ /** Refresh tables list */
663
+ refresh: () => Promise<void>;
664
+ }
665
+ /**
666
+ * Hook to get list of active tables
667
+ */
668
+ declare function useTables(): UseTablesResult;
669
+ /**
670
+ * Hook to manage WebSocket connection
671
+ */
672
+ declare function useConnection(): {
673
+ state: ConnectionState;
674
+ isConnected: boolean;
675
+ isConnecting: boolean;
676
+ isReconnecting: boolean;
677
+ latency: number | null;
678
+ connect: () => Promise<void>;
679
+ disconnect: () => void;
680
+ ping: () => Promise<number | null>;
681
+ };
682
+
683
+ export { type PokerContextValue, PokerProvider, type PokerProviderProps, type UseTableOptions, type UseTableResult, type UseTablesResult, type UseUserResult, useConnection, usePoker, usePokerClient, usePokerSocket, useTable, useTables, useUser };