@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
package/src/index.ts DELETED
@@ -1,461 +0,0 @@
1
- /**
2
- * @catalyst-team/poly-sdk
3
- *
4
- * Unified SDK for Polymarket APIs
5
- * - Data API (positions, activity, trades, leaderboard)
6
- * - Gamma API (markets, events, trending)
7
- * - CLOB API (orderbook, market info, trading)
8
- * - Services (WalletService, MarketService)
9
- */
10
-
11
- // Core infrastructure
12
- export { RateLimiter, ApiType } from './core/rate-limiter.js';
13
- export { Cache, CACHE_TTL } from './core/cache.js';
14
- export { PolymarketError, ErrorCode, withRetry } from './core/errors.js';
15
- export * from './core/types.js';
16
-
17
- // Cache integration (new)
18
- export type { UnifiedCache } from './core/unified-cache.js';
19
- export { createUnifiedCache } from './core/unified-cache.js';
20
-
21
- // API Clients
22
- export { DataApiClient } from './clients/data-api.js';
23
- export type {
24
- Position,
25
- Activity,
26
- Trade,
27
- LeaderboardEntry,
28
- LeaderboardPage,
29
- } from './clients/data-api.js';
30
-
31
- export { GammaApiClient } from './clients/gamma-api.js';
32
- export type {
33
- GammaMarket,
34
- GammaEvent,
35
- MarketSearchParams,
36
- } from './clients/gamma-api.js';
37
-
38
- export { ClobApiClient } from './clients/clob-api.js';
39
- export type {
40
- ClobMarket,
41
- ClobToken,
42
- Orderbook,
43
- OrderbookLevel,
44
- } from './clients/clob-api.js';
45
-
46
- // Services
47
- export { WalletService } from './services/wallet-service.js';
48
- export type {
49
- WalletProfile,
50
- WalletActivitySummary,
51
- SellActivityResult,
52
- } from './services/wallet-service.js';
53
-
54
- export { MarketService, getIntervalMs as getIntervalMsService } from './services/market-service.js';
55
-
56
- // Real-time
57
- export { WebSocketManager } from './clients/websocket-manager.js';
58
- export type { WebSocketManagerConfig, WebSocketManagerEvents } from './clients/websocket-manager.js';
59
-
60
- export { RealtimeService } from './services/realtime-service.js';
61
- export type { Subscription, MarketSubscriptionHandlers } from './services/realtime-service.js';
62
-
63
- // ArbitrageService (Real-time arbitrage detection, execution, rebalancing, and settlement)
64
- export { ArbitrageService } from './services/arbitrage-service.js';
65
- export type {
66
- ArbitrageMarketConfig,
67
- ArbitrageServiceConfig,
68
- ArbitrageOpportunity as ArbitrageServiceOpportunity,
69
- ArbitrageExecutionResult,
70
- ArbitrageServiceEvents,
71
- OrderbookState,
72
- BalanceState,
73
- // Rebalancer types
74
- RebalanceAction,
75
- RebalanceResult,
76
- // Settle types
77
- SettleResult,
78
- // Clear position types (smart settle)
79
- ClearPositionResult,
80
- ClearAction,
81
- // Scanning types
82
- ScanCriteria,
83
- ScanResult,
84
- } from './services/arbitrage-service.js';
85
-
86
- // Trading
87
- export { TradingClient, POLYGON_MAINNET, POLYGON_AMOY } from './clients/trading-client.js';
88
- export type {
89
- Side,
90
- OrderType,
91
- ApiCredentials,
92
- OrderParams,
93
- MarketOrderParams,
94
- Order,
95
- OrderResult,
96
- TradeInfo,
97
- TradingClientConfig,
98
- // Rewards types
99
- UserEarning,
100
- MarketReward,
101
- OrderScoring,
102
- } from './clients/trading-client.js';
103
-
104
- // CTF (Conditional Token Framework)
105
- // NOTE: USDC_CONTRACT is USDC.e (bridged), required for Polymarket CTF
106
- // NATIVE_USDC_CONTRACT is native USDC, NOT compatible with CTF
107
- export {
108
- CTFClient,
109
- CTF_CONTRACT,
110
- USDC_CONTRACT, // USDC.e (0x2791...) - Required for CTF
111
- NATIVE_USDC_CONTRACT, // Native USDC (0x3c49...) - NOT for CTF
112
- NEG_RISK_CTF_EXCHANGE,
113
- NEG_RISK_ADAPTER,
114
- USDC_DECIMALS,
115
- calculateConditionId,
116
- parseUsdc,
117
- formatUsdc,
118
- } from './clients/ctf-client.js';
119
- export type {
120
- CTFConfig,
121
- SplitResult,
122
- MergeResult,
123
- RedeemResult,
124
- PositionBalance,
125
- MarketResolution,
126
- GasEstimate,
127
- TransactionStatus,
128
- TokenIds,
129
- } from './clients/ctf-client.js';
130
- export { RevertReason } from './clients/ctf-client.js';
131
-
132
- // Bridge (Cross-chain Deposits)
133
- export {
134
- BridgeClient,
135
- SUPPORTED_CHAINS,
136
- BRIDGE_TOKENS,
137
- estimateBridgeOutput,
138
- getExplorerUrl,
139
- depositUsdc,
140
- swapAndDeposit,
141
- getSupportedDepositTokens,
142
- } from './clients/bridge-client.js';
143
- export type {
144
- BridgeSupportedAsset,
145
- DepositAddress,
146
- CreateDepositResponse,
147
- DepositStatus,
148
- BridgeConfig,
149
- DepositResult,
150
- DepositOptions,
151
- SwapAndDepositOptions,
152
- SwapAndDepositResult,
153
- } from './clients/bridge-client.js';
154
-
155
- // Swap Service (DEX swaps on Polygon)
156
- export {
157
- SwapService,
158
- QUICKSWAP_ROUTER,
159
- POLYGON_TOKENS,
160
- TOKEN_DECIMALS,
161
- } from './services/swap-service.js';
162
- export type {
163
- SupportedToken,
164
- SwapQuote,
165
- SwapResult,
166
- TokenBalance,
167
- TransferResult,
168
- } from './services/swap-service.js';
169
-
170
- // Authorization (ERC20/ERC1155 Approvals)
171
- export { AuthorizationService } from './services/authorization-service.js';
172
- export type {
173
- AllowanceInfo,
174
- AllowancesResult,
175
- ApprovalTxResult,
176
- ApprovalsResult,
177
- AuthorizationServiceConfig,
178
- } from './services/authorization-service.js';
179
-
180
- // Price Utilities
181
- export {
182
- roundPrice,
183
- roundSize,
184
- validatePrice,
185
- validateSize,
186
- calculateBuyAmount,
187
- calculateSellPayout,
188
- calculateSharesForAmount,
189
- calculateSpread,
190
- calculateMidpoint,
191
- formatPrice,
192
- formatUSDC,
193
- calculatePnL,
194
- checkArbitrage,
195
- getEffectivePrices,
196
- ROUNDING_CONFIG,
197
- } from './utils/price-utils.js';
198
- export type { TickSize } from './utils/price-utils.js';
199
-
200
- // NOTE: MCP tools have been moved to @catalyst-team/poly-mcp package
201
- // See packages/poly-mcp/
202
-
203
- // ===== Main SDK Class =====
204
-
205
- import { RateLimiter } from './core/rate-limiter.js';
206
- import { DataApiClient } from './clients/data-api.js';
207
- import { GammaApiClient } from './clients/gamma-api.js';
208
- import { ClobApiClient } from './clients/clob-api.js';
209
- import { WalletService } from './services/wallet-service.js';
210
- import { MarketService } from './services/market-service.js';
211
- import type { UnifiedMarket, ProcessedOrderbook, ArbitrageOpportunity, KLineInterval, KLineCandle, DualKLineData, PolySDKOptions } from './core/types.js';
212
- import { PolymarketError, ErrorCode } from './core/errors.js';
213
- import { createUnifiedCache, type UnifiedCache } from './core/unified-cache.js';
214
-
215
- // Re-export for backward compatibility
216
- export interface PolymarketSDKConfig extends PolySDKOptions {}
217
-
218
- export class PolymarketSDK {
219
- // Infrastructure
220
- private rateLimiter: RateLimiter;
221
- private cache: UnifiedCache;
222
-
223
- // API Clients
224
- public readonly dataApi: DataApiClient;
225
- public readonly gammaApi: GammaApiClient;
226
- public readonly clobApi: ClobApiClient;
227
-
228
- // Services
229
- public readonly wallets: WalletService;
230
- public readonly markets: MarketService;
231
-
232
- constructor(config: PolymarketSDKConfig = {}) {
233
- // Initialize infrastructure
234
- this.rateLimiter = new RateLimiter();
235
-
236
- // Create unified cache (supports both legacy Cache and CacheAdapter)
237
- this.cache = createUnifiedCache(config.cache);
238
-
239
- // Initialize API clients
240
- this.dataApi = new DataApiClient(this.rateLimiter, this.cache);
241
- this.gammaApi = new GammaApiClient(this.rateLimiter, this.cache);
242
- this.clobApi = new ClobApiClient(this.rateLimiter, this.cache, {
243
- chainId: config.chainId,
244
- signer: config.signer,
245
- creds: config.creds,
246
- });
247
-
248
- // Initialize services
249
- this.wallets = new WalletService(this.dataApi, this.cache);
250
- this.markets = new MarketService(this.gammaApi, this.clobApi, this.dataApi, this.cache);
251
- }
252
-
253
- // ===== Unified Market Access =====
254
-
255
- /**
256
- * Get market by slug or condition ID
257
- * Uses Gamma for slug, CLOB for conditionId
258
- */
259
- async getMarket(identifier: string): Promise<UnifiedMarket> {
260
- const isConditionId =
261
- identifier.startsWith('0x') || /^\d+$/.test(identifier);
262
-
263
- if (isConditionId) {
264
- return this.getMarketByConditionId(identifier);
265
- } else {
266
- return this.getMarketBySlug(identifier);
267
- }
268
- }
269
-
270
- private async getMarketBySlug(slug: string): Promise<UnifiedMarket> {
271
- // Gamma as primary source for slug
272
- const gammaMarket = await this.gammaApi.getMarketBySlug(slug);
273
- if (!gammaMarket) {
274
- throw new PolymarketError(
275
- ErrorCode.MARKET_NOT_FOUND,
276
- `Market not found: ${slug}`
277
- );
278
- }
279
-
280
- // Enrich with CLOB data
281
- try {
282
- const clobMarket = await this.clobApi.getMarket(gammaMarket.conditionId);
283
- return this.mergeMarkets(gammaMarket, clobMarket);
284
- } catch {
285
- return this.fromGammaMarket(gammaMarket);
286
- }
287
- }
288
-
289
- private async getMarketByConditionId(
290
- conditionId: string
291
- ): Promise<UnifiedMarket> {
292
- // CLOB as primary source for conditionId (more reliable)
293
- try {
294
- const clobMarket = await this.clobApi.getMarket(conditionId);
295
-
296
- // Try to enrich with Gamma data
297
- try {
298
- const gammaMarket =
299
- await this.gammaApi.getMarketByConditionId(conditionId);
300
- if (gammaMarket) {
301
- return this.mergeMarkets(gammaMarket, clobMarket);
302
- }
303
- } catch {
304
- // Gamma enrichment failed, use CLOB only
305
- }
306
-
307
- return this.fromClobMarket(clobMarket);
308
- } catch {
309
- throw new PolymarketError(
310
- ErrorCode.MARKET_NOT_FOUND,
311
- `Market not found: ${conditionId}`
312
- );
313
- }
314
- }
315
-
316
- // ===== Orderbook Analysis =====
317
-
318
- /**
319
- * Get processed orderbook with analytics
320
- */
321
- async getOrderbook(conditionId: string): Promise<ProcessedOrderbook> {
322
- return this.clobApi.getProcessedOrderbook(conditionId);
323
- }
324
-
325
- /**
326
- * Detect arbitrage opportunity
327
- *
328
- * 使用有效价格计算套利机会(正确考虑镜像订单)
329
- * 详细文档见: docs/01-polymarket-orderbook-arbitrage.md
330
- */
331
- async detectArbitrage(
332
- conditionId: string,
333
- threshold = 0.005
334
- ): Promise<ArbitrageOpportunity | null> {
335
- const orderbook = await this.getOrderbook(conditionId);
336
- const { effectivePrices, longArbProfit, shortArbProfit } = orderbook.summary;
337
-
338
- if (longArbProfit > threshold) {
339
- return {
340
- type: 'long',
341
- profit: longArbProfit,
342
- action: `Buy YES @ ${effectivePrices.effectiveBuyYes.toFixed(4)} + Buy NO @ ${effectivePrices.effectiveBuyNo.toFixed(4)}, merge for 1 USDC`,
343
- expectedProfit: longArbProfit,
344
- };
345
- }
346
-
347
- if (shortArbProfit > threshold) {
348
- return {
349
- type: 'short',
350
- profit: shortArbProfit,
351
- action: `Split 1 USDC, Sell YES @ ${effectivePrices.effectiveSellYes.toFixed(4)} + Sell NO @ ${effectivePrices.effectiveSellNo.toFixed(4)}`,
352
- expectedProfit: shortArbProfit,
353
- };
354
- }
355
-
356
- return null;
357
- }
358
-
359
- // ===== Helper Methods =====
360
-
361
- private mergeMarkets(
362
- gamma: import('./clients/gamma-api.js').GammaMarket,
363
- clob: import('./clients/clob-api.js').ClobMarket
364
- ): UnifiedMarket {
365
- const yesToken = clob.tokens.find((t) => t.outcome === 'Yes');
366
- const noToken = clob.tokens.find((t) => t.outcome === 'No');
367
-
368
- return {
369
- conditionId: clob.conditionId,
370
- slug: gamma.slug,
371
- question: clob.question,
372
- description: clob.description || gamma.description,
373
- tokens: {
374
- yes: {
375
- tokenId: yesToken?.tokenId || '',
376
- price: yesToken?.price || gamma.outcomePrices[0] || 0.5,
377
- },
378
- no: {
379
- tokenId: noToken?.tokenId || '',
380
- price: noToken?.price || gamma.outcomePrices[1] || 0.5,
381
- },
382
- },
383
- volume: gamma.volume,
384
- volume24hr: gamma.volume24hr,
385
- liquidity: gamma.liquidity,
386
- spread: gamma.spread,
387
- active: clob.active,
388
- closed: clob.closed,
389
- acceptingOrders: clob.acceptingOrders,
390
- endDate: clob.endDateIso ? new Date(clob.endDateIso) : new Date(),
391
- source: 'merged',
392
- };
393
- }
394
-
395
- private fromGammaMarket(
396
- gamma: import('./clients/gamma-api.js').GammaMarket
397
- ): UnifiedMarket {
398
- return {
399
- conditionId: gamma.conditionId,
400
- slug: gamma.slug,
401
- question: gamma.question,
402
- description: gamma.description,
403
- tokens: {
404
- yes: { tokenId: '', price: gamma.outcomePrices[0] || 0.5 },
405
- no: { tokenId: '', price: gamma.outcomePrices[1] || 0.5 },
406
- },
407
- volume: gamma.volume,
408
- volume24hr: gamma.volume24hr,
409
- liquidity: gamma.liquidity,
410
- spread: gamma.spread,
411
- active: gamma.active,
412
- closed: gamma.closed,
413
- acceptingOrders: !gamma.closed,
414
- endDate: gamma.endDate,
415
- source: 'gamma',
416
- };
417
- }
418
-
419
- private fromClobMarket(
420
- clob: import('./clients/clob-api.js').ClobMarket
421
- ): UnifiedMarket {
422
- const yesToken = clob.tokens.find((t) => t.outcome === 'Yes');
423
- const noToken = clob.tokens.find((t) => t.outcome === 'No');
424
-
425
- return {
426
- conditionId: clob.conditionId,
427
- slug: clob.marketSlug,
428
- question: clob.question,
429
- description: clob.description,
430
- tokens: {
431
- yes: { tokenId: yesToken?.tokenId || '', price: yesToken?.price || 0.5 },
432
- no: { tokenId: noToken?.tokenId || '', price: noToken?.price || 0.5 },
433
- },
434
- volume: 0, // CLOB doesn't have volume
435
- volume24hr: undefined,
436
- liquidity: 0,
437
- spread: undefined,
438
- active: clob.active,
439
- closed: clob.closed,
440
- acceptingOrders: clob.acceptingOrders,
441
- endDate: clob.endDateIso ? new Date(clob.endDateIso) : new Date(),
442
- source: 'clob',
443
- };
444
- }
445
-
446
- // ===== Cache Management =====
447
-
448
- /**
449
- * Clear all cached data
450
- */
451
- clearCache(): void {
452
- this.cache.clear();
453
- }
454
-
455
- /**
456
- * Invalidate cache for a specific market
457
- */
458
- invalidateMarketCache(conditionId: string): void {
459
- this.cache.invalidate(conditionId);
460
- }
461
- }