@catalyst-team/poly-sdk 0.1.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 (244) hide show
  1. package/.env +0 -0
  2. package/README.md +803 -0
  3. package/dist/__tests__/clob-api.test.d.ts +5 -0
  4. package/dist/__tests__/clob-api.test.d.ts.map +1 -0
  5. package/dist/__tests__/clob-api.test.js +240 -0
  6. package/dist/__tests__/clob-api.test.js.map +1 -0
  7. package/dist/__tests__/integration/bridge-client.integration.test.d.ts +11 -0
  8. package/dist/__tests__/integration/bridge-client.integration.test.d.ts.map +1 -0
  9. package/dist/__tests__/integration/bridge-client.integration.test.js +260 -0
  10. package/dist/__tests__/integration/bridge-client.integration.test.js.map +1 -0
  11. package/dist/__tests__/integration/clob-api.integration.test.d.ts +13 -0
  12. package/dist/__tests__/integration/clob-api.integration.test.d.ts.map +1 -0
  13. package/dist/__tests__/integration/clob-api.integration.test.js +170 -0
  14. package/dist/__tests__/integration/clob-api.integration.test.js.map +1 -0
  15. package/dist/__tests__/integration/ctf-client.integration.test.d.ts +17 -0
  16. package/dist/__tests__/integration/ctf-client.integration.test.d.ts.map +1 -0
  17. package/dist/__tests__/integration/ctf-client.integration.test.js +234 -0
  18. package/dist/__tests__/integration/ctf-client.integration.test.js.map +1 -0
  19. package/dist/__tests__/integration/data-api.integration.test.d.ts +9 -0
  20. package/dist/__tests__/integration/data-api.integration.test.d.ts.map +1 -0
  21. package/dist/__tests__/integration/data-api.integration.test.js +161 -0
  22. package/dist/__tests__/integration/data-api.integration.test.js.map +1 -0
  23. package/dist/__tests__/integration/gamma-api.integration.test.d.ts +9 -0
  24. package/dist/__tests__/integration/gamma-api.integration.test.d.ts.map +1 -0
  25. package/dist/__tests__/integration/gamma-api.integration.test.js +170 -0
  26. package/dist/__tests__/integration/gamma-api.integration.test.js.map +1 -0
  27. package/dist/__tests__/test-utils.d.ts +92 -0
  28. package/dist/__tests__/test-utils.d.ts.map +1 -0
  29. package/dist/__tests__/test-utils.js +143 -0
  30. package/dist/__tests__/test-utils.js.map +1 -0
  31. package/dist/clients/bridge-client.d.ts +388 -0
  32. package/dist/clients/bridge-client.d.ts.map +1 -0
  33. package/dist/clients/bridge-client.js +587 -0
  34. package/dist/clients/bridge-client.js.map +1 -0
  35. package/dist/clients/clob-api.d.ts +318 -0
  36. package/dist/clients/clob-api.d.ts.map +1 -0
  37. package/dist/clients/clob-api.js +388 -0
  38. package/dist/clients/clob-api.js.map +1 -0
  39. package/dist/clients/ctf-client.d.ts +473 -0
  40. package/dist/clients/ctf-client.d.ts.map +1 -0
  41. package/dist/clients/ctf-client.js +915 -0
  42. package/dist/clients/ctf-client.js.map +1 -0
  43. package/dist/clients/data-api.d.ts +134 -0
  44. package/dist/clients/data-api.d.ts.map +1 -0
  45. package/dist/clients/data-api.js +265 -0
  46. package/dist/clients/data-api.js.map +1 -0
  47. package/dist/clients/gamma-api.d.ts +401 -0
  48. package/dist/clients/gamma-api.d.ts.map +1 -0
  49. package/dist/clients/gamma-api.js +352 -0
  50. package/dist/clients/gamma-api.js.map +1 -0
  51. package/dist/clients/trading-client.d.ts +252 -0
  52. package/dist/clients/trading-client.d.ts.map +1 -0
  53. package/dist/clients/trading-client.js +543 -0
  54. package/dist/clients/trading-client.js.map +1 -0
  55. package/dist/clients/websocket-manager.d.ts +100 -0
  56. package/dist/clients/websocket-manager.d.ts.map +1 -0
  57. package/dist/clients/websocket-manager.js +193 -0
  58. package/dist/clients/websocket-manager.js.map +1 -0
  59. package/dist/core/cache-adapter-bridge.d.ts +36 -0
  60. package/dist/core/cache-adapter-bridge.d.ts.map +1 -0
  61. package/dist/core/cache-adapter-bridge.js +81 -0
  62. package/dist/core/cache-adapter-bridge.js.map +1 -0
  63. package/dist/core/cache.d.ts +40 -0
  64. package/dist/core/cache.d.ts.map +1 -0
  65. package/dist/core/cache.js +71 -0
  66. package/dist/core/cache.js.map +1 -0
  67. package/dist/core/errors.d.ts +38 -0
  68. package/dist/core/errors.d.ts.map +1 -0
  69. package/dist/core/errors.js +84 -0
  70. package/dist/core/errors.js.map +1 -0
  71. package/dist/core/rate-limiter.d.ts +31 -0
  72. package/dist/core/rate-limiter.d.ts.map +1 -0
  73. package/dist/core/rate-limiter.js +70 -0
  74. package/dist/core/rate-limiter.js.map +1 -0
  75. package/dist/core/types.d.ts +314 -0
  76. package/dist/core/types.d.ts.map +1 -0
  77. package/dist/core/types.js +19 -0
  78. package/dist/core/types.js.map +1 -0
  79. package/dist/core/unified-cache.d.ts +63 -0
  80. package/dist/core/unified-cache.d.ts.map +1 -0
  81. package/dist/core/unified-cache.js +114 -0
  82. package/dist/core/unified-cache.js.map +1 -0
  83. package/dist/index.d.ts +94 -0
  84. package/dist/index.d.ts.map +1 -0
  85. package/dist/index.js +258 -0
  86. package/dist/index.js.map +1 -0
  87. package/dist/mcp/errors.d.ts +33 -0
  88. package/dist/mcp/errors.d.ts.map +1 -0
  89. package/dist/mcp/errors.js +86 -0
  90. package/dist/mcp/errors.js.map +1 -0
  91. package/dist/mcp/index.d.ts +62 -0
  92. package/dist/mcp/index.d.ts.map +1 -0
  93. package/dist/mcp/index.js +173 -0
  94. package/dist/mcp/index.js.map +1 -0
  95. package/dist/mcp/server.d.ts +17 -0
  96. package/dist/mcp/server.d.ts.map +1 -0
  97. package/dist/mcp/server.js +155 -0
  98. package/dist/mcp/server.js.map +1 -0
  99. package/dist/mcp/tools/guide.d.ts +12 -0
  100. package/dist/mcp/tools/guide.d.ts.map +1 -0
  101. package/dist/mcp/tools/guide.js +801 -0
  102. package/dist/mcp/tools/guide.js.map +1 -0
  103. package/dist/mcp/tools/index.d.ts +11 -0
  104. package/dist/mcp/tools/index.d.ts.map +1 -0
  105. package/dist/mcp/tools/index.js +27 -0
  106. package/dist/mcp/tools/index.js.map +1 -0
  107. package/dist/mcp/tools/market.d.ts +11 -0
  108. package/dist/mcp/tools/market.d.ts.map +1 -0
  109. package/dist/mcp/tools/market.js +314 -0
  110. package/dist/mcp/tools/market.js.map +1 -0
  111. package/dist/mcp/tools/order.d.ts +10 -0
  112. package/dist/mcp/tools/order.d.ts.map +1 -0
  113. package/dist/mcp/tools/order.js +258 -0
  114. package/dist/mcp/tools/order.js.map +1 -0
  115. package/dist/mcp/tools/trade.d.ts +38 -0
  116. package/dist/mcp/tools/trade.d.ts.map +1 -0
  117. package/dist/mcp/tools/trade.js +314 -0
  118. package/dist/mcp/tools/trade.js.map +1 -0
  119. package/dist/mcp/tools/trader.d.ts +11 -0
  120. package/dist/mcp/tools/trader.d.ts.map +1 -0
  121. package/dist/mcp/tools/trader.js +277 -0
  122. package/dist/mcp/tools/trader.js.map +1 -0
  123. package/dist/mcp/tools/wallet.d.ts +274 -0
  124. package/dist/mcp/tools/wallet.d.ts.map +1 -0
  125. package/dist/mcp/tools/wallet.js +579 -0
  126. package/dist/mcp/tools/wallet.js.map +1 -0
  127. package/dist/mcp/types.d.ts +413 -0
  128. package/dist/mcp/types.d.ts.map +1 -0
  129. package/dist/mcp/types.js +5 -0
  130. package/dist/mcp/types.js.map +1 -0
  131. package/dist/services/authorization-service.d.ts +97 -0
  132. package/dist/services/authorization-service.d.ts.map +1 -0
  133. package/dist/services/authorization-service.js +279 -0
  134. package/dist/services/authorization-service.js.map +1 -0
  135. package/dist/services/market-service.d.ts +108 -0
  136. package/dist/services/market-service.d.ts.map +1 -0
  137. package/dist/services/market-service.js +458 -0
  138. package/dist/services/market-service.js.map +1 -0
  139. package/dist/services/realtime-service.d.ts +82 -0
  140. package/dist/services/realtime-service.d.ts.map +1 -0
  141. package/dist/services/realtime-service.js +150 -0
  142. package/dist/services/realtime-service.js.map +1 -0
  143. package/dist/services/swap-service.d.ts +217 -0
  144. package/dist/services/swap-service.d.ts.map +1 -0
  145. package/dist/services/swap-service.js +695 -0
  146. package/dist/services/swap-service.js.map +1 -0
  147. package/dist/services/wallet-service.d.ts +94 -0
  148. package/dist/services/wallet-service.d.ts.map +1 -0
  149. package/dist/services/wallet-service.js +173 -0
  150. package/dist/services/wallet-service.js.map +1 -0
  151. package/dist/utils/price-utils.d.ts +153 -0
  152. package/dist/utils/price-utils.d.ts.map +1 -0
  153. package/dist/utils/price-utils.js +236 -0
  154. package/dist/utils/price-utils.js.map +1 -0
  155. package/docs/00-design.md +760 -0
  156. package/docs/01-mcp.md +2041 -0
  157. package/docs/02-API.md +1148 -0
  158. package/docs/e2e/01-trader-tools.md +159 -0
  159. package/docs/e2e/02-market-tools.md +180 -0
  160. package/docs/e2e/03-order-tools.md +166 -0
  161. package/docs/e2e/04-wallet-tools.md +224 -0
  162. package/docs/e2e/05-trading-tools.md +327 -0
  163. package/docs/e2e/06-integration-scenarios.md +481 -0
  164. package/docs/e2e/coordinator.md +376 -0
  165. package/examples/01-basic-usage.ts +68 -0
  166. package/examples/02-smart-money.ts +95 -0
  167. package/examples/03-market-analysis.ts +108 -0
  168. package/examples/04-kline-aggregation.ts +158 -0
  169. package/examples/05-follow-wallet-strategy.ts +156 -0
  170. package/examples/06-services-demo.ts +124 -0
  171. package/examples/07-realtime-websocket.ts +117 -0
  172. package/examples/08-trading-orders.ts +278 -0
  173. package/examples/09-rewards-tracking.ts +187 -0
  174. package/examples/10-ctf-operations.ts +336 -0
  175. package/examples/11-live-arbitrage-scan.ts +221 -0
  176. package/examples/12-trending-arb-monitor.ts +406 -0
  177. package/examples/README.md +179 -0
  178. package/package.json +62 -0
  179. package/scripts/README.md +163 -0
  180. package/scripts/approvals/approve-erc1155.ts +129 -0
  181. package/scripts/approvals/approve-neg-risk-erc1155.ts +149 -0
  182. package/scripts/approvals/approve-neg-risk.ts +102 -0
  183. package/scripts/approvals/check-all-allowances.ts +150 -0
  184. package/scripts/approvals/check-allowance.ts +129 -0
  185. package/scripts/approvals/check-ctf-approval.ts +158 -0
  186. package/scripts/datas/001-report.md +486 -0
  187. package/scripts/datas/clone-modal-screenshot.png +0 -0
  188. package/scripts/deposit/deposit-native-usdc.ts +179 -0
  189. package/scripts/deposit/deposit-usdc.ts +155 -0
  190. package/scripts/deposit/swap-usdc-to-usdce.ts +375 -0
  191. package/scripts/research/research-markets.ts +166 -0
  192. package/scripts/trading/check-orders.ts +50 -0
  193. package/scripts/trading/sell-nvidia-positions.ts +206 -0
  194. package/scripts/trading/test-order.ts +172 -0
  195. package/scripts/truth.md +440 -0
  196. package/scripts/verify/test-approve-trading.ts +98 -0
  197. package/scripts/verify/test-provider-fix.ts +43 -0
  198. package/scripts/verify/test-search-mcp.ts +113 -0
  199. package/scripts/verify/verify-all-apis.ts +160 -0
  200. package/scripts/wallet/check-wallet-balances.ts +75 -0
  201. package/scripts/wallet/test-wallet-operations.ts +191 -0
  202. package/scripts/wallet/verify-wallet-tools.ts +124 -0
  203. package/src/__tests__/clob-api.test.ts +301 -0
  204. package/src/__tests__/integration/bridge-client.integration.test.ts +314 -0
  205. package/src/__tests__/integration/clob-api.integration.test.ts +218 -0
  206. package/src/__tests__/integration/ctf-client.integration.test.ts +331 -0
  207. package/src/__tests__/integration/data-api.integration.test.ts +194 -0
  208. package/src/__tests__/integration/gamma-api.integration.test.ts +206 -0
  209. package/src/__tests__/test-utils.ts +170 -0
  210. package/src/clients/bridge-client.ts +841 -0
  211. package/src/clients/clob-api.ts +629 -0
  212. package/src/clients/ctf-client.ts +1216 -0
  213. package/src/clients/data-api.ts +469 -0
  214. package/src/clients/gamma-api.ts +597 -0
  215. package/src/clients/trading-client.ts +749 -0
  216. package/src/clients/websocket-manager.ts +267 -0
  217. package/src/core/cache-adapter-bridge.ts +94 -0
  218. package/src/core/cache.ts +85 -0
  219. package/src/core/errors.ts +117 -0
  220. package/src/core/rate-limiter.ts +74 -0
  221. package/src/core/types.ts +360 -0
  222. package/src/core/unified-cache.ts +153 -0
  223. package/src/index.ts +455 -0
  224. package/src/mcp/README.md +380 -0
  225. package/src/mcp/errors.ts +124 -0
  226. package/src/mcp/index.ts +309 -0
  227. package/src/mcp/server.ts +183 -0
  228. package/src/mcp/tools/guide.ts +821 -0
  229. package/src/mcp/tools/index.ts +73 -0
  230. package/src/mcp/tools/market.ts +363 -0
  231. package/src/mcp/tools/order.ts +326 -0
  232. package/src/mcp/tools/trade.ts +417 -0
  233. package/src/mcp/tools/trader.ts +322 -0
  234. package/src/mcp/tools/wallet.ts +683 -0
  235. package/src/mcp/types.ts +472 -0
  236. package/src/services/authorization-service.ts +357 -0
  237. package/src/services/market-service.ts +544 -0
  238. package/src/services/realtime-service.ts +196 -0
  239. package/src/services/swap-service.ts +896 -0
  240. package/src/services/wallet-service.ts +259 -0
  241. package/src/utils/price-utils.ts +307 -0
  242. package/tsconfig.json +8 -0
  243. package/vitest.config.ts +19 -0
  244. package/vitest.integration.config.ts +18 -0
@@ -0,0 +1,597 @@
1
+ /**
2
+ * Gamma API Client for Polymarket
3
+ *
4
+ * The Gamma API provides rich market discovery and metadata. Unlike the CLOB API
5
+ * which is focused on trading, Gamma is optimized for browsing, searching, and
6
+ * discovering prediction markets.
7
+ *
8
+ * @remarks
9
+ * - Base URL: https://gamma-api.polymarket.com
10
+ * - Best for: Market discovery, trending markets, event groupings
11
+ * - Rate limits are automatically handled by the RateLimiter
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * import { GammaApiClient, RateLimiter, Cache } from '@prediction-router/poly-sdk';
16
+ *
17
+ * const client = new GammaApiClient(new RateLimiter(), new Cache());
18
+ *
19
+ * // Get trending markets by 24h volume
20
+ * const trending = await client.getTrendingMarkets(20);
21
+ *
22
+ * // Search for specific markets
23
+ * const btcMarkets = await client.getMarkets({
24
+ * active: true,
25
+ * closed: false,
26
+ * order: 'volume24hr',
27
+ * ascending: false,
28
+ * limit: 10,
29
+ * });
30
+ * ```
31
+ *
32
+ * @see {@link https://docs.polymarket.com/#gamma-api Gamma API Documentation}
33
+ *
34
+ * @module clients/gamma-api
35
+ */
36
+
37
+ import { RateLimiter, ApiType } from '../core/rate-limiter.js';
38
+ import type { UnifiedCache } from '../core/unified-cache.js';
39
+ import { PolymarketError } from '../core/errors.js';
40
+
41
+ /** Gamma API base URL */
42
+ const GAMMA_API_BASE = 'https://gamma-api.polymarket.com';
43
+
44
+ // ===== Types =====
45
+
46
+ /**
47
+ * Market information from the Gamma API
48
+ *
49
+ * @remarks
50
+ * Gamma markets include rich metadata like volume statistics, price changes,
51
+ * and liquidity metrics that are useful for market discovery and analysis.
52
+ */
53
+ export interface GammaMarket {
54
+ /**
55
+ * Internal Gamma market ID
56
+ */
57
+ id: string;
58
+
59
+ /**
60
+ * Condition ID matching the CLOB API
61
+ * @example "0x82ace55cdcba920112a2b3548f21e6e117730144db4dd580456aaecf1a2ad751"
62
+ */
63
+ conditionId: string;
64
+
65
+ /**
66
+ * URL-friendly market slug
67
+ * @example "will-btc-reach-100k-by-end-of-2024"
68
+ */
69
+ slug: string;
70
+
71
+ /**
72
+ * The prediction market question
73
+ */
74
+ question: string;
75
+
76
+ /**
77
+ * Detailed description and resolution criteria
78
+ */
79
+ description?: string;
80
+
81
+ /**
82
+ * Outcome names (typically ["Yes", "No"])
83
+ */
84
+ outcomes: string[];
85
+
86
+ /**
87
+ * Current prices for each outcome (0-1 range)
88
+ * @example [0.65, 0.35] for 65% YES probability
89
+ */
90
+ outcomePrices: number[];
91
+
92
+ /**
93
+ * Total trading volume (lifetime, in USDC)
94
+ */
95
+ volume: number;
96
+
97
+ /**
98
+ * 24-hour trading volume (in USDC)
99
+ */
100
+ volume24hr?: number;
101
+
102
+ /**
103
+ * 7-day trading volume (in USDC)
104
+ */
105
+ volume1wk?: number;
106
+
107
+ /**
108
+ * Current available liquidity (in USDC)
109
+ */
110
+ liquidity: number;
111
+
112
+ /**
113
+ * Bid-ask spread (as decimal, e.g., 0.02 = 2%)
114
+ */
115
+ spread?: number;
116
+
117
+ /**
118
+ * 24-hour price change (as decimal, e.g., 0.05 = +5%)
119
+ */
120
+ oneDayPriceChange?: number;
121
+
122
+ /**
123
+ * 7-day price change (as decimal)
124
+ */
125
+ oneWeekPriceChange?: number;
126
+
127
+ /**
128
+ * Last traded price for the YES outcome
129
+ */
130
+ lastTradePrice?: number;
131
+
132
+ /**
133
+ * Best bid price for YES outcome
134
+ */
135
+ bestBid?: number;
136
+
137
+ /**
138
+ * Best ask price for YES outcome
139
+ */
140
+ bestAsk?: number;
141
+
142
+ /**
143
+ * Market end/resolution date
144
+ */
145
+ endDate: Date;
146
+
147
+ /**
148
+ * Whether the market is currently active
149
+ */
150
+ active: boolean;
151
+
152
+ /**
153
+ * Whether the market has been resolved
154
+ */
155
+ closed: boolean;
156
+
157
+ /**
158
+ * URL to market image
159
+ */
160
+ image?: string;
161
+
162
+ /**
163
+ * URL to market icon
164
+ */
165
+ icon?: string;
166
+
167
+ /**
168
+ * Category tags (e.g., ["crypto", "bitcoin", "finance"])
169
+ */
170
+ tags?: string[];
171
+ }
172
+
173
+ /**
174
+ * Event grouping from the Gamma API
175
+ *
176
+ * @remarks
177
+ * Events group related markets together. For example, a "2024 US Election"
178
+ * event might contain markets for each candidate and related predictions.
179
+ */
180
+ export interface GammaEvent {
181
+ /**
182
+ * Internal Gamma event ID
183
+ */
184
+ id: string;
185
+
186
+ /**
187
+ * URL-friendly event slug
188
+ */
189
+ slug: string;
190
+
191
+ /**
192
+ * Event title
193
+ * @example "2024 US Presidential Election"
194
+ */
195
+ title: string;
196
+
197
+ /**
198
+ * Event description
199
+ */
200
+ description?: string;
201
+
202
+ /**
203
+ * Markets belonging to this event
204
+ */
205
+ markets: GammaMarket[];
206
+
207
+ /**
208
+ * Event start date
209
+ */
210
+ startDate?: Date;
211
+
212
+ /**
213
+ * Event end date
214
+ */
215
+ endDate?: Date;
216
+
217
+ /**
218
+ * URL to event image
219
+ */
220
+ image?: string;
221
+ }
222
+
223
+ /**
224
+ * Parameters for searching/filtering markets
225
+ */
226
+ export interface MarketSearchParams {
227
+ /**
228
+ * Filter by market slug
229
+ */
230
+ slug?: string;
231
+
232
+ /**
233
+ * Filter by condition ID
234
+ */
235
+ conditionId?: string;
236
+
237
+ /**
238
+ * Filter by active status
239
+ */
240
+ active?: boolean;
241
+
242
+ /**
243
+ * Filter by closed status
244
+ */
245
+ closed?: boolean;
246
+
247
+ /**
248
+ * Maximum number of results (default: 100)
249
+ */
250
+ limit?: number;
251
+
252
+ /**
253
+ * Offset for pagination
254
+ */
255
+ offset?: number;
256
+
257
+ /**
258
+ * Sort field (e.g., "volume24hr", "liquidity", "endDate")
259
+ */
260
+ order?: string;
261
+
262
+ /**
263
+ * Sort direction (true = ascending, false = descending)
264
+ */
265
+ ascending?: boolean;
266
+ }
267
+
268
+ // ===== Client =====
269
+
270
+ /**
271
+ * Gamma API client for market discovery and metadata
272
+ *
273
+ * @remarks
274
+ * Use this client for:
275
+ * - Discovering trending markets
276
+ * - Searching for specific topics
277
+ * - Getting market metadata and statistics
278
+ * - Browsing events and market groupings
279
+ *
280
+ * For orderbook data and trading, use {@link ClobApiClient} and {@link TradingClient}.
281
+ *
282
+ * @example
283
+ * ```typescript
284
+ * const client = new GammaApiClient(rateLimiter, cache);
285
+ *
286
+ * // Find top volume markets
287
+ * const trending = await client.getTrendingMarkets(20);
288
+ * for (const market of trending) {
289
+ * console.log(market.question, '$' + market.volume24hr.toLocaleString());
290
+ * }
291
+ * ```
292
+ */
293
+ export class GammaApiClient {
294
+ /**
295
+ * Creates a new Gamma API client
296
+ *
297
+ * @param rateLimiter - Rate limiter instance for API throttling
298
+ * @param cache - Cache instance for storing data (supports both legacy Cache and CacheAdapter)
299
+ */
300
+ constructor(
301
+ private rateLimiter: RateLimiter,
302
+ private cache: UnifiedCache
303
+ ) {}
304
+
305
+ // ===== Market Queries =====
306
+
307
+ /**
308
+ * Get markets with optional filters and sorting
309
+ *
310
+ * @param params - Search and filter parameters
311
+ * @returns Array of markets matching the criteria
312
+ *
313
+ * @remarks
314
+ * Common sort fields:
315
+ * - `volume24hr` - 24-hour trading volume
316
+ * - `liquidity` - Available liquidity
317
+ * - `endDate` - Market end date
318
+ * - `volume` - Lifetime volume
319
+ *
320
+ * @example
321
+ * ```typescript
322
+ * // Get active markets sorted by 24h volume
323
+ * const markets = await client.getMarkets({
324
+ * active: true,
325
+ * closed: false,
326
+ * order: 'volume24hr',
327
+ * ascending: false,
328
+ * limit: 50,
329
+ * });
330
+ *
331
+ * // Search by slug
332
+ * const market = await client.getMarkets({
333
+ * slug: 'will-btc-reach-100k',
334
+ * limit: 1,
335
+ * });
336
+ * ```
337
+ */
338
+ async getMarkets(params?: MarketSearchParams): Promise<GammaMarket[]> {
339
+ const query = new URLSearchParams();
340
+ if (params?.slug) query.set('slug', params.slug);
341
+ if (params?.conditionId) query.set('condition_id', params.conditionId);
342
+ if (params?.active !== undefined) query.set('active', String(params.active));
343
+ if (params?.closed !== undefined) query.set('closed', String(params.closed));
344
+ if (params?.limit) query.set('limit', String(params.limit));
345
+ if (params?.offset) query.set('offset', String(params.offset));
346
+ if (params?.order) query.set('order', params.order);
347
+ if (params?.ascending !== undefined)
348
+ query.set('ascending', String(params.ascending));
349
+
350
+ return this.rateLimiter.execute(ApiType.GAMMA_API, async () => {
351
+ const response = await fetch(`${GAMMA_API_BASE}/markets?${query}`);
352
+ if (!response.ok)
353
+ throw PolymarketError.fromHttpError(
354
+ response.status,
355
+ await response.json().catch(() => null)
356
+ );
357
+ const data = (await response.json()) as unknown[];
358
+ if (!Array.isArray(data)) return [];
359
+ return data.map((item) => this.normalizeMarket(item as Record<string, unknown>));
360
+ });
361
+ }
362
+
363
+ /**
364
+ * Get a single market by its URL slug
365
+ *
366
+ * @param slug - The URL-friendly market slug
367
+ * @returns The market if found, null otherwise
368
+ *
369
+ * @example
370
+ * ```typescript
371
+ * const market = await client.getMarketBySlug('will-btc-reach-100k');
372
+ * if (market) {
373
+ * console.log(market.question);
374
+ * }
375
+ * ```
376
+ */
377
+ async getMarketBySlug(slug: string): Promise<GammaMarket | null> {
378
+ const markets = await this.getMarkets({ slug, limit: 1 });
379
+ return markets[0] || null;
380
+ }
381
+
382
+ /**
383
+ * Get a single market by condition ID
384
+ *
385
+ * @param conditionId - The unique condition identifier
386
+ * @returns The market if found, null otherwise
387
+ *
388
+ * @remarks
389
+ * For more reliable market data by condition ID, prefer {@link ClobApiClient.getMarket}.
390
+ *
391
+ * @example
392
+ * ```typescript
393
+ * const market = await client.getMarketByConditionId('0x82ace55...');
394
+ * ```
395
+ */
396
+ async getMarketByConditionId(conditionId: string): Promise<GammaMarket | null> {
397
+ const markets = await this.getMarkets({ conditionId, limit: 1 });
398
+ return markets[0] || null;
399
+ }
400
+
401
+ // ===== Event Queries =====
402
+
403
+ /**
404
+ * Get events with optional filters
405
+ *
406
+ * @param params - Filter parameters
407
+ * @param params.slug - Filter by event slug
408
+ * @param params.active - Filter by active status
409
+ * @param params.limit - Maximum results to return
410
+ * @returns Array of events matching the criteria
411
+ *
412
+ * @example
413
+ * ```typescript
414
+ * // Get all active events
415
+ * const events = await client.getEvents({ active: true, limit: 20 });
416
+ *
417
+ * // Get a specific event by slug
418
+ * const election = await client.getEvents({ slug: '2024-us-election' });
419
+ * ```
420
+ */
421
+ async getEvents(params?: {
422
+ slug?: string;
423
+ active?: boolean;
424
+ limit?: number;
425
+ }): Promise<GammaEvent[]> {
426
+ const query = new URLSearchParams();
427
+ if (params?.slug) query.set('slug', params.slug);
428
+ if (params?.active !== undefined) query.set('active', String(params.active));
429
+ if (params?.limit) query.set('limit', String(params.limit));
430
+
431
+ return this.rateLimiter.execute(ApiType.GAMMA_API, async () => {
432
+ const response = await fetch(`${GAMMA_API_BASE}/events?${query}`);
433
+ if (!response.ok)
434
+ throw PolymarketError.fromHttpError(
435
+ response.status,
436
+ await response.json().catch(() => null)
437
+ );
438
+ const data = (await response.json()) as unknown[];
439
+ if (!Array.isArray(data)) return [];
440
+ return data.map((item) => this.normalizeEvent(item as Record<string, unknown>));
441
+ });
442
+ }
443
+
444
+ /**
445
+ * Get a single event by its URL slug
446
+ *
447
+ * @param slug - The URL-friendly event slug
448
+ * @returns The event if found, null otherwise
449
+ *
450
+ * @example
451
+ * ```typescript
452
+ * const event = await client.getEventBySlug('2024-us-election');
453
+ * if (event) {
454
+ * console.log(`${event.title} has ${event.markets.length} markets`);
455
+ * }
456
+ * ```
457
+ */
458
+ async getEventBySlug(slug: string): Promise<GammaEvent | null> {
459
+ const events = await this.getEvents({ slug, limit: 1 });
460
+ return events[0] || null;
461
+ }
462
+
463
+ /**
464
+ * Get a single event by its ID
465
+ *
466
+ * @param id - The internal event ID
467
+ * @returns The event if found, null otherwise
468
+ *
469
+ * @example
470
+ * ```typescript
471
+ * const event = await client.getEventById('12345');
472
+ * ```
473
+ */
474
+ async getEventById(id: string): Promise<GammaEvent | null> {
475
+ return this.rateLimiter.execute(ApiType.GAMMA_API, async () => {
476
+ const response = await fetch(`${GAMMA_API_BASE}/events/${id}`);
477
+ if (!response.ok) {
478
+ if (response.status === 404) return null;
479
+ throw PolymarketError.fromHttpError(
480
+ response.status,
481
+ await response.json().catch(() => null)
482
+ );
483
+ }
484
+ const data = (await response.json()) as Record<string, unknown>;
485
+ return this.normalizeEvent(data);
486
+ });
487
+ }
488
+
489
+ // ===== Trending =====
490
+
491
+ /**
492
+ * Get trending markets sorted by 24-hour volume
493
+ *
494
+ * @param limit - Maximum number of markets to return (default: 20)
495
+ * @returns Array of active markets sorted by volume
496
+ *
497
+ * @remarks
498
+ * This is a convenience method equivalent to:
499
+ * ```typescript
500
+ * getMarkets({
501
+ * active: true,
502
+ * closed: false,
503
+ * order: 'volume24hr',
504
+ * ascending: false,
505
+ * limit,
506
+ * })
507
+ * ```
508
+ *
509
+ * @example
510
+ * ```typescript
511
+ * // Get top 10 trending markets
512
+ * const trending = await client.getTrendingMarkets(10);
513
+ *
514
+ * for (const market of trending) {
515
+ * console.log(`${market.question}`);
516
+ * console.log(` 24h Volume: $${market.volume24hr?.toLocaleString()}`);
517
+ * console.log(` YES Price: ${(market.outcomePrices[0] * 100).toFixed(1)}%`);
518
+ * }
519
+ * ```
520
+ */
521
+ async getTrendingMarkets(limit = 20): Promise<GammaMarket[]> {
522
+ return this.getMarkets({
523
+ active: true,
524
+ closed: false,
525
+ order: 'volume24hr',
526
+ ascending: false,
527
+ limit,
528
+ });
529
+ }
530
+
531
+ // ===== Data Normalization =====
532
+
533
+ private normalizeMarket(m: Record<string, unknown>): GammaMarket {
534
+ return {
535
+ id: String(m.id || ''),
536
+ conditionId: String(m.conditionId || ''),
537
+ slug: String(m.slug || ''),
538
+ question: String(m.question || ''),
539
+ description: m.description ? String(m.description) : undefined,
540
+ outcomes: this.parseJsonArray(m.outcomes, ['Yes', 'No']),
541
+ outcomePrices: this.parseJsonArray(m.outcomePrices, [0.5, 0.5]).map(
542
+ Number
543
+ ),
544
+ volume: Number(m.volume || 0),
545
+ volume24hr: m.volume24hr !== undefined ? Number(m.volume24hr) : undefined,
546
+ volume1wk: m.volume1wk !== undefined ? Number(m.volume1wk) : undefined,
547
+ liquidity: Number(m.liquidity || 0),
548
+ spread: m.spread !== undefined ? Number(m.spread) : undefined,
549
+ oneDayPriceChange:
550
+ m.oneDayPriceChange !== undefined
551
+ ? Number(m.oneDayPriceChange)
552
+ : undefined,
553
+ oneWeekPriceChange:
554
+ m.oneWeekPriceChange !== undefined
555
+ ? Number(m.oneWeekPriceChange)
556
+ : undefined,
557
+ lastTradePrice:
558
+ m.lastTradePrice !== undefined ? Number(m.lastTradePrice) : undefined,
559
+ bestBid: m.bestBid !== undefined ? Number(m.bestBid) : undefined,
560
+ bestAsk: m.bestAsk !== undefined ? Number(m.bestAsk) : undefined,
561
+ endDate: new Date(String(m.endDate || Date.now())),
562
+ active: Boolean(m.active),
563
+ closed: Boolean(m.closed),
564
+ image: m.image ? String(m.image) : undefined,
565
+ icon: m.icon ? String(m.icon) : undefined,
566
+ tags: m.tags ? this.parseJsonArray(m.tags, []) : undefined,
567
+ };
568
+ }
569
+
570
+ private normalizeEvent(e: Record<string, unknown>): GammaEvent {
571
+ const markets = e.markets;
572
+ return {
573
+ id: String(e.id || ''),
574
+ slug: String(e.slug || ''),
575
+ title: String(e.title || ''),
576
+ description: e.description ? String(e.description) : undefined,
577
+ markets: Array.isArray(markets)
578
+ ? markets.map((m: Record<string, unknown>) => this.normalizeMarket(m))
579
+ : [],
580
+ startDate: e.startDate ? new Date(String(e.startDate)) : undefined,
581
+ endDate: e.endDate ? new Date(String(e.endDate)) : undefined,
582
+ image: e.image ? String(e.image) : undefined,
583
+ };
584
+ }
585
+
586
+ private parseJsonArray<T>(value: unknown, fallback: T[]): T[] {
587
+ if (Array.isArray(value)) return value as T[];
588
+ if (typeof value === 'string') {
589
+ try {
590
+ return JSON.parse(value);
591
+ } catch {
592
+ return fallback;
593
+ }
594
+ }
595
+ return fallback;
596
+ }
597
+ }