@catalyst-team/poly-sdk 0.1.1 → 0.2.1

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 (191) hide show
  1. package/LICENSE +1 -1
  2. package/README.en.md +502 -0
  3. package/README.md +6 -1
  4. package/README.zh-CN.md +502 -0
  5. package/dist/__tests__/clob-api.test.d.ts +5 -0
  6. package/dist/__tests__/clob-api.test.d.ts.map +1 -0
  7. package/dist/__tests__/clob-api.test.js +240 -0
  8. package/dist/__tests__/clob-api.test.js.map +1 -0
  9. package/dist/__tests__/integration/bridge-client.integration.test.d.ts +11 -0
  10. package/dist/__tests__/integration/bridge-client.integration.test.d.ts.map +1 -0
  11. package/dist/__tests__/integration/bridge-client.integration.test.js +260 -0
  12. package/dist/__tests__/integration/bridge-client.integration.test.js.map +1 -0
  13. package/dist/__tests__/integration/clob-api.integration.test.d.ts +13 -0
  14. package/dist/__tests__/integration/clob-api.integration.test.d.ts.map +1 -0
  15. package/dist/__tests__/integration/clob-api.integration.test.js +170 -0
  16. package/dist/__tests__/integration/clob-api.integration.test.js.map +1 -0
  17. package/dist/__tests__/integration/ctf-client.integration.test.d.ts +17 -0
  18. package/dist/__tests__/integration/ctf-client.integration.test.d.ts.map +1 -0
  19. package/dist/__tests__/integration/ctf-client.integration.test.js +234 -0
  20. package/dist/__tests__/integration/ctf-client.integration.test.js.map +1 -0
  21. package/dist/__tests__/integration/data-api.integration.test.d.ts +9 -0
  22. package/dist/__tests__/integration/data-api.integration.test.d.ts.map +1 -0
  23. package/dist/__tests__/integration/data-api.integration.test.js +161 -0
  24. package/dist/__tests__/integration/data-api.integration.test.js.map +1 -0
  25. package/dist/__tests__/integration/gamma-api.integration.test.d.ts +9 -0
  26. package/dist/__tests__/integration/gamma-api.integration.test.d.ts.map +1 -0
  27. package/dist/__tests__/integration/gamma-api.integration.test.js +170 -0
  28. package/dist/__tests__/integration/gamma-api.integration.test.js.map +1 -0
  29. package/dist/__tests__/test-utils.d.ts +92 -0
  30. package/dist/__tests__/test-utils.d.ts.map +1 -0
  31. package/dist/__tests__/test-utils.js +143 -0
  32. package/dist/__tests__/test-utils.js.map +1 -0
  33. package/dist/clients/bridge-client.d.ts +388 -0
  34. package/dist/clients/bridge-client.d.ts.map +1 -0
  35. package/dist/clients/bridge-client.js +587 -0
  36. package/dist/clients/bridge-client.js.map +1 -0
  37. package/dist/clients/clob-api.d.ts +318 -0
  38. package/dist/clients/clob-api.d.ts.map +1 -0
  39. package/dist/clients/clob-api.js +388 -0
  40. package/dist/clients/clob-api.js.map +1 -0
  41. package/dist/clients/ctf-client.d.ts +473 -0
  42. package/dist/clients/ctf-client.d.ts.map +1 -0
  43. package/dist/clients/ctf-client.js +915 -0
  44. package/dist/clients/ctf-client.js.map +1 -0
  45. package/dist/clients/data-api.d.ts +134 -0
  46. package/dist/clients/data-api.d.ts.map +1 -0
  47. package/dist/clients/data-api.js +265 -0
  48. package/dist/clients/data-api.js.map +1 -0
  49. package/dist/clients/gamma-api.d.ts +401 -0
  50. package/dist/clients/gamma-api.d.ts.map +1 -0
  51. package/dist/clients/gamma-api.js +352 -0
  52. package/dist/clients/gamma-api.js.map +1 -0
  53. package/dist/clients/trading-client.d.ts +252 -0
  54. package/dist/clients/trading-client.d.ts.map +1 -0
  55. package/dist/clients/trading-client.js +543 -0
  56. package/dist/clients/trading-client.js.map +1 -0
  57. package/dist/clients/websocket-manager.d.ts +100 -0
  58. package/dist/clients/websocket-manager.d.ts.map +1 -0
  59. package/dist/clients/websocket-manager.js +193 -0
  60. package/dist/clients/websocket-manager.js.map +1 -0
  61. package/dist/core/cache-adapter-bridge.d.ts +36 -0
  62. package/dist/core/cache-adapter-bridge.d.ts.map +1 -0
  63. package/dist/core/cache-adapter-bridge.js +81 -0
  64. package/dist/core/cache-adapter-bridge.js.map +1 -0
  65. package/dist/core/cache.d.ts +40 -0
  66. package/dist/core/cache.d.ts.map +1 -0
  67. package/dist/core/cache.js +71 -0
  68. package/dist/core/cache.js.map +1 -0
  69. package/dist/core/errors.d.ts +38 -0
  70. package/dist/core/errors.d.ts.map +1 -0
  71. package/dist/core/errors.js +84 -0
  72. package/dist/core/errors.js.map +1 -0
  73. package/dist/core/rate-limiter.d.ts +31 -0
  74. package/dist/core/rate-limiter.d.ts.map +1 -0
  75. package/dist/core/rate-limiter.js +70 -0
  76. package/dist/core/rate-limiter.js.map +1 -0
  77. package/{src/core/types.ts → dist/core/types.d.ts} +169 -215
  78. package/dist/core/types.d.ts.map +1 -0
  79. package/dist/core/types.js +19 -0
  80. package/dist/core/types.js.map +1 -0
  81. package/dist/core/unified-cache.d.ts +63 -0
  82. package/dist/core/unified-cache.d.ts.map +1 -0
  83. package/dist/core/unified-cache.js +114 -0
  84. package/dist/core/unified-cache.js.map +1 -0
  85. package/dist/index.d.ts +93 -0
  86. package/dist/index.d.ts.map +1 -0
  87. package/dist/index.js +255 -0
  88. package/dist/index.js.map +1 -0
  89. package/dist/services/arbitrage-service.d.ts +408 -0
  90. package/dist/services/arbitrage-service.d.ts.map +1 -0
  91. package/dist/services/arbitrage-service.js +1422 -0
  92. package/dist/services/arbitrage-service.js.map +1 -0
  93. package/dist/services/authorization-service.d.ts +97 -0
  94. package/dist/services/authorization-service.d.ts.map +1 -0
  95. package/dist/services/authorization-service.js +279 -0
  96. package/dist/services/authorization-service.js.map +1 -0
  97. package/dist/services/market-service.d.ts +108 -0
  98. package/dist/services/market-service.d.ts.map +1 -0
  99. package/dist/services/market-service.js +458 -0
  100. package/dist/services/market-service.js.map +1 -0
  101. package/dist/services/realtime-service.d.ts +82 -0
  102. package/dist/services/realtime-service.d.ts.map +1 -0
  103. package/dist/services/realtime-service.js +150 -0
  104. package/dist/services/realtime-service.js.map +1 -0
  105. package/dist/services/swap-service.d.ts +217 -0
  106. package/dist/services/swap-service.d.ts.map +1 -0
  107. package/dist/services/swap-service.js +695 -0
  108. package/dist/services/swap-service.js.map +1 -0
  109. package/dist/services/wallet-service.d.ts +94 -0
  110. package/dist/services/wallet-service.d.ts.map +1 -0
  111. package/dist/services/wallet-service.js +173 -0
  112. package/dist/services/wallet-service.js.map +1 -0
  113. package/dist/utils/price-utils.d.ts +153 -0
  114. package/dist/utils/price-utils.d.ts.map +1 -0
  115. package/dist/utils/price-utils.js +236 -0
  116. package/dist/utils/price-utils.js.map +1 -0
  117. package/package.json +7 -2
  118. package/docs/00-design.md +0 -760
  119. package/docs/02-API.md +0 -1148
  120. package/docs/arbitrage.md +0 -754
  121. package/docs/reports/smart-money-analysis-2025-12-23-cn.md +0 -840
  122. package/examples/01-basic-usage.ts +0 -68
  123. package/examples/02-smart-money.ts +0 -95
  124. package/examples/03-market-analysis.ts +0 -108
  125. package/examples/04-kline-aggregation.ts +0 -158
  126. package/examples/05-follow-wallet-strategy.ts +0 -156
  127. package/examples/06-services-demo.ts +0 -124
  128. package/examples/07-realtime-websocket.ts +0 -117
  129. package/examples/08-trading-orders.ts +0 -278
  130. package/examples/09-rewards-tracking.ts +0 -187
  131. package/examples/10-ctf-operations.ts +0 -336
  132. package/examples/11-live-arbitrage-scan.ts +0 -221
  133. package/examples/12-trending-arb-monitor.ts +0 -406
  134. package/examples/13-arbitrage-service.ts +0 -211
  135. package/examples/README.md +0 -179
  136. package/scripts/README.md +0 -163
  137. package/scripts/approvals/approve-erc1155.ts +0 -129
  138. package/scripts/approvals/approve-neg-risk-erc1155.ts +0 -149
  139. package/scripts/approvals/approve-neg-risk.ts +0 -102
  140. package/scripts/approvals/check-all-allowances.ts +0 -150
  141. package/scripts/approvals/check-allowance.ts +0 -129
  142. package/scripts/approvals/check-ctf-approval.ts +0 -158
  143. package/scripts/arb/faze-bo3-arb.ts +0 -385
  144. package/scripts/arb/settle-position.ts +0 -190
  145. package/scripts/arb/token-rebalancer.ts +0 -420
  146. package/scripts/datas/001-report.md +0 -486
  147. package/scripts/datas/clone-modal-screenshot.png +0 -0
  148. package/scripts/deposit/deposit-native-usdc.ts +0 -179
  149. package/scripts/deposit/deposit-usdc.ts +0 -155
  150. package/scripts/deposit/swap-usdc-to-usdce.ts +0 -375
  151. package/scripts/research/research-markets.ts +0 -166
  152. package/scripts/trading/check-orders.ts +0 -50
  153. package/scripts/trading/sell-nvidia-positions.ts +0 -206
  154. package/scripts/trading/test-order.ts +0 -172
  155. package/scripts/verify/test-approve-trading.ts +0 -98
  156. package/scripts/verify/test-provider-fix.ts +0 -43
  157. package/scripts/verify/test-search-mcp.ts +0 -113
  158. package/scripts/verify/verify-all-apis.ts +0 -160
  159. package/scripts/wallet/check-wallet-balances.ts +0 -75
  160. package/scripts/wallet/test-wallet-operations.ts +0 -191
  161. package/scripts/wallet/verify-wallet-tools.ts +0 -124
  162. package/src/__tests__/clob-api.test.ts +0 -301
  163. package/src/__tests__/integration/bridge-client.integration.test.ts +0 -314
  164. package/src/__tests__/integration/clob-api.integration.test.ts +0 -218
  165. package/src/__tests__/integration/ctf-client.integration.test.ts +0 -331
  166. package/src/__tests__/integration/data-api.integration.test.ts +0 -194
  167. package/src/__tests__/integration/gamma-api.integration.test.ts +0 -206
  168. package/src/__tests__/test-utils.ts +0 -170
  169. package/src/clients/bridge-client.ts +0 -841
  170. package/src/clients/clob-api.ts +0 -629
  171. package/src/clients/ctf-client.ts +0 -1216
  172. package/src/clients/data-api.ts +0 -469
  173. package/src/clients/gamma-api.ts +0 -597
  174. package/src/clients/trading-client.ts +0 -749
  175. package/src/clients/websocket-manager.ts +0 -267
  176. package/src/core/cache-adapter-bridge.ts +0 -94
  177. package/src/core/cache.ts +0 -85
  178. package/src/core/errors.ts +0 -117
  179. package/src/core/rate-limiter.ts +0 -74
  180. package/src/core/unified-cache.ts +0 -153
  181. package/src/index.ts +0 -461
  182. package/src/services/arbitrage-service.ts +0 -1807
  183. package/src/services/authorization-service.ts +0 -357
  184. package/src/services/market-service.ts +0 -544
  185. package/src/services/realtime-service.ts +0 -196
  186. package/src/services/swap-service.ts +0 -896
  187. package/src/services/wallet-service.ts +0 -259
  188. package/src/utils/price-utils.ts +0 -307
  189. package/tsconfig.json +0 -8
  190. package/vitest.config.ts +0 -19
  191. package/vitest.integration.config.ts +0 -18
@@ -1,153 +0,0 @@
1
- /**
2
- * Unified cache interface for poly-sdk
3
- *
4
- * Bridges between:
5
- * 1. Legacy internal Cache (synchronous get/set with millisecond TTL)
6
- * 2. New CacheAdapter interface (async with second TTL)
7
- *
8
- * This allows the SDK to accept external cache adapters while maintaining
9
- * backward compatibility with existing code.
10
- */
11
-
12
- import type { CacheAdapter } from '@catalyst-team/cache';
13
- import { Cache, CACHE_TTL } from './cache.js';
14
-
15
- /**
16
- * Unified cache interface that works with both legacy Cache and CacheAdapter
17
- *
18
- * Key features:
19
- * - Async API (compatible with CacheAdapter)
20
- * - Millisecond TTL (compatible with existing SDK code)
21
- * - getOrSet helper for cache-aside pattern
22
- */
23
- export interface UnifiedCache {
24
- get<T>(key: string): Promise<T | undefined>;
25
- set<T>(key: string, value: T, ttlMs: number): Promise<void>;
26
- getOrSet<T>(key: string, ttlMs: number, factory: () => Promise<T>): Promise<T>;
27
- invalidate(pattern: string): Promise<void>;
28
- clear(): void;
29
- }
30
-
31
- /**
32
- * Wraps the legacy Cache class to provide async interface
33
- */
34
- export class LegacyCacheWrapper implements UnifiedCache {
35
- constructor(private cache: Cache) {}
36
-
37
- async get<T>(key: string): Promise<T | undefined> {
38
- return this.cache.get<T>(key);
39
- }
40
-
41
- async set<T>(key: string, value: T, ttlMs: number): Promise<void> {
42
- this.cache.set(key, value, ttlMs);
43
- }
44
-
45
- async getOrSet<T>(
46
- key: string,
47
- ttlMs: number,
48
- factory: () => Promise<T>
49
- ): Promise<T> {
50
- return this.cache.getOrSet(key, ttlMs, factory);
51
- }
52
-
53
- async invalidate(pattern: string): Promise<void> {
54
- this.cache.invalidate(pattern);
55
- }
56
-
57
- clear(): void {
58
- this.cache.clear();
59
- }
60
- }
61
-
62
- /**
63
- * Wraps a CacheAdapter to provide legacy-compatible interface
64
- *
65
- * Main differences:
66
- * - Converts milliseconds to seconds for TTL
67
- * - Returns undefined instead of null for missing keys
68
- * - Implements getOrSet helper
69
- * - Implements pattern-based invalidation (limited support)
70
- */
71
- export class CacheAdapterWrapper implements UnifiedCache {
72
- constructor(private adapter: CacheAdapter) {}
73
-
74
- async get<T>(key: string): Promise<T | undefined> {
75
- const value = await this.adapter.get<T>(key);
76
- return value ?? undefined;
77
- }
78
-
79
- async set<T>(key: string, value: T, ttlMs: number): Promise<void> {
80
- // Convert milliseconds to seconds
81
- const ttlSeconds = Math.ceil(ttlMs / 1000);
82
-
83
- // Check if this is a CacheManager (has getStats method)
84
- if ('getStats' in this.adapter) {
85
- // This is a CacheManager - use CacheSetOptions signature
86
- await (this.adapter as any).set(key, value, { ttl: ttlSeconds });
87
- } else {
88
- // This is a regular CacheAdapter - use simple signature
89
- await this.adapter.set(key, value, ttlSeconds);
90
- }
91
- }
92
-
93
- async getOrSet<T>(
94
- key: string,
95
- ttlMs: number,
96
- factory: () => Promise<T>
97
- ): Promise<T> {
98
- const cached = await this.adapter.get<T>(key);
99
- if (cached !== null) return cached;
100
-
101
- const value = await factory();
102
- const ttlSeconds = Math.ceil(ttlMs / 1000);
103
-
104
- // Check if this is a CacheManager
105
- if ('getStats' in this.adapter) {
106
- // This is a CacheManager
107
- await (this.adapter as any).set(key, value, { ttl: ttlSeconds });
108
- } else {
109
- // This is a regular CacheAdapter
110
- await this.adapter.set(key, value, ttlSeconds);
111
- }
112
- return value;
113
- }
114
-
115
- async invalidate(pattern: string): Promise<void> {
116
- // CacheAdapter doesn't have pattern matching
117
- // Best we can do is warn - this is a limitation
118
- console.warn(
119
- `invalidate(pattern="${pattern}") not fully supported with external cache adapter`
120
- );
121
- }
122
-
123
- clear(): void {
124
- void this.adapter.clear?.();
125
- }
126
- }
127
-
128
- /**
129
- * Create a UnifiedCache from either legacy Cache or CacheAdapter
130
- */
131
- export function createUnifiedCache(
132
- cache?: CacheAdapter | Cache
133
- ): UnifiedCache {
134
- if (!cache) {
135
- // No cache provided, create default legacy cache
136
- return new LegacyCacheWrapper(new Cache());
137
- }
138
-
139
- // Check if it's a CacheAdapter (has async get method)
140
- if ('get' in cache && typeof cache.get === 'function') {
141
- const testResult = cache.get('test');
142
- if (testResult instanceof Promise) {
143
- // It's a CacheAdapter
144
- return new CacheAdapterWrapper(cache as CacheAdapter);
145
- }
146
- }
147
-
148
- // It's a legacy Cache
149
- return new LegacyCacheWrapper(cache as Cache);
150
- }
151
-
152
- // Re-export CACHE_TTL for convenience
153
- export { CACHE_TTL };
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
- }