@catalyst-team/poly-sdk 0.2.0 → 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.
Files changed (242) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +548 -813
  3. package/README.zh-CN.md +805 -0
  4. package/dist/__tests__/clob-api.test.d.ts +5 -0
  5. package/dist/__tests__/clob-api.test.d.ts.map +1 -0
  6. package/dist/__tests__/clob-api.test.js +240 -0
  7. package/dist/__tests__/clob-api.test.js.map +1 -0
  8. package/dist/__tests__/integration/arbitrage-service.integration.test.d.ts +12 -0
  9. package/dist/__tests__/integration/arbitrage-service.integration.test.d.ts.map +1 -0
  10. package/dist/__tests__/integration/arbitrage-service.integration.test.js +267 -0
  11. package/dist/__tests__/integration/arbitrage-service.integration.test.js.map +1 -0
  12. package/dist/__tests__/integration/bridge-client.integration.test.d.ts +11 -0
  13. package/dist/__tests__/integration/bridge-client.integration.test.d.ts.map +1 -0
  14. package/dist/__tests__/integration/bridge-client.integration.test.js +260 -0
  15. package/dist/__tests__/integration/bridge-client.integration.test.js.map +1 -0
  16. package/dist/__tests__/integration/clob-api.integration.test.d.ts +13 -0
  17. package/dist/__tests__/integration/clob-api.integration.test.d.ts.map +1 -0
  18. package/dist/__tests__/integration/clob-api.integration.test.js +170 -0
  19. package/dist/__tests__/integration/clob-api.integration.test.js.map +1 -0
  20. package/dist/__tests__/integration/ctf-client.integration.test.d.ts +17 -0
  21. package/dist/__tests__/integration/ctf-client.integration.test.d.ts.map +1 -0
  22. package/dist/__tests__/integration/ctf-client.integration.test.js +234 -0
  23. package/dist/__tests__/integration/ctf-client.integration.test.js.map +1 -0
  24. package/dist/__tests__/integration/data-api.integration.test.d.ts +9 -0
  25. package/dist/__tests__/integration/data-api.integration.test.d.ts.map +1 -0
  26. package/dist/__tests__/integration/data-api.integration.test.js +164 -0
  27. package/dist/__tests__/integration/data-api.integration.test.js.map +1 -0
  28. package/dist/__tests__/integration/gamma-api.integration.test.d.ts +9 -0
  29. package/dist/__tests__/integration/gamma-api.integration.test.d.ts.map +1 -0
  30. package/dist/__tests__/integration/gamma-api.integration.test.js +170 -0
  31. package/dist/__tests__/integration/gamma-api.integration.test.js.map +1 -0
  32. package/dist/__tests__/integration/market-service.integration.test.d.ts +10 -0
  33. package/dist/__tests__/integration/market-service.integration.test.d.ts.map +1 -0
  34. package/dist/__tests__/integration/market-service.integration.test.js +173 -0
  35. package/dist/__tests__/integration/market-service.integration.test.js.map +1 -0
  36. package/dist/__tests__/integration/realtime-service-v2.integration.test.d.ts +10 -0
  37. package/dist/__tests__/integration/realtime-service-v2.integration.test.d.ts.map +1 -0
  38. package/dist/__tests__/integration/realtime-service-v2.integration.test.js +307 -0
  39. package/dist/__tests__/integration/realtime-service-v2.integration.test.js.map +1 -0
  40. package/dist/__tests__/integration/trading-service.integration.test.d.ts +10 -0
  41. package/dist/__tests__/integration/trading-service.integration.test.d.ts.map +1 -0
  42. package/dist/__tests__/integration/trading-service.integration.test.js +58 -0
  43. package/dist/__tests__/integration/trading-service.integration.test.js.map +1 -0
  44. package/dist/__tests__/test-utils.d.ts +92 -0
  45. package/dist/__tests__/test-utils.d.ts.map +1 -0
  46. package/dist/__tests__/test-utils.js +143 -0
  47. package/dist/__tests__/test-utils.js.map +1 -0
  48. package/dist/clients/bridge-client.d.ts +388 -0
  49. package/dist/clients/bridge-client.d.ts.map +1 -0
  50. package/dist/clients/bridge-client.js +587 -0
  51. package/dist/clients/bridge-client.js.map +1 -0
  52. package/dist/clients/clob-api.d.ts +391 -0
  53. package/dist/clients/clob-api.d.ts.map +1 -0
  54. package/dist/clients/clob-api.js +448 -0
  55. package/dist/clients/clob-api.js.map +1 -0
  56. package/dist/clients/ctf-client.d.ts +473 -0
  57. package/dist/clients/ctf-client.d.ts.map +1 -0
  58. package/dist/clients/ctf-client.js +915 -0
  59. package/dist/clients/ctf-client.js.map +1 -0
  60. package/dist/clients/data-api.d.ts +439 -0
  61. package/dist/clients/data-api.d.ts.map +1 -0
  62. package/dist/clients/data-api.js +592 -0
  63. package/dist/clients/data-api.js.map +1 -0
  64. package/dist/clients/gamma-api.d.ts +401 -0
  65. package/dist/clients/gamma-api.d.ts.map +1 -0
  66. package/dist/clients/gamma-api.js +352 -0
  67. package/dist/clients/gamma-api.js.map +1 -0
  68. package/dist/clients/subgraph.d.ts +196 -0
  69. package/dist/clients/subgraph.d.ts.map +1 -0
  70. package/dist/clients/subgraph.js +332 -0
  71. package/dist/clients/subgraph.js.map +1 -0
  72. package/dist/clients/trading-client.d.ts +252 -0
  73. package/dist/clients/trading-client.d.ts.map +1 -0
  74. package/dist/clients/trading-client.js +543 -0
  75. package/dist/clients/trading-client.js.map +1 -0
  76. package/dist/clients/websocket-manager.d.ts +103 -0
  77. package/dist/clients/websocket-manager.d.ts.map +1 -0
  78. package/dist/clients/websocket-manager.js +200 -0
  79. package/dist/clients/websocket-manager.js.map +1 -0
  80. package/dist/core/cache-adapter-bridge.d.ts +36 -0
  81. package/dist/core/cache-adapter-bridge.d.ts.map +1 -0
  82. package/dist/core/cache-adapter-bridge.js +81 -0
  83. package/dist/core/cache-adapter-bridge.js.map +1 -0
  84. package/dist/core/cache.d.ts +41 -0
  85. package/dist/core/cache.d.ts.map +1 -0
  86. package/dist/core/cache.js +72 -0
  87. package/dist/core/cache.js.map +1 -0
  88. package/dist/core/errors.d.ts +39 -0
  89. package/dist/core/errors.d.ts.map +1 -0
  90. package/dist/core/errors.js +86 -0
  91. package/dist/core/errors.js.map +1 -0
  92. package/dist/core/rate-limiter.d.ts +32 -0
  93. package/dist/core/rate-limiter.d.ts.map +1 -0
  94. package/dist/core/rate-limiter.js +75 -0
  95. package/dist/core/rate-limiter.js.map +1 -0
  96. package/dist/core/types.d.ts +402 -0
  97. package/dist/core/types.d.ts.map +1 -0
  98. package/dist/core/types.js +19 -0
  99. package/dist/core/types.js.map +1 -0
  100. package/dist/core/types.test.d.ts +7 -0
  101. package/dist/core/types.test.d.ts.map +1 -0
  102. package/dist/core/types.test.js +122 -0
  103. package/dist/core/types.test.js.map +1 -0
  104. package/dist/core/unified-cache.d.ts +63 -0
  105. package/dist/core/unified-cache.d.ts.map +1 -0
  106. package/dist/core/unified-cache.js +114 -0
  107. package/dist/core/unified-cache.js.map +1 -0
  108. package/dist/index.d.ts +151 -0
  109. package/dist/index.d.ts.map +1 -0
  110. package/dist/index.js +248 -0
  111. package/dist/index.js.map +1 -0
  112. package/dist/services/arbitrage-service.d.ts +409 -0
  113. package/dist/services/arbitrage-service.d.ts.map +1 -0
  114. package/dist/services/arbitrage-service.js +1440 -0
  115. package/dist/services/arbitrage-service.js.map +1 -0
  116. package/dist/services/authorization-service.d.ts +97 -0
  117. package/dist/services/authorization-service.d.ts.map +1 -0
  118. package/dist/services/authorization-service.js +279 -0
  119. package/dist/services/authorization-service.js.map +1 -0
  120. package/dist/services/market-service.d.ts +208 -0
  121. package/dist/services/market-service.d.ts.map +1 -0
  122. package/dist/services/market-service.js +774 -0
  123. package/dist/services/market-service.js.map +1 -0
  124. package/dist/services/onchain-service.d.ts +309 -0
  125. package/dist/services/onchain-service.d.ts.map +1 -0
  126. package/dist/services/onchain-service.js +417 -0
  127. package/dist/services/onchain-service.js.map +1 -0
  128. package/dist/services/realtime-service-v2.d.ts +361 -0
  129. package/dist/services/realtime-service-v2.d.ts.map +1 -0
  130. package/dist/services/realtime-service-v2.js +840 -0
  131. package/dist/services/realtime-service-v2.js.map +1 -0
  132. package/dist/services/realtime-service.d.ts +82 -0
  133. package/dist/services/realtime-service.d.ts.map +1 -0
  134. package/dist/services/realtime-service.js +182 -0
  135. package/dist/services/realtime-service.js.map +1 -0
  136. package/dist/services/smart-money-service.d.ts +196 -0
  137. package/dist/services/smart-money-service.d.ts.map +1 -0
  138. package/dist/services/smart-money-service.js +358 -0
  139. package/dist/services/smart-money-service.js.map +1 -0
  140. package/dist/services/swap-service.d.ts +217 -0
  141. package/dist/services/swap-service.d.ts.map +1 -0
  142. package/dist/services/swap-service.js +695 -0
  143. package/dist/services/swap-service.js.map +1 -0
  144. package/dist/services/trading-service.d.ts +156 -0
  145. package/dist/services/trading-service.d.ts.map +1 -0
  146. package/dist/services/trading-service.js +356 -0
  147. package/dist/services/trading-service.js.map +1 -0
  148. package/dist/services/wallet-service.d.ts +275 -0
  149. package/dist/services/wallet-service.d.ts.map +1 -0
  150. package/dist/services/wallet-service.js +630 -0
  151. package/dist/services/wallet-service.js.map +1 -0
  152. package/dist/utils/price-utils.d.ts +153 -0
  153. package/dist/utils/price-utils.d.ts.map +1 -0
  154. package/dist/utils/price-utils.js +236 -0
  155. package/dist/utils/price-utils.js.map +1 -0
  156. package/dist/utils/price-utils.test.d.ts +5 -0
  157. package/dist/utils/price-utils.test.d.ts.map +1 -0
  158. package/dist/utils/price-utils.test.js +192 -0
  159. package/dist/utils/price-utils.test.js.map +1 -0
  160. package/package.json +10 -4
  161. package/README.en.md +0 -538
  162. package/docs/00-design.md +0 -760
  163. package/docs/02-API.md +0 -1148
  164. package/docs/arb/test-plan.md +0 -387
  165. package/docs/arb/test-results.md +0 -336
  166. package/docs/arbitrage.md +0 -754
  167. package/docs/reports/smart-money-analysis-2025-12-23-cn.md +0 -840
  168. package/examples/01-basic-usage.ts +0 -68
  169. package/examples/02-smart-money.ts +0 -95
  170. package/examples/03-market-analysis.ts +0 -108
  171. package/examples/04-kline-aggregation.ts +0 -158
  172. package/examples/05-follow-wallet-strategy.ts +0 -156
  173. package/examples/06-services-demo.ts +0 -124
  174. package/examples/07-realtime-websocket.ts +0 -117
  175. package/examples/08-trading-orders.ts +0 -278
  176. package/examples/09-rewards-tracking.ts +0 -187
  177. package/examples/10-ctf-operations.ts +0 -336
  178. package/examples/11-live-arbitrage-scan.ts +0 -221
  179. package/examples/12-trending-arb-monitor.ts +0 -406
  180. package/examples/13-arbitrage-service.ts +0 -211
  181. package/examples/README.md +0 -179
  182. package/scripts/README.md +0 -163
  183. package/scripts/approvals/approve-erc1155.ts +0 -129
  184. package/scripts/approvals/approve-neg-risk-erc1155.ts +0 -149
  185. package/scripts/approvals/approve-neg-risk.ts +0 -102
  186. package/scripts/approvals/check-all-allowances.ts +0 -150
  187. package/scripts/approvals/check-allowance.ts +0 -129
  188. package/scripts/approvals/check-ctf-approval.ts +0 -158
  189. package/scripts/arb/faze-bo3-arb.ts +0 -385
  190. package/scripts/arb/settle-position.ts +0 -190
  191. package/scripts/arb/token-rebalancer.ts +0 -420
  192. package/scripts/arb-tests/01-unit-tests.ts +0 -495
  193. package/scripts/arb-tests/02-integration-tests.ts +0 -412
  194. package/scripts/arb-tests/03-e2e-tests.ts +0 -503
  195. package/scripts/arb-tests/README.md +0 -109
  196. package/scripts/datas/001-report.md +0 -486
  197. package/scripts/datas/clone-modal-screenshot.png +0 -0
  198. package/scripts/deposit/deposit-native-usdc.ts +0 -179
  199. package/scripts/deposit/deposit-usdc.ts +0 -155
  200. package/scripts/deposit/swap-usdc-to-usdce.ts +0 -375
  201. package/scripts/research/research-markets.ts +0 -166
  202. package/scripts/trading/check-orders.ts +0 -50
  203. package/scripts/trading/sell-nvidia-positions.ts +0 -206
  204. package/scripts/trading/test-order.ts +0 -172
  205. package/scripts/verify/test-approve-trading.ts +0 -98
  206. package/scripts/verify/test-provider-fix.ts +0 -43
  207. package/scripts/verify/test-search-mcp.ts +0 -113
  208. package/scripts/verify/verify-all-apis.ts +0 -160
  209. package/scripts/wallet/check-wallet-balances.ts +0 -75
  210. package/scripts/wallet/test-wallet-operations.ts +0 -191
  211. package/scripts/wallet/verify-wallet-tools.ts +0 -124
  212. package/src/__tests__/clob-api.test.ts +0 -301
  213. package/src/__tests__/integration/bridge-client.integration.test.ts +0 -314
  214. package/src/__tests__/integration/clob-api.integration.test.ts +0 -218
  215. package/src/__tests__/integration/ctf-client.integration.test.ts +0 -331
  216. package/src/__tests__/integration/data-api.integration.test.ts +0 -194
  217. package/src/__tests__/integration/gamma-api.integration.test.ts +0 -206
  218. package/src/__tests__/test-utils.ts +0 -170
  219. package/src/clients/bridge-client.ts +0 -841
  220. package/src/clients/clob-api.ts +0 -629
  221. package/src/clients/ctf-client.ts +0 -1216
  222. package/src/clients/data-api.ts +0 -469
  223. package/src/clients/gamma-api.ts +0 -597
  224. package/src/clients/trading-client.ts +0 -749
  225. package/src/clients/websocket-manager.ts +0 -267
  226. package/src/core/cache-adapter-bridge.ts +0 -94
  227. package/src/core/cache.ts +0 -85
  228. package/src/core/errors.ts +0 -117
  229. package/src/core/rate-limiter.ts +0 -74
  230. package/src/core/types.ts +0 -360
  231. package/src/core/unified-cache.ts +0 -153
  232. package/src/index.ts +0 -461
  233. package/src/services/arbitrage-service.ts +0 -1807
  234. package/src/services/authorization-service.ts +0 -357
  235. package/src/services/market-service.ts +0 -544
  236. package/src/services/realtime-service.ts +0 -196
  237. package/src/services/swap-service.ts +0 -896
  238. package/src/services/wallet-service.ts +0 -259
  239. package/src/utils/price-utils.ts +0 -307
  240. package/tsconfig.json +0 -8
  241. package/vitest.config.ts +0 -19
  242. package/vitest.integration.config.ts +0 -18
@@ -1,267 +0,0 @@
1
- /**
2
- * WebSocket Manager
3
- *
4
- * Wraps @nevuamarkets/poly-websockets for real-time market data:
5
- * - Price updates (derived from order book and trades)
6
- * - Order book snapshots
7
- * - Last trade price events
8
- *
9
- * Features:
10
- * - Automatic connection management
11
- * - Rate limiting built-in
12
- * - Price caching for quick access
13
- * - EventEmitter-based event distribution
14
- */
15
-
16
- import { EventEmitter } from 'events';
17
- import type { PriceUpdate, BookUpdate } from '../core/types.js';
18
-
19
- // Note: poly-websockets types (these match the library's exports)
20
- interface PolymarketPriceUpdateEvent {
21
- event_type: 'price_update';
22
- asset_id: string;
23
- timestamp: string;
24
- price: string;
25
- midpoint: string;
26
- spread: string;
27
- }
28
-
29
- interface BookEvent {
30
- market: string;
31
- asset_id: string;
32
- timestamp: string;
33
- bids: Array<{ price: string; size: string }>;
34
- asks: Array<{ price: string; size: string }>;
35
- event_type: 'book';
36
- }
37
-
38
- interface LastTradePriceEvent {
39
- asset_id: string;
40
- event_type: 'last_trade_price';
41
- price: string;
42
- side: 'BUY' | 'SELL';
43
- size: string;
44
- timestamp: string;
45
- }
46
-
47
- export interface WebSocketManagerConfig {
48
- maxMarketsPerWS?: number;
49
- enableLogging?: boolean;
50
- }
51
-
52
- export interface WebSocketManagerEvents {
53
- priceUpdate: (update: PriceUpdate) => void;
54
- bookUpdate: (update: BookUpdate) => void;
55
- lastTrade: (trade: { assetId: string; price: number; side: 'BUY' | 'SELL'; size: number; timestamp: number }) => void;
56
- connected: (info: { groupId: string; assetIds: string[] }) => void;
57
- disconnected: (info: { groupId: string; code: number; reason: string }) => void;
58
- error: (error: Error) => void;
59
- }
60
-
61
- export class WebSocketManager extends EventEmitter {
62
- private wsManager: unknown; // WSSubscriptionManager instance
63
- private subscriptions: Set<string> = new Set();
64
- private priceCache: Map<string, PriceUpdate> = new Map();
65
- private bookCache: Map<string, BookUpdate> = new Map();
66
- private initialized = false;
67
- private config: WebSocketManagerConfig;
68
-
69
- constructor(config: WebSocketManagerConfig = {}) {
70
- super();
71
- this.config = {
72
- maxMarketsPerWS: config.maxMarketsPerWS || 100,
73
- enableLogging: config.enableLogging ?? false,
74
- };
75
- }
76
-
77
- /**
78
- * Initialize the WebSocket manager (lazy initialization)
79
- */
80
- private async ensureInitialized(): Promise<void> {
81
- if (this.initialized) return;
82
-
83
- try {
84
- // Dynamic import to handle the package not being installed
85
- const { WSSubscriptionManager } = await import('@nevuamarkets/poly-websockets');
86
-
87
- this.wsManager = new WSSubscriptionManager(
88
- {
89
- onPolymarketPriceUpdate: this.handlePriceUpdate.bind(this),
90
- onBook: this.handleBookUpdate.bind(this),
91
- onLastTradePrice: this.handleLastTradePrice.bind(this),
92
- onWSOpen: this.handleOpen.bind(this),
93
- onWSClose: this.handleClose.bind(this),
94
- onError: this.handleError.bind(this),
95
- },
96
- {
97
- maxMarketsPerWS: this.config.maxMarketsPerWS,
98
- }
99
- );
100
-
101
- this.initialized = true;
102
- } catch (error) {
103
- throw new Error(
104
- 'Failed to initialize WebSocket manager. Make sure @nevuamarkets/poly-websockets is installed.'
105
- );
106
- }
107
- }
108
-
109
- // ===== Subscription Management =====
110
-
111
- /**
112
- * Subscribe to asset price updates
113
- */
114
- async subscribe(assetIds: string[]): Promise<void> {
115
- await this.ensureInitialized();
116
-
117
- const newIds = assetIds.filter((id) => !this.subscriptions.has(id));
118
- if (newIds.length === 0) return;
119
-
120
- const manager = this.wsManager as { addSubscriptions: (ids: string[]) => Promise<void> };
121
- await manager.addSubscriptions(newIds);
122
- newIds.forEach((id) => this.subscriptions.add(id));
123
- }
124
-
125
- /**
126
- * Unsubscribe from asset price updates
127
- */
128
- async unsubscribe(assetIds: string[]): Promise<void> {
129
- if (!this.initialized) return;
130
-
131
- const existingIds = assetIds.filter((id) => this.subscriptions.has(id));
132
- if (existingIds.length === 0) return;
133
-
134
- const manager = this.wsManager as { removeSubscriptions: (ids: string[]) => Promise<void> };
135
- await manager.removeSubscriptions(existingIds);
136
- existingIds.forEach((id) => {
137
- this.subscriptions.delete(id);
138
- this.priceCache.delete(id);
139
- this.bookCache.delete(id);
140
- });
141
- }
142
-
143
- /**
144
- * Unsubscribe from all assets and cleanup
145
- */
146
- async unsubscribeAll(): Promise<void> {
147
- if (!this.initialized) return;
148
-
149
- const manager = this.wsManager as { clearState: () => Promise<void> };
150
- await manager.clearState();
151
- this.subscriptions.clear();
152
- this.priceCache.clear();
153
- this.bookCache.clear();
154
- }
155
-
156
- // ===== Price Cache Access =====
157
-
158
- /**
159
- * Get cached price for an asset
160
- */
161
- getPrice(assetId: string): PriceUpdate | undefined {
162
- return this.priceCache.get(assetId);
163
- }
164
-
165
- /**
166
- * Get all cached prices
167
- */
168
- getAllPrices(): Map<string, PriceUpdate> {
169
- return new Map(this.priceCache);
170
- }
171
-
172
- /**
173
- * Get cached order book for an asset
174
- */
175
- getBook(assetId: string): BookUpdate | undefined {
176
- return this.bookCache.get(assetId);
177
- }
178
-
179
- // ===== State Query =====
180
-
181
- /**
182
- * Get subscribed asset IDs
183
- */
184
- getSubscribedAssets(): string[] {
185
- return Array.from(this.subscriptions);
186
- }
187
-
188
- /**
189
- * Get connection statistics
190
- */
191
- getStatistics(): { groups: number; subscriptions: number } | null {
192
- if (!this.initialized) return null;
193
-
194
- const manager = this.wsManager as { getStatistics: () => { groups: number; subscriptions: number } };
195
- return manager.getStatistics();
196
- }
197
-
198
- /**
199
- * Check if initialized
200
- */
201
- isInitialized(): boolean {
202
- return this.initialized;
203
- }
204
-
205
- // ===== Event Handlers =====
206
-
207
- private async handlePriceUpdate(events: PolymarketPriceUpdateEvent[]): Promise<void> {
208
- for (const event of events) {
209
- const update: PriceUpdate = {
210
- assetId: event.asset_id,
211
- price: parseFloat(event.price),
212
- midpoint: parseFloat(event.midpoint),
213
- spread: parseFloat(event.spread),
214
- timestamp: parseInt(event.timestamp, 10),
215
- };
216
- this.priceCache.set(event.asset_id, update);
217
- this.emit('priceUpdate', update);
218
- }
219
- }
220
-
221
- private async handleBookUpdate(events: BookEvent[]): Promise<void> {
222
- for (const event of events) {
223
- // Parse and sort bids descending (highest price = best bid first)
224
- const bids = event.bids
225
- .map((l) => ({ price: parseFloat(l.price), size: parseFloat(l.size) }))
226
- .sort((a, b) => b.price - a.price);
227
-
228
- // Parse and sort asks ascending (lowest price = best ask first)
229
- const asks = event.asks
230
- .map((l) => ({ price: parseFloat(l.price), size: parseFloat(l.size) }))
231
- .sort((a, b) => a.price - b.price);
232
-
233
- const update: BookUpdate = {
234
- assetId: event.asset_id,
235
- bids,
236
- asks,
237
- timestamp: parseInt(event.timestamp, 10),
238
- };
239
- this.bookCache.set(event.asset_id, update);
240
- this.emit('bookUpdate', update);
241
- }
242
- }
243
-
244
- private async handleLastTradePrice(events: LastTradePriceEvent[]): Promise<void> {
245
- for (const event of events) {
246
- this.emit('lastTrade', {
247
- assetId: event.asset_id,
248
- price: parseFloat(event.price),
249
- side: event.side,
250
- size: parseFloat(event.size),
251
- timestamp: parseInt(event.timestamp, 10),
252
- });
253
- }
254
- }
255
-
256
- private async handleOpen(groupId: string, assetIds: string[]): Promise<void> {
257
- this.emit('connected', { groupId, assetIds });
258
- }
259
-
260
- private async handleClose(groupId: string, code: number, reason: string): Promise<void> {
261
- this.emit('disconnected', { groupId, code, reason });
262
- }
263
-
264
- private async handleError(error: Error): Promise<void> {
265
- this.emit('error', error);
266
- }
267
- }
@@ -1,94 +0,0 @@
1
- /**
2
- * Bridge adapter between legacy Cache class and new CacheAdapter interface
3
- *
4
- * This allows the SDK to work with both:
5
- * 1. Legacy internal Cache (synchronous, millisecond TTL)
6
- * 2. New CacheAdapter interface (async, second TTL)
7
- */
8
-
9
- import type { CacheAdapter } from '@catalyst-team/cache';
10
- import { Cache } from './cache.js';
11
-
12
- /**
13
- * Wraps the legacy Cache class to implement CacheAdapter interface
14
- */
15
- export class LegacyCacheAdapter implements CacheAdapter {
16
- constructor(private cache: Cache) {}
17
-
18
- async get<T>(key: string): Promise<T | null> {
19
- const value = this.cache.get<T>(key);
20
- return value === undefined ? null : value;
21
- }
22
-
23
- async set<T>(key: string, value: T, ttl?: number): Promise<void> {
24
- // Convert seconds to milliseconds (CacheAdapter uses seconds, Cache uses ms)
25
- const ttlMs = ttl ? ttl * 1000 : 60000; // Default 60s
26
- this.cache.set(key, value, ttlMs);
27
- }
28
-
29
- async del(key: string): Promise<void> {
30
- this.cache.invalidate(key);
31
- }
32
-
33
- async exists(key: string): Promise<boolean> {
34
- const value = this.cache.get(key);
35
- return value !== undefined;
36
- }
37
-
38
- async clear(): Promise<void> {
39
- this.cache.clear();
40
- }
41
- }
42
-
43
- /**
44
- * Wraps a CacheAdapter to provide the legacy Cache interface
45
- * This allows using new cache adapters with code expecting the old Cache class
46
- */
47
- export class CacheAdapterWrapper {
48
- constructor(private adapter: CacheAdapter) {}
49
-
50
- get<T>(key: string): T | undefined {
51
- // Note: This makes an async operation sync, which may cause issues
52
- // However, we need to maintain backward compatibility
53
- let result: T | undefined;
54
- this.adapter.get<T>(key).then((value) => {
55
- result = value ?? undefined;
56
- });
57
- return result;
58
- }
59
-
60
- set<T>(key: string, value: T, ttlMs: number): void {
61
- // Convert milliseconds to seconds
62
- const ttlSeconds = Math.ceil(ttlMs / 1000);
63
- void this.adapter.set(key, value, ttlSeconds);
64
- }
65
-
66
- async getOrSet<T>(
67
- key: string,
68
- ttlMs: number,
69
- factory: () => Promise<T>
70
- ): Promise<T> {
71
- const cached = await this.adapter.get<T>(key);
72
- if (cached !== null) return cached;
73
-
74
- const value = await factory();
75
- const ttlSeconds = Math.ceil(ttlMs / 1000);
76
- await this.adapter.set(key, value, ttlSeconds);
77
- return value;
78
- }
79
-
80
- invalidate(pattern: string): void {
81
- // CacheAdapter doesn't have pattern matching, so we can't implement this
82
- // This is a limitation of the adapter approach
83
- console.warn('invalidate(pattern) not supported with external cache adapter');
84
- }
85
-
86
- clear(): void {
87
- void this.adapter.clear?.();
88
- }
89
-
90
- size(): number {
91
- // CacheAdapter doesn't expose size, return -1 to indicate unknown
92
- return -1;
93
- }
94
- }
package/src/core/cache.ts DELETED
@@ -1,85 +0,0 @@
1
- /**
2
- * Simple in-memory cache with TTL support
3
- */
4
-
5
- interface CacheEntry<T> {
6
- value: T;
7
- expiresAt: number;
8
- }
9
-
10
- export class Cache {
11
- private store: Map<string, CacheEntry<unknown>> = new Map();
12
-
13
- /**
14
- * Get a cached value
15
- */
16
- get<T>(key: string): T | undefined {
17
- const entry = this.store.get(key);
18
- if (!entry) return undefined;
19
- if (Date.now() > entry.expiresAt) {
20
- this.store.delete(key);
21
- return undefined;
22
- }
23
- return entry.value as T;
24
- }
25
-
26
- /**
27
- * Set a cached value with TTL
28
- */
29
- set<T>(key: string, value: T, ttlMs: number): void {
30
- this.store.set(key, {
31
- value,
32
- expiresAt: Date.now() + ttlMs,
33
- });
34
- }
35
-
36
- /**
37
- * Get a cached value or set it if not present
38
- */
39
- async getOrSet<T>(
40
- key: string,
41
- ttlMs: number,
42
- factory: () => Promise<T>
43
- ): Promise<T> {
44
- const cached = this.get<T>(key);
45
- if (cached !== undefined) return cached;
46
- const value = await factory();
47
- this.set(key, value, ttlMs);
48
- return value;
49
- }
50
-
51
- /**
52
- * Invalidate all keys matching a pattern
53
- */
54
- invalidate(pattern: string): void {
55
- for (const key of this.store.keys()) {
56
- if (key.includes(pattern)) {
57
- this.store.delete(key);
58
- }
59
- }
60
- }
61
-
62
- /**
63
- * Clear all cached values
64
- */
65
- clear(): void {
66
- this.store.clear();
67
- }
68
-
69
- /**
70
- * Get the number of cached entries
71
- */
72
- size(): number {
73
- return this.store.size;
74
- }
75
- }
76
-
77
- /**
78
- * Cache TTL constants (in milliseconds)
79
- */
80
- export const CACHE_TTL = {
81
- MARKET_INFO: 60 * 1000, // 1 minute
82
- WALLET_POSITIONS: 5 * 60 * 1000, // 5 minutes
83
- LEADERBOARD: 60 * 60 * 1000, // 1 hour
84
- TICK_SIZE: 24 * 60 * 60 * 1000, // 24 hours
85
- };
@@ -1,117 +0,0 @@
1
- /**
2
- * Unified error handling for Polymarket SDK
3
- */
4
-
5
- export enum ErrorCode {
6
- // Network errors
7
- NETWORK_ERROR = 'NETWORK_ERROR',
8
- TIMEOUT = 'TIMEOUT',
9
- RATE_LIMITED = 'RATE_LIMITED',
10
-
11
- // Authentication errors
12
- AUTH_FAILED = 'AUTH_FAILED',
13
- API_KEY_EXPIRED = 'API_KEY_EXPIRED',
14
- INVALID_SIGNATURE = 'INVALID_SIGNATURE',
15
-
16
- // Data errors
17
- MARKET_NOT_FOUND = 'MARKET_NOT_FOUND',
18
- WALLET_NOT_FOUND = 'WALLET_NOT_FOUND',
19
- INVALID_RESPONSE = 'INVALID_RESPONSE',
20
-
21
- // Trading errors
22
- INSUFFICIENT_BALANCE = 'INSUFFICIENT_BALANCE',
23
- ORDER_REJECTED = 'ORDER_REJECTED',
24
- ORDER_FAILED = 'ORDER_FAILED',
25
- MARKET_CLOSED = 'MARKET_CLOSED',
26
-
27
- // API errors
28
- API_ERROR = 'API_ERROR',
29
-
30
- // Internal errors
31
- INTERNAL_ERROR = 'INTERNAL_ERROR',
32
- }
33
-
34
- export class PolymarketError extends Error {
35
- constructor(
36
- public code: ErrorCode,
37
- message: string,
38
- public retryable: boolean = false,
39
- public originalError?: Error
40
- ) {
41
- super(message);
42
- this.name = 'PolymarketError';
43
- }
44
-
45
- /**
46
- * Create error from HTTP response status
47
- */
48
- static fromHttpError(status: number, body?: unknown): PolymarketError {
49
- const bodyMessage =
50
- body && typeof body === 'object' && 'message' in body
51
- ? String((body as { message: unknown }).message)
52
- : '';
53
-
54
- switch (status) {
55
- case 429:
56
- return new PolymarketError(
57
- ErrorCode.RATE_LIMITED,
58
- bodyMessage || 'Rate limited',
59
- true
60
- );
61
- case 401:
62
- return new PolymarketError(
63
- ErrorCode.AUTH_FAILED,
64
- bodyMessage || 'Authentication failed'
65
- );
66
- case 403:
67
- return new PolymarketError(
68
- ErrorCode.AUTH_FAILED,
69
- bodyMessage || 'Forbidden'
70
- );
71
- case 404:
72
- return new PolymarketError(
73
- ErrorCode.MARKET_NOT_FOUND,
74
- bodyMessage || 'Resource not found'
75
- );
76
- case 400:
77
- return new PolymarketError(
78
- ErrorCode.INVALID_RESPONSE,
79
- bodyMessage || 'Bad request'
80
- );
81
- default:
82
- return new PolymarketError(
83
- ErrorCode.NETWORK_ERROR,
84
- bodyMessage || `HTTP ${status}`,
85
- status >= 500
86
- );
87
- }
88
- }
89
- }
90
-
91
- /**
92
- * Retry decorator for async functions
93
- */
94
- export async function withRetry<T>(
95
- fn: () => Promise<T>,
96
- options: { maxRetries?: number; delay?: number } = {}
97
- ): Promise<T> {
98
- const { maxRetries = 3, delay = 1000 } = options;
99
-
100
- let lastError: Error | undefined;
101
-
102
- for (let i = 0; i < maxRetries; i++) {
103
- try {
104
- return await fn();
105
- } catch (error) {
106
- lastError = error as Error;
107
- if (error instanceof PolymarketError && !error.retryable) {
108
- throw error;
109
- }
110
- if (i < maxRetries - 1) {
111
- await new Promise((r) => setTimeout(r, delay * Math.pow(2, i)));
112
- }
113
- }
114
- }
115
-
116
- throw lastError;
117
- }
@@ -1,74 +0,0 @@
1
- /**
2
- * Rate Limiter for Polymarket APIs
3
- * - Data API: 100ms minimum interval
4
- * - Gamma API: 10 req/s
5
- * - CLOB API: 10 req/s
6
- */
7
-
8
- import Bottleneck from 'bottleneck';
9
-
10
- export enum ApiType {
11
- DATA_API = 'data-api',
12
- GAMMA_API = 'gamma-api',
13
- CLOB_API = 'clob-api',
14
- }
15
-
16
- const API_LIMITS: Record<ApiType, Bottleneck.ConstructorOptions> = {
17
- [ApiType.DATA_API]: {
18
- minTime: 100, // 100ms minimum interval
19
- maxConcurrent: 5,
20
- },
21
- [ApiType.GAMMA_API]: {
22
- reservoir: 10,
23
- reservoirRefreshAmount: 10,
24
- reservoirRefreshInterval: 1000,
25
- },
26
- [ApiType.CLOB_API]: {
27
- reservoir: 10,
28
- reservoirRefreshAmount: 10,
29
- reservoirRefreshInterval: 1000,
30
- },
31
- };
32
-
33
- export class RateLimiter {
34
- private limiters: Map<ApiType, Bottleneck> = new Map();
35
-
36
- constructor() {
37
- for (const [type, config] of Object.entries(API_LIMITS)) {
38
- this.limiters.set(type as ApiType, new Bottleneck(config));
39
- }
40
- }
41
-
42
- /**
43
- * Execute a function with rate limiting
44
- */
45
- async execute<T>(api: ApiType, fn: () => Promise<T>): Promise<T> {
46
- const limiter = this.limiters.get(api);
47
- if (!limiter) throw new Error(`Unknown API type: ${api}`);
48
- return limiter.schedule(fn);
49
- }
50
-
51
- /**
52
- * Execute multiple functions in order with rate limiting
53
- */
54
- async executeBatch<T>(api: ApiType, fns: (() => Promise<T>)[]): Promise<T[]> {
55
- const results: T[] = [];
56
- for (const fn of fns) {
57
- results.push(await this.execute(api, fn));
58
- }
59
- return results;
60
- }
61
-
62
- /**
63
- * Get current limiter statistics
64
- */
65
- getStats(api: ApiType): { running: number; queued: number } | null {
66
- const limiter = this.limiters.get(api);
67
- if (!limiter) return null;
68
- const counts = limiter.counts();
69
- return {
70
- running: counts.RUNNING,
71
- queued: counts.QUEUED,
72
- };
73
- }
74
- }