@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,469 @@
1
+ /**
2
+ * Data API Client for Polymarket
3
+ * Handles: positions, activity, trades, leaderboard
4
+ */
5
+
6
+ import { RateLimiter, ApiType } from '../core/rate-limiter.js';
7
+ import type { UnifiedCache } from '../core/unified-cache.js';
8
+ import { CACHE_TTL } from '../core/unified-cache.js';
9
+ import { PolymarketError } from '../core/errors.js';
10
+
11
+ const DATA_API_BASE = 'https://data-api.polymarket.com';
12
+
13
+ // ===== Types =====
14
+
15
+ export interface Position {
16
+ // Wallet identifier
17
+ proxyWallet?: string;
18
+
19
+ // Core identifiers
20
+ asset: string; // ERC-1155 Token ID
21
+ conditionId: string;
22
+ outcome: string;
23
+ outcomeIndex: number;
24
+
25
+ // Position data
26
+ size: number;
27
+ avgPrice: number;
28
+ curPrice?: number;
29
+ totalBought?: number;
30
+
31
+ // Value calculations
32
+ initialValue?: number;
33
+ currentValue?: number;
34
+ cashPnl?: number; // Unrealized PnL
35
+ percentPnl?: number;
36
+ realizedPnl?: number;
37
+ percentRealizedPnl?: number;
38
+
39
+ // Market metadata (from API)
40
+ title: string;
41
+ slug?: string;
42
+ icon?: string;
43
+ eventId?: string;
44
+ eventSlug?: string;
45
+
46
+ // Opposite side info (for binary markets)
47
+ oppositeOutcome?: string;
48
+ oppositeAsset?: string;
49
+
50
+ // Status fields (from API)
51
+ redeemable?: boolean;
52
+ mergeable?: boolean;
53
+ endDate?: string;
54
+ negativeRisk?: boolean;
55
+ }
56
+
57
+ export interface Activity {
58
+ // Transaction type
59
+ type: 'TRADE' | 'SPLIT' | 'MERGE' | 'REDEEM' | 'CONVERSION';
60
+ side: 'BUY' | 'SELL';
61
+
62
+ // Trade data
63
+ size: number;
64
+ price: number;
65
+ usdcSize?: number;
66
+
67
+ // Market identifiers
68
+ asset: string;
69
+ conditionId: string;
70
+ outcome: string;
71
+ outcomeIndex?: number;
72
+
73
+ // Transaction info
74
+ timestamp: number;
75
+ transactionHash: string;
76
+
77
+ // Market metadata (from API)
78
+ title?: string;
79
+ slug?: string;
80
+
81
+ // Trader info (from API - returned as "name")
82
+ name?: string;
83
+ }
84
+
85
+ export interface Trade {
86
+ // Identifiers (id is optional - not always returned by API)
87
+ id?: string;
88
+ market: string; // conditionId (may come as "conditionId" from API)
89
+ asset: string;
90
+
91
+ // Trade data
92
+ side: 'BUY' | 'SELL';
93
+ price: number;
94
+ size: number;
95
+ outcome: string;
96
+ outcomeIndex: number;
97
+
98
+ // Transaction info
99
+ timestamp: number;
100
+ transactionHash: string;
101
+ proxyWallet?: string;
102
+
103
+ // Market metadata (from API)
104
+ title?: string;
105
+ slug?: string;
106
+ icon?: string;
107
+ eventSlug?: string;
108
+
109
+ // Trader info (from API)
110
+ name?: string;
111
+ pseudonym?: string;
112
+ bio?: string;
113
+ profileImage?: string;
114
+ profileImageOptimized?: string;
115
+ }
116
+
117
+ export interface LeaderboardEntry {
118
+ // Wallet identifier (normalized from proxyWallet)
119
+ address: string;
120
+
121
+ // Ranking data
122
+ rank: number;
123
+ pnl: number;
124
+ volume: number;
125
+
126
+ // User profile (optional - may not exist)
127
+ userName?: string;
128
+ xUsername?: string;
129
+ verifiedBadge?: boolean;
130
+ profileImage?: string;
131
+
132
+ // Activity counts (optional - API often returns null)
133
+ positions?: number;
134
+ trades?: number;
135
+ }
136
+
137
+ export interface LeaderboardPage {
138
+ entries: LeaderboardEntry[];
139
+ total: number;
140
+ offset: number;
141
+ limit: number;
142
+ }
143
+
144
+ // ===== Client =====
145
+
146
+ export class DataApiClient {
147
+ constructor(
148
+ private rateLimiter: RateLimiter,
149
+ private cache: UnifiedCache
150
+ ) {}
151
+
152
+ // ===== Wallet-related =====
153
+
154
+ /**
155
+ * Get positions for a wallet address
156
+ */
157
+ async getPositions(address: string): Promise<Position[]> {
158
+ return this.rateLimiter.execute(ApiType.DATA_API, async () => {
159
+ const response = await fetch(
160
+ `${DATA_API_BASE}/positions?user=${address}`
161
+ );
162
+ if (!response.ok)
163
+ throw PolymarketError.fromHttpError(
164
+ response.status,
165
+ await response.json().catch(() => null)
166
+ );
167
+ const data = (await response.json()) as unknown[];
168
+ return this.normalizePositions(data);
169
+ });
170
+ }
171
+
172
+ /**
173
+ * Get activity for a wallet address
174
+ */
175
+ async getActivity(
176
+ address: string,
177
+ params?: { limit?: number; type?: string }
178
+ ): Promise<Activity[]> {
179
+ const query = new URLSearchParams({
180
+ user: address,
181
+ limit: String(params?.limit || 100),
182
+ ...(params?.type && { type: params.type }),
183
+ });
184
+
185
+ return this.rateLimiter.execute(ApiType.DATA_API, async () => {
186
+ const response = await fetch(`${DATA_API_BASE}/activity?${query}`);
187
+ if (!response.ok)
188
+ throw PolymarketError.fromHttpError(
189
+ response.status,
190
+ await response.json().catch(() => null)
191
+ );
192
+ const data = (await response.json()) as unknown[];
193
+ return this.normalizeActivities(data);
194
+ });
195
+ }
196
+
197
+ // ===== Trade-related =====
198
+
199
+ /**
200
+ * Get recent trades
201
+ */
202
+ async getTrades(params?: {
203
+ limit?: number;
204
+ market?: string;
205
+ }): Promise<Trade[]> {
206
+ const query = new URLSearchParams({
207
+ limit: String(params?.limit || 1000),
208
+ ...(params?.market && { market: params.market }),
209
+ });
210
+
211
+ return this.rateLimiter.execute(ApiType.DATA_API, async () => {
212
+ const response = await fetch(`${DATA_API_BASE}/trades?${query}`);
213
+ if (!response.ok)
214
+ throw PolymarketError.fromHttpError(
215
+ response.status,
216
+ await response.json().catch(() => null)
217
+ );
218
+ const data = (await response.json()) as unknown[];
219
+ return this.normalizeTrades(data);
220
+ });
221
+ }
222
+
223
+ /**
224
+ * Get trades for a specific market
225
+ */
226
+ async getTradesByMarket(conditionId: string, limit = 500): Promise<Trade[]> {
227
+ return this.getTrades({ market: conditionId, limit });
228
+ }
229
+
230
+ // ===== Leaderboard =====
231
+
232
+ /**
233
+ * Get leaderboard page
234
+ */
235
+ async getLeaderboard(params?: {
236
+ limit?: number;
237
+ offset?: number;
238
+ }): Promise<LeaderboardPage> {
239
+ const limit = params?.limit || 50;
240
+ const offset = params?.offset || 0;
241
+ const cacheKey = `leaderboard:${offset}:${limit}`;
242
+
243
+ return this.cache.getOrSet(cacheKey, CACHE_TTL.LEADERBOARD, async () => {
244
+ const query = new URLSearchParams({
245
+ limit: String(limit),
246
+ offset: String(offset),
247
+ });
248
+
249
+ return this.rateLimiter.execute(ApiType.DATA_API, async () => {
250
+ const response = await fetch(
251
+ `${DATA_API_BASE}/v1/leaderboard?${query}`
252
+ );
253
+ if (!response.ok)
254
+ throw PolymarketError.fromHttpError(
255
+ response.status,
256
+ await response.json().catch(() => null)
257
+ );
258
+
259
+ const data = (await response.json()) as unknown[];
260
+ const entries = this.normalizeLeaderboardEntries(data);
261
+
262
+ return {
263
+ entries,
264
+ total: entries.length + offset, // Approximate - API doesn't provide total
265
+ offset,
266
+ limit,
267
+ };
268
+ });
269
+ });
270
+ }
271
+
272
+ /**
273
+ * Get all leaderboard entries up to a max count
274
+ */
275
+ async getAllLeaderboard(maxEntries = 500): Promise<LeaderboardEntry[]> {
276
+ const all: LeaderboardEntry[] = [];
277
+ let offset = 0;
278
+ const limit = 50;
279
+
280
+ while (all.length < maxEntries) {
281
+ const page = await this.getLeaderboard({ limit, offset });
282
+ all.push(...page.entries);
283
+ if (page.entries.length < limit) break;
284
+ offset += limit;
285
+ }
286
+
287
+ return all.slice(0, maxEntries);
288
+ }
289
+
290
+ // ===== Data Normalization =====
291
+
292
+ private normalizePositions(data: unknown[]): Position[] {
293
+ if (!Array.isArray(data)) return [];
294
+ return data.map((item) => {
295
+ const p = item as Record<string, unknown>;
296
+ return {
297
+ // Wallet identifier
298
+ proxyWallet: p.proxyWallet !== undefined ? String(p.proxyWallet) : undefined,
299
+
300
+ // Core identifiers
301
+ asset: String(p.asset || ''),
302
+ conditionId: String(p.conditionId || ''),
303
+ outcome: String(p.outcome || ''),
304
+ outcomeIndex:
305
+ typeof p.outcomeIndex === 'number'
306
+ ? p.outcomeIndex
307
+ : p.outcome === 'Yes'
308
+ ? 0
309
+ : 1,
310
+
311
+ // Position data
312
+ size: Number(p.size),
313
+ avgPrice: Number(p.avgPrice),
314
+ curPrice: p.curPrice !== undefined ? Number(p.curPrice) : undefined,
315
+ totalBought: p.totalBought !== undefined ? Number(p.totalBought) : undefined,
316
+
317
+ // Value calculations
318
+ initialValue:
319
+ p.initialValue !== undefined ? Number(p.initialValue) : undefined,
320
+ currentValue:
321
+ p.currentValue !== undefined ? Number(p.currentValue) : undefined,
322
+ cashPnl: p.cashPnl !== undefined ? Number(p.cashPnl) : undefined,
323
+ percentPnl:
324
+ p.percentPnl !== undefined ? Number(p.percentPnl) : undefined,
325
+ realizedPnl:
326
+ p.realizedPnl !== undefined ? Number(p.realizedPnl) : undefined,
327
+ percentRealizedPnl:
328
+ p.percentRealizedPnl !== undefined ? Number(p.percentRealizedPnl) : undefined,
329
+
330
+ // Market metadata
331
+ title: String(p.title || ''),
332
+ slug: p.slug !== undefined ? String(p.slug) : undefined,
333
+ icon: p.icon !== undefined ? String(p.icon) : undefined,
334
+ eventId: p.eventId !== undefined ? String(p.eventId) : undefined,
335
+ eventSlug: p.eventSlug !== undefined ? String(p.eventSlug) : undefined,
336
+
337
+ // Opposite side info
338
+ oppositeOutcome: p.oppositeOutcome !== undefined ? String(p.oppositeOutcome) : undefined,
339
+ oppositeAsset: p.oppositeAsset !== undefined ? String(p.oppositeAsset) : undefined,
340
+
341
+ // Status fields
342
+ redeemable: p.redeemable !== undefined ? Boolean(p.redeemable) : undefined,
343
+ mergeable: p.mergeable !== undefined ? Boolean(p.mergeable) : undefined,
344
+ endDate: p.endDate !== undefined ? String(p.endDate) : undefined,
345
+ negativeRisk: p.negativeRisk !== undefined ? Boolean(p.negativeRisk) : undefined,
346
+ };
347
+ });
348
+ }
349
+
350
+ private normalizeActivities(data: unknown[]): Activity[] {
351
+ if (!Array.isArray(data)) return [];
352
+ return data.map((item) => {
353
+ const a = item as Record<string, unknown>;
354
+ return {
355
+ // Transaction type
356
+ type: String(a.type) as Activity['type'],
357
+ side: String(a.side) as Activity['side'],
358
+
359
+ // Trade data
360
+ size: Number(a.size),
361
+ price: Number(a.price),
362
+ usdcSize:
363
+ a.usdcSize !== undefined
364
+ ? Number(a.usdcSize)
365
+ : Number(a.size) * Number(a.price),
366
+
367
+ // Market identifiers
368
+ asset: String(a.asset || ''),
369
+ conditionId: String(a.conditionId || ''),
370
+ outcome: String(a.outcome || ''),
371
+ outcomeIndex:
372
+ a.outcomeIndex !== undefined ? Number(a.outcomeIndex) : undefined,
373
+
374
+ // Transaction info
375
+ timestamp: this.normalizeTimestamp(a.timestamp),
376
+ transactionHash: String(a.transactionHash || ''),
377
+
378
+ // Market metadata
379
+ title: a.title !== undefined ? String(a.title) : undefined,
380
+ slug: a.slug !== undefined ? String(a.slug) : undefined,
381
+
382
+ // Trader info
383
+ name: a.name !== undefined ? String(a.name) : undefined,
384
+ };
385
+ });
386
+ }
387
+
388
+ private normalizeTrades(data: unknown[]): Trade[] {
389
+ if (!Array.isArray(data)) return [];
390
+ return data.map((item) => {
391
+ const t = item as Record<string, unknown>;
392
+ return {
393
+ // Identifiers
394
+ id: t.id !== undefined ? String(t.id) : undefined,
395
+ market: String(t.market || t.conditionId || ''),
396
+ asset: String(t.asset || ''),
397
+
398
+ // Trade data
399
+ side: String(t.side) as Trade['side'],
400
+ price: Number(t.price),
401
+ size: Number(t.size),
402
+ outcome: String(t.outcome || ''),
403
+ outcomeIndex:
404
+ typeof t.outcomeIndex === 'number'
405
+ ? t.outcomeIndex
406
+ : t.outcome === 'Yes'
407
+ ? 0
408
+ : 1,
409
+
410
+ // Transaction info
411
+ timestamp: this.normalizeTimestamp(t.timestamp),
412
+ transactionHash: String(t.transactionHash || ''),
413
+ proxyWallet:
414
+ t.proxyWallet !== undefined ? String(t.proxyWallet) : undefined,
415
+
416
+ // Market metadata
417
+ title: t.title !== undefined ? String(t.title) : undefined,
418
+ slug: t.slug !== undefined ? String(t.slug) : undefined,
419
+ icon: t.icon !== undefined ? String(t.icon) : undefined,
420
+ eventSlug: t.eventSlug !== undefined ? String(t.eventSlug) : undefined,
421
+
422
+ // Trader info
423
+ name: t.name !== undefined ? String(t.name) : undefined,
424
+ pseudonym: t.pseudonym !== undefined ? String(t.pseudonym) : undefined,
425
+ bio: t.bio !== undefined ? String(t.bio) : undefined,
426
+ profileImage: t.profileImage !== undefined ? String(t.profileImage) : undefined,
427
+ profileImageOptimized: t.profileImageOptimized !== undefined ? String(t.profileImageOptimized) : undefined,
428
+ };
429
+ });
430
+ }
431
+
432
+ private normalizeTimestamp(ts: unknown): number {
433
+ if (typeof ts === 'number') {
434
+ // If timestamp is in seconds, convert to milliseconds
435
+ return ts < 1e12 ? ts * 1000 : ts;
436
+ }
437
+ if (typeof ts === 'string') {
438
+ const num = parseInt(ts, 10);
439
+ return num < 1e12 ? num * 1000 : num;
440
+ }
441
+ return Date.now();
442
+ }
443
+
444
+ private normalizeLeaderboardEntries(data: unknown[]): LeaderboardEntry[] {
445
+ if (!Array.isArray(data)) return [];
446
+ return data.map((item) => {
447
+ const e = item as Record<string, unknown>;
448
+ return {
449
+ // Wallet identifier
450
+ address: String(e.proxyWallet || e.address || ''),
451
+
452
+ // Ranking data
453
+ rank: typeof e.rank === 'number' ? e.rank : parseInt(String(e.rank), 10) || 0,
454
+ pnl: Number(e.pnl) || 0,
455
+ volume: Number(e.vol || e.volume) || 0,
456
+
457
+ // User profile
458
+ userName: e.userName !== undefined ? String(e.userName) : undefined,
459
+ xUsername: e.xUsername !== undefined ? String(e.xUsername) : undefined,
460
+ verifiedBadge: Boolean(e.verifiedBadge),
461
+ profileImage: e.profileImage !== undefined ? String(e.profileImage) : undefined,
462
+
463
+ // Activity counts (optional - API often returns null)
464
+ positions: e.positions != null ? Number(e.positions) : undefined,
465
+ trades: e.trades != null ? Number(e.trades) : undefined,
466
+ };
467
+ });
468
+ }
469
+ }