@catalyst-team/poly-sdk 0.1.0 → 0.2.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 (201) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +538 -0
  3. package/README.md +357 -78
  4. package/docs/00-design.md +1 -1
  5. package/docs/02-API.md +21 -21
  6. package/docs/arb/test-plan.md +387 -0
  7. package/docs/arb/test-results.md +336 -0
  8. package/docs/arbitrage.md +754 -0
  9. package/docs/reports/smart-money-analysis-2025-12-23-cn.md +840 -0
  10. package/examples/13-arbitrage-service.ts +211 -0
  11. package/examples/README.md +1 -1
  12. package/package.json +19 -19
  13. package/scripts/arb/faze-bo3-arb.ts +385 -0
  14. package/scripts/arb/settle-position.ts +190 -0
  15. package/scripts/arb/token-rebalancer.ts +420 -0
  16. package/scripts/arb-tests/01-unit-tests.ts +495 -0
  17. package/scripts/arb-tests/02-integration-tests.ts +412 -0
  18. package/scripts/arb-tests/03-e2e-tests.ts +503 -0
  19. package/scripts/arb-tests/README.md +109 -0
  20. package/scripts/verify/verify-all-apis.ts +1 -1
  21. package/src/clients/clob-api.ts +1 -1
  22. package/src/clients/gamma-api.ts +1 -1
  23. package/src/core/cache-adapter-bridge.ts +1 -1
  24. package/src/core/types.ts +3 -3
  25. package/src/core/unified-cache.ts +1 -1
  26. package/src/index.ts +25 -19
  27. package/src/services/arbitrage-service.ts +1807 -0
  28. package/.env +0 -0
  29. package/dist/__tests__/clob-api.test.d.ts +0 -5
  30. package/dist/__tests__/clob-api.test.d.ts.map +0 -1
  31. package/dist/__tests__/clob-api.test.js +0 -240
  32. package/dist/__tests__/clob-api.test.js.map +0 -1
  33. package/dist/__tests__/integration/bridge-client.integration.test.d.ts +0 -11
  34. package/dist/__tests__/integration/bridge-client.integration.test.d.ts.map +0 -1
  35. package/dist/__tests__/integration/bridge-client.integration.test.js +0 -260
  36. package/dist/__tests__/integration/bridge-client.integration.test.js.map +0 -1
  37. package/dist/__tests__/integration/clob-api.integration.test.d.ts +0 -13
  38. package/dist/__tests__/integration/clob-api.integration.test.d.ts.map +0 -1
  39. package/dist/__tests__/integration/clob-api.integration.test.js +0 -170
  40. package/dist/__tests__/integration/clob-api.integration.test.js.map +0 -1
  41. package/dist/__tests__/integration/ctf-client.integration.test.d.ts +0 -17
  42. package/dist/__tests__/integration/ctf-client.integration.test.d.ts.map +0 -1
  43. package/dist/__tests__/integration/ctf-client.integration.test.js +0 -234
  44. package/dist/__tests__/integration/ctf-client.integration.test.js.map +0 -1
  45. package/dist/__tests__/integration/data-api.integration.test.d.ts +0 -9
  46. package/dist/__tests__/integration/data-api.integration.test.d.ts.map +0 -1
  47. package/dist/__tests__/integration/data-api.integration.test.js +0 -161
  48. package/dist/__tests__/integration/data-api.integration.test.js.map +0 -1
  49. package/dist/__tests__/integration/gamma-api.integration.test.d.ts +0 -9
  50. package/dist/__tests__/integration/gamma-api.integration.test.d.ts.map +0 -1
  51. package/dist/__tests__/integration/gamma-api.integration.test.js +0 -170
  52. package/dist/__tests__/integration/gamma-api.integration.test.js.map +0 -1
  53. package/dist/__tests__/test-utils.d.ts +0 -92
  54. package/dist/__tests__/test-utils.d.ts.map +0 -1
  55. package/dist/__tests__/test-utils.js +0 -143
  56. package/dist/__tests__/test-utils.js.map +0 -1
  57. package/dist/clients/bridge-client.d.ts +0 -388
  58. package/dist/clients/bridge-client.d.ts.map +0 -1
  59. package/dist/clients/bridge-client.js +0 -587
  60. package/dist/clients/bridge-client.js.map +0 -1
  61. package/dist/clients/clob-api.d.ts +0 -318
  62. package/dist/clients/clob-api.d.ts.map +0 -1
  63. package/dist/clients/clob-api.js +0 -388
  64. package/dist/clients/clob-api.js.map +0 -1
  65. package/dist/clients/ctf-client.d.ts +0 -473
  66. package/dist/clients/ctf-client.d.ts.map +0 -1
  67. package/dist/clients/ctf-client.js +0 -915
  68. package/dist/clients/ctf-client.js.map +0 -1
  69. package/dist/clients/data-api.d.ts +0 -134
  70. package/dist/clients/data-api.d.ts.map +0 -1
  71. package/dist/clients/data-api.js +0 -265
  72. package/dist/clients/data-api.js.map +0 -1
  73. package/dist/clients/gamma-api.d.ts +0 -401
  74. package/dist/clients/gamma-api.d.ts.map +0 -1
  75. package/dist/clients/gamma-api.js +0 -352
  76. package/dist/clients/gamma-api.js.map +0 -1
  77. package/dist/clients/trading-client.d.ts +0 -252
  78. package/dist/clients/trading-client.d.ts.map +0 -1
  79. package/dist/clients/trading-client.js +0 -543
  80. package/dist/clients/trading-client.js.map +0 -1
  81. package/dist/clients/websocket-manager.d.ts +0 -100
  82. package/dist/clients/websocket-manager.d.ts.map +0 -1
  83. package/dist/clients/websocket-manager.js +0 -193
  84. package/dist/clients/websocket-manager.js.map +0 -1
  85. package/dist/core/cache-adapter-bridge.d.ts +0 -36
  86. package/dist/core/cache-adapter-bridge.d.ts.map +0 -1
  87. package/dist/core/cache-adapter-bridge.js +0 -81
  88. package/dist/core/cache-adapter-bridge.js.map +0 -1
  89. package/dist/core/cache.d.ts +0 -40
  90. package/dist/core/cache.d.ts.map +0 -1
  91. package/dist/core/cache.js +0 -71
  92. package/dist/core/cache.js.map +0 -1
  93. package/dist/core/errors.d.ts +0 -38
  94. package/dist/core/errors.d.ts.map +0 -1
  95. package/dist/core/errors.js +0 -84
  96. package/dist/core/errors.js.map +0 -1
  97. package/dist/core/rate-limiter.d.ts +0 -31
  98. package/dist/core/rate-limiter.d.ts.map +0 -1
  99. package/dist/core/rate-limiter.js +0 -70
  100. package/dist/core/rate-limiter.js.map +0 -1
  101. package/dist/core/types.d.ts +0 -314
  102. package/dist/core/types.d.ts.map +0 -1
  103. package/dist/core/types.js +0 -19
  104. package/dist/core/types.js.map +0 -1
  105. package/dist/core/unified-cache.d.ts +0 -63
  106. package/dist/core/unified-cache.d.ts.map +0 -1
  107. package/dist/core/unified-cache.js +0 -114
  108. package/dist/core/unified-cache.js.map +0 -1
  109. package/dist/index.d.ts +0 -94
  110. package/dist/index.d.ts.map +0 -1
  111. package/dist/index.js +0 -258
  112. package/dist/index.js.map +0 -1
  113. package/dist/mcp/errors.d.ts +0 -33
  114. package/dist/mcp/errors.d.ts.map +0 -1
  115. package/dist/mcp/errors.js +0 -86
  116. package/dist/mcp/errors.js.map +0 -1
  117. package/dist/mcp/index.d.ts +0 -62
  118. package/dist/mcp/index.d.ts.map +0 -1
  119. package/dist/mcp/index.js +0 -173
  120. package/dist/mcp/index.js.map +0 -1
  121. package/dist/mcp/server.d.ts +0 -17
  122. package/dist/mcp/server.d.ts.map +0 -1
  123. package/dist/mcp/server.js +0 -155
  124. package/dist/mcp/server.js.map +0 -1
  125. package/dist/mcp/tools/guide.d.ts +0 -12
  126. package/dist/mcp/tools/guide.d.ts.map +0 -1
  127. package/dist/mcp/tools/guide.js +0 -801
  128. package/dist/mcp/tools/guide.js.map +0 -1
  129. package/dist/mcp/tools/index.d.ts +0 -11
  130. package/dist/mcp/tools/index.d.ts.map +0 -1
  131. package/dist/mcp/tools/index.js +0 -27
  132. package/dist/mcp/tools/index.js.map +0 -1
  133. package/dist/mcp/tools/market.d.ts +0 -11
  134. package/dist/mcp/tools/market.d.ts.map +0 -1
  135. package/dist/mcp/tools/market.js +0 -314
  136. package/dist/mcp/tools/market.js.map +0 -1
  137. package/dist/mcp/tools/order.d.ts +0 -10
  138. package/dist/mcp/tools/order.d.ts.map +0 -1
  139. package/dist/mcp/tools/order.js +0 -258
  140. package/dist/mcp/tools/order.js.map +0 -1
  141. package/dist/mcp/tools/trade.d.ts +0 -38
  142. package/dist/mcp/tools/trade.d.ts.map +0 -1
  143. package/dist/mcp/tools/trade.js +0 -314
  144. package/dist/mcp/tools/trade.js.map +0 -1
  145. package/dist/mcp/tools/trader.d.ts +0 -11
  146. package/dist/mcp/tools/trader.d.ts.map +0 -1
  147. package/dist/mcp/tools/trader.js +0 -277
  148. package/dist/mcp/tools/trader.js.map +0 -1
  149. package/dist/mcp/tools/wallet.d.ts +0 -274
  150. package/dist/mcp/tools/wallet.d.ts.map +0 -1
  151. package/dist/mcp/tools/wallet.js +0 -579
  152. package/dist/mcp/tools/wallet.js.map +0 -1
  153. package/dist/mcp/types.d.ts +0 -413
  154. package/dist/mcp/types.d.ts.map +0 -1
  155. package/dist/mcp/types.js +0 -5
  156. package/dist/mcp/types.js.map +0 -1
  157. package/dist/services/authorization-service.d.ts +0 -97
  158. package/dist/services/authorization-service.d.ts.map +0 -1
  159. package/dist/services/authorization-service.js +0 -279
  160. package/dist/services/authorization-service.js.map +0 -1
  161. package/dist/services/market-service.d.ts +0 -108
  162. package/dist/services/market-service.d.ts.map +0 -1
  163. package/dist/services/market-service.js +0 -458
  164. package/dist/services/market-service.js.map +0 -1
  165. package/dist/services/realtime-service.d.ts +0 -82
  166. package/dist/services/realtime-service.d.ts.map +0 -1
  167. package/dist/services/realtime-service.js +0 -150
  168. package/dist/services/realtime-service.js.map +0 -1
  169. package/dist/services/swap-service.d.ts +0 -217
  170. package/dist/services/swap-service.d.ts.map +0 -1
  171. package/dist/services/swap-service.js +0 -695
  172. package/dist/services/swap-service.js.map +0 -1
  173. package/dist/services/wallet-service.d.ts +0 -94
  174. package/dist/services/wallet-service.d.ts.map +0 -1
  175. package/dist/services/wallet-service.js +0 -173
  176. package/dist/services/wallet-service.js.map +0 -1
  177. package/dist/utils/price-utils.d.ts +0 -153
  178. package/dist/utils/price-utils.d.ts.map +0 -1
  179. package/dist/utils/price-utils.js +0 -236
  180. package/dist/utils/price-utils.js.map +0 -1
  181. package/docs/01-mcp.md +0 -2041
  182. package/docs/e2e/01-trader-tools.md +0 -159
  183. package/docs/e2e/02-market-tools.md +0 -180
  184. package/docs/e2e/03-order-tools.md +0 -166
  185. package/docs/e2e/04-wallet-tools.md +0 -224
  186. package/docs/e2e/05-trading-tools.md +0 -327
  187. package/docs/e2e/06-integration-scenarios.md +0 -481
  188. package/docs/e2e/coordinator.md +0 -376
  189. package/scripts/truth.md +0 -440
  190. package/src/mcp/README.md +0 -380
  191. package/src/mcp/errors.ts +0 -124
  192. package/src/mcp/index.ts +0 -309
  193. package/src/mcp/server.ts +0 -183
  194. package/src/mcp/tools/guide.ts +0 -821
  195. package/src/mcp/tools/index.ts +0 -73
  196. package/src/mcp/tools/market.ts +0 -363
  197. package/src/mcp/tools/order.ts +0 -326
  198. package/src/mcp/tools/trade.ts +0 -417
  199. package/src/mcp/tools/trader.ts +0 -322
  200. package/src/mcp/tools/wallet.ts +0 -683
  201. package/src/mcp/types.ts +0 -472
@@ -0,0 +1,503 @@
1
+ #!/usr/bin/env npx tsx
2
+ /**
3
+ * E2E Test Script for CTF Operations
4
+ *
5
+ * Tests complete workflow with real private key:
6
+ * 1. Wallet connection and balance query
7
+ * 2. CTF checkReadyForCTF()
8
+ * 3. CTF Split operation (small amount: $5)
9
+ * 4. CTF Merge operation (merge back the split tokens)
10
+ * 5. clearPositions() dry run
11
+ *
12
+ * ⚠️ SAFETY:
13
+ * - Uses small amounts ($5 max) for safety
14
+ * - Always do dry run first for clearPositions
15
+ * - Real on-chain transactions with real funds
16
+ *
17
+ * Environment:
18
+ * PRIVATE_KEY - Private key (from .env file)
19
+ * POLYGON_RPC_URL - Optional RPC URL (default: https://polygon-rpc.com)
20
+ *
21
+ * Run with:
22
+ * npx tsx scripts/arb-tests/03-e2e-tests.ts
23
+ *
24
+ * Based on:
25
+ * - examples/10-ctf-operations.ts
26
+ * - examples/13-arbitrage-service.ts
27
+ */
28
+
29
+ import { config } from 'dotenv';
30
+ import path from 'path';
31
+ import {
32
+ CTFClient,
33
+ PolymarketSDK,
34
+ ArbitrageService,
35
+ CTF_CONTRACT,
36
+ USDC_CONTRACT,
37
+ NATIVE_USDC_CONTRACT,
38
+ formatUSDC,
39
+ } from '../../src/index.js';
40
+ import type { ArbitrageMarketConfig, TokenIds } from '../../src/index.js';
41
+
42
+ // Load .env from package root
43
+ config({ path: path.resolve(process.cwd(), '.env') });
44
+
45
+ // ===== Configuration =====
46
+
47
+ const PRIVATE_KEY = process.env.PRIVATE_KEY;
48
+ const RPC_URL = process.env.POLYGON_RPC_URL || 'https://polygon-rpc.com';
49
+ const TEST_AMOUNT = '5'; // $5 for safety
50
+ const MIN_MATIC_BALANCE = 0.01; // Minimum MATIC for gas
51
+
52
+ // ===== Test State =====
53
+
54
+ interface TestResult {
55
+ name: string;
56
+ status: 'PASS' | 'FAIL' | 'SKIP';
57
+ duration?: number;
58
+ error?: string;
59
+ data?: any;
60
+ }
61
+
62
+ const results: TestResult[] = [];
63
+ let ctfClient: CTFClient;
64
+ let sdk: PolymarketSDK;
65
+ let testMarket: ArbitrageMarketConfig | null = null;
66
+
67
+ // ===== Helper Functions =====
68
+
69
+ function printHeader(title: string) {
70
+ console.log('\n' + '='.repeat(70));
71
+ console.log(title);
72
+ console.log('='.repeat(70));
73
+ }
74
+
75
+ function printSubHeader(title: string) {
76
+ console.log('\n' + '-'.repeat(70));
77
+ console.log(title);
78
+ console.log('-'.repeat(70));
79
+ }
80
+
81
+ function logTest(name: string) {
82
+ console.log(`\n[TEST] ${name}`);
83
+ }
84
+
85
+ function recordResult(name: string, status: 'PASS' | 'FAIL' | 'SKIP', duration?: number, error?: string, data?: any) {
86
+ results.push({ name, status, duration, error, data });
87
+
88
+ const statusSymbol = status === 'PASS' ? '✅' : status === 'FAIL' ? '❌' : '⏭️ ';
89
+ const durationStr = duration !== undefined ? ` (${duration}ms)` : '';
90
+ console.log(`${statusSymbol} ${name}${durationStr}`);
91
+
92
+ if (error) {
93
+ console.log(` Error: ${error}`);
94
+ }
95
+ }
96
+
97
+ function printSummary() {
98
+ printHeader('TEST SUMMARY');
99
+
100
+ const passed = results.filter(r => r.status === 'PASS').length;
101
+ const failed = results.filter(r => r.status === 'FAIL').length;
102
+ const skipped = results.filter(r => r.status === 'SKIP').length;
103
+ const total = results.length;
104
+
105
+ console.log(`\nTotal: ${total} | Passed: ${passed} | Failed: ${failed} | Skipped: ${skipped}`);
106
+ console.log('');
107
+
108
+ results.forEach(r => {
109
+ const statusSymbol = r.status === 'PASS' ? '✅' : r.status === 'FAIL' ? '❌' : '⏭️ ';
110
+ console.log(`${statusSymbol} ${r.name}`);
111
+ if (r.error) {
112
+ console.log(` ${r.error}`);
113
+ }
114
+ });
115
+
116
+ console.log('');
117
+ process.exit(failed > 0 ? 1 : 0);
118
+ }
119
+
120
+ // ===== Test Functions =====
121
+
122
+ async function test1_WalletConnection() {
123
+ logTest('Test 1: Wallet Connection and Balance Query');
124
+ const start = Date.now();
125
+
126
+ try {
127
+ if (!PRIVATE_KEY) {
128
+ throw new Error('PRIVATE_KEY not set in .env file');
129
+ }
130
+
131
+ // Initialize CTF Client
132
+ ctfClient = new CTFClient({
133
+ privateKey: PRIVATE_KEY,
134
+ rpcUrl: RPC_URL,
135
+ });
136
+
137
+ const address = ctfClient.getAddress();
138
+ console.log(` Wallet Address: ${address}`);
139
+ console.log(` RPC URL: ${RPC_URL}`);
140
+
141
+ // Get balances
142
+ const [usdcE, nativeUsdc, maticBigNumber] = await Promise.all([
143
+ ctfClient.getUsdcBalance(),
144
+ ctfClient.getNativeUsdcBalance(),
145
+ ctfClient['provider'].getBalance(address),
146
+ ]);
147
+
148
+ // Convert BigNumber to ether string
149
+ const matic = parseFloat((await import('ethers')).ethers.utils.formatEther(maticBigNumber));
150
+
151
+ console.log(`\n Balances:`);
152
+ console.log(` ├─ USDC.e (CTF): $${parseFloat(usdcE).toFixed(4)}`);
153
+ console.log(` ├─ Native USDC: $${parseFloat(nativeUsdc).toFixed(4)}`);
154
+ console.log(` └─ MATIC (gas): ${matic.toFixed(4)}`);
155
+
156
+ console.log(`\n Contract Addresses:`);
157
+ console.log(` ├─ CTF: ${CTF_CONTRACT}`);
158
+ console.log(` ├─ USDC.e: ${USDC_CONTRACT}`);
159
+ console.log(` └─ Native USDC: ${NATIVE_USDC_CONTRACT}`);
160
+
161
+ // Validate minimum balances
162
+ if (matic < MIN_MATIC_BALANCE) {
163
+ throw new Error(`Insufficient MATIC for gas. Have: ${matic.toFixed(4)}, Need: ${MIN_MATIC_BALANCE}`);
164
+ }
165
+
166
+ recordResult('Test 1: Wallet Connection', 'PASS', Date.now() - start, undefined, {
167
+ address,
168
+ usdcE: parseFloat(usdcE),
169
+ nativeUsdc: parseFloat(nativeUsdc),
170
+ matic,
171
+ });
172
+ } catch (error) {
173
+ recordResult('Test 1: Wallet Connection', 'FAIL', Date.now() - start, String(error));
174
+ throw error;
175
+ }
176
+ }
177
+
178
+ async function test2_CheckReadyForCTF() {
179
+ logTest('Test 2: CTF checkReadyForCTF()');
180
+ const start = Date.now();
181
+
182
+ try {
183
+ const readiness = await ctfClient.checkReadyForCTF(TEST_AMOUNT);
184
+
185
+ console.log(`\n CTF Readiness Check (for $${TEST_AMOUNT}):`);
186
+ console.log(` ├─ USDC.e Balance: $${readiness.usdcEBalance}`);
187
+ console.log(` ├─ Native USDC: $${readiness.nativeUsdcBalance}`);
188
+ console.log(` ├─ MATIC Balance: ${readiness.maticBalance}`);
189
+ console.log(` └─ CTF Ready: ${readiness.ready ? '✅ Yes' : '❌ No'}`);
190
+
191
+ if (readiness.suggestion) {
192
+ console.log(`\n ⚠️ ${readiness.suggestion}`);
193
+ }
194
+
195
+ if (!readiness.ready) {
196
+ recordResult('Test 2: CTF Readiness Check', 'SKIP', Date.now() - start, 'Not ready for CTF operations', readiness);
197
+ return false;
198
+ }
199
+
200
+ recordResult('Test 2: CTF Readiness Check', 'PASS', Date.now() - start, undefined, readiness);
201
+ return true;
202
+ } catch (error) {
203
+ recordResult('Test 2: CTF Readiness Check', 'FAIL', Date.now() - start, String(error));
204
+ throw error;
205
+ }
206
+ }
207
+
208
+ async function test3_FindActiveMarket() {
209
+ logTest('Test 3: Find Active Market for Testing');
210
+ const start = Date.now();
211
+
212
+ try {
213
+ sdk = new PolymarketSDK();
214
+
215
+ // Find an active market with reasonable volume
216
+ const markets = await sdk.gammaApi.getMarkets({
217
+ closed: false,
218
+ active: true,
219
+ limit: 20,
220
+ });
221
+
222
+ if (markets.length === 0) {
223
+ throw new Error('No active markets found');
224
+ }
225
+
226
+ // Find market with orderbook
227
+ let selectedMarket = null;
228
+
229
+ for (const market of markets) {
230
+ try {
231
+ const clobMarket = await sdk.clobApi.getMarket(market.conditionId);
232
+ const yesToken = clobMarket.tokens.find(t => t.outcome === 'Yes');
233
+ const noToken = clobMarket.tokens.find(t => t.outcome === 'No');
234
+
235
+ if (yesToken && noToken && clobMarket.active && clobMarket.acceptingOrders) {
236
+ selectedMarket = {
237
+ market,
238
+ yesTokenId: yesToken.tokenId,
239
+ noTokenId: noToken.tokenId,
240
+ };
241
+ break;
242
+ }
243
+ } catch {
244
+ // Skip markets without orderbook
245
+ continue;
246
+ }
247
+ }
248
+
249
+ if (!selectedMarket) {
250
+ throw new Error('No suitable market found with orderbook');
251
+ }
252
+
253
+ testMarket = {
254
+ name: selectedMarket.market.question || 'Unknown Market',
255
+ conditionId: selectedMarket.market.conditionId,
256
+ yesTokenId: selectedMarket.yesTokenId,
257
+ noTokenId: selectedMarket.noTokenId,
258
+ };
259
+
260
+ console.log(`\n Selected Market:`);
261
+ console.log(` ├─ Question: ${testMarket.name.slice(0, 50)}...`);
262
+ console.log(` ├─ Condition ID: ${testMarket.conditionId}`);
263
+ console.log(` ├─ YES Token ID: ${testMarket.yesTokenId.slice(0, 20)}...`);
264
+ console.log(` └─ NO Token ID: ${testMarket.noTokenId.slice(0, 20)}...`);
265
+
266
+ recordResult('Test 3: Find Active Market', 'PASS', Date.now() - start, undefined, {
267
+ question: testMarket.name,
268
+ conditionId: testMarket.conditionId,
269
+ });
270
+ return true;
271
+ } catch (error) {
272
+ recordResult('Test 3: Find Active Market', 'FAIL', Date.now() - start, String(error));
273
+ return false;
274
+ }
275
+ }
276
+
277
+ async function test4_SplitOperation() {
278
+ logTest(`Test 4: CTF Split Operation ($${TEST_AMOUNT})`);
279
+ const start = Date.now();
280
+
281
+ try {
282
+ if (!testMarket) {
283
+ throw new Error('No test market available');
284
+ }
285
+
286
+ console.log(`\n Splitting $${TEST_AMOUNT} USDC into YES + NO tokens...`);
287
+ console.log(` Market: ${testMarket.conditionId}`);
288
+
289
+ // Check balance before
290
+ const balanceBefore = await ctfClient.getUsdcBalance();
291
+ console.log(` Balance before: $${balanceBefore}`);
292
+
293
+ // Execute split
294
+ const splitResult = await ctfClient.split(testMarket.conditionId, TEST_AMOUNT);
295
+
296
+ console.log(`\n ✅ Split successful!`);
297
+ console.log(` ├─ TX Hash: ${splitResult.txHash}`);
298
+ console.log(` ├─ Amount: ${splitResult.amount} USDC`);
299
+ console.log(` ├─ YES Tokens: ${splitResult.yesTokens}`);
300
+ console.log(` ├─ NO Tokens: ${splitResult.noTokens}`);
301
+ console.log(` └─ Gas Used: ${splitResult.gasUsed}`);
302
+
303
+ // Check balance after
304
+ const balanceAfter = await ctfClient.getUsdcBalance();
305
+ const balanceChange = parseFloat(balanceBefore) - parseFloat(balanceAfter);
306
+ console.log(` Balance after: $${balanceAfter} (spent: $${balanceChange.toFixed(4)})`);
307
+
308
+ // Wait for blockchain to settle
309
+ console.log(`\n Waiting 2s for blockchain to settle...`);
310
+ await new Promise(resolve => setTimeout(resolve, 2000));
311
+
312
+ // Verify token balances
313
+ const tokenIds: TokenIds = {
314
+ yesTokenId: testMarket.yesTokenId,
315
+ noTokenId: testMarket.noTokenId,
316
+ };
317
+
318
+ const positions = await ctfClient.getPositionBalanceByTokenIds(testMarket.conditionId, tokenIds);
319
+ console.log(`\n Token Positions:`);
320
+ console.log(` ├─ YES Balance: ${positions.yesBalance}`);
321
+ console.log(` └─ NO Balance: ${positions.noBalance}`);
322
+
323
+ recordResult('Test 4: CTF Split', 'PASS', Date.now() - start, undefined, {
324
+ txHash: splitResult.txHash,
325
+ amount: splitResult.amount,
326
+ gasUsed: splitResult.gasUsed,
327
+ });
328
+ return true;
329
+ } catch (error) {
330
+ recordResult('Test 4: CTF Split', 'FAIL', Date.now() - start, String(error));
331
+ return false;
332
+ }
333
+ }
334
+
335
+ async function test5_MergeOperation() {
336
+ logTest(`Test 5: CTF Merge Operation (merge back $${TEST_AMOUNT})`);
337
+ const start = Date.now();
338
+
339
+ try {
340
+ if (!testMarket) {
341
+ throw new Error('No test market available');
342
+ }
343
+
344
+ console.log(`\n Merging ${TEST_AMOUNT} YES + ${TEST_AMOUNT} NO → $${TEST_AMOUNT} USDC...`);
345
+ console.log(` Market: ${testMarket.conditionId}`);
346
+
347
+ // Check balance before
348
+ const balanceBefore = await ctfClient.getUsdcBalance();
349
+ console.log(` USDC balance before: $${balanceBefore}`);
350
+
351
+ // Execute merge
352
+ const tokenIds: TokenIds = {
353
+ yesTokenId: testMarket.yesTokenId,
354
+ noTokenId: testMarket.noTokenId,
355
+ };
356
+
357
+ // Check token balances before merge
358
+ const positionsBefore = await ctfClient.getPositionBalanceByTokenIds(testMarket.conditionId, tokenIds);
359
+ console.log(` Token positions before merge:`);
360
+ console.log(` ├─ YES: ${positionsBefore.yesBalance}`);
361
+ console.log(` └─ NO: ${positionsBefore.noBalance}`);
362
+
363
+ const mergeResult = await ctfClient.mergeByTokenIds(
364
+ testMarket.conditionId,
365
+ tokenIds,
366
+ TEST_AMOUNT
367
+ );
368
+
369
+ console.log(`\n ✅ Merge successful!`);
370
+ console.log(` ├─ TX Hash: ${mergeResult.txHash}`);
371
+ console.log(` ├─ Amount: ${mergeResult.amount} pairs`);
372
+ console.log(` ├─ USDC Received: $${mergeResult.usdcReceived}`);
373
+ console.log(` └─ Gas Used: ${mergeResult.gasUsed}`);
374
+
375
+ // Check balance after
376
+ const balanceAfter = await ctfClient.getUsdcBalance();
377
+ const balanceChange = parseFloat(balanceAfter) - parseFloat(balanceBefore);
378
+ console.log(` USDC balance after: $${balanceAfter} (recovered: $${balanceChange.toFixed(4)})`);
379
+
380
+ // Verify token balances
381
+ const positions = await ctfClient.getPositionBalanceByTokenIds(testMarket.conditionId, tokenIds);
382
+ console.log(`\n Token Positions (remaining):`);
383
+ console.log(` ├─ YES Balance: ${positions.yesBalance}`);
384
+ console.log(` └─ NO Balance: ${positions.noBalance}`);
385
+
386
+ recordResult('Test 5: CTF Merge', 'PASS', Date.now() - start, undefined, {
387
+ txHash: mergeResult.txHash,
388
+ usdcReceived: mergeResult.usdcReceived,
389
+ gasUsed: mergeResult.gasUsed,
390
+ });
391
+ return true;
392
+ } catch (error) {
393
+ recordResult('Test 5: CTF Merge', 'FAIL', Date.now() - start, String(error));
394
+ return false;
395
+ }
396
+ }
397
+
398
+ async function test6_ClearPositionsDryRun() {
399
+ logTest('Test 6: clearPositions() Dry Run');
400
+ const start = Date.now();
401
+
402
+ try {
403
+ if (!testMarket) {
404
+ throw new Error('No test market available');
405
+ }
406
+
407
+ // Initialize ArbitrageService for clearPositions
408
+ const arbService = new ArbitrageService({
409
+ privateKey: PRIVATE_KEY,
410
+ rpcUrl: RPC_URL,
411
+ enableLogging: false,
412
+ });
413
+
414
+ console.log(`\n Running clearPositions dry run...`);
415
+ console.log(` Market: ${testMarket.name.slice(0, 50)}...`);
416
+
417
+ // Execute dry run (execute = false)
418
+ const clearResult = await arbService.clearPositions(testMarket, false);
419
+
420
+ console.log(`\n Clear Positions Analysis:`);
421
+ console.log(` ├─ Market Status: ${clearResult.marketStatus}`);
422
+ console.log(` ├─ YES Balance: ${clearResult.yesBalance.toFixed(4)}`);
423
+ console.log(` ├─ NO Balance: ${clearResult.noBalance.toFixed(4)}`);
424
+ console.log(` ├─ Recovery Est: $${clearResult.totalUsdcRecovered.toFixed(4)}`);
425
+ console.log(` └─ Actions Planned: ${clearResult.actions.length}`);
426
+
427
+ if (clearResult.actions.length > 0) {
428
+ console.log(`\n Planned Actions:`);
429
+ clearResult.actions.forEach((action, i) => {
430
+ console.log(` ${i + 1}. ${action.type}: ${action.amount.toFixed(4)} → ~$${action.usdcResult.toFixed(4)}`);
431
+ });
432
+ } else {
433
+ console.log(`\n No actions needed (positions already clear)`);
434
+ }
435
+
436
+ recordResult('Test 6: clearPositions Dry Run', 'PASS', Date.now() - start, undefined, {
437
+ yesBalance: clearResult.yesBalance,
438
+ noBalance: clearResult.noBalance,
439
+ actions: clearResult.actions.length,
440
+ totalRecovery: clearResult.totalUsdcRecovered,
441
+ });
442
+ return true;
443
+ } catch (error) {
444
+ recordResult('Test 6: clearPositions Dry Run', 'FAIL', Date.now() - start, String(error));
445
+ return false;
446
+ }
447
+ }
448
+
449
+ // ===== Main Test Runner =====
450
+
451
+ async function main() {
452
+ printHeader('E2E CTF Operations Test Suite');
453
+ console.log('');
454
+ console.log('⚠️ WARNING: This script executes real on-chain transactions!');
455
+ console.log(` Test amount: $${TEST_AMOUNT} (small for safety)`);
456
+ console.log(` RPC URL: ${RPC_URL}`);
457
+ console.log('');
458
+
459
+ try {
460
+ // Test 1: Wallet Connection
461
+ await test1_WalletConnection();
462
+
463
+ // Test 2: CTF Readiness Check
464
+ const isReady = await test2_CheckReadyForCTF();
465
+
466
+ if (!isReady) {
467
+ console.log('\n⚠️ Wallet not ready for CTF operations. Skipping remaining tests.');
468
+ printSummary();
469
+ return;
470
+ }
471
+
472
+ // Test 3: Find Active Market
473
+ const hasMarket = await test3_FindActiveMarket();
474
+
475
+ if (!hasMarket) {
476
+ console.log('\n⚠️ No suitable market found. Skipping CTF operation tests.');
477
+ printSummary();
478
+ return;
479
+ }
480
+
481
+ // Test 4: Split Operation
482
+ const splitSuccess = await test4_SplitOperation();
483
+
484
+ if (!splitSuccess) {
485
+ console.log('\n⚠️ Split failed. Skipping merge test.');
486
+ printSummary();
487
+ return;
488
+ }
489
+
490
+ // Test 5: Merge Operation
491
+ await test5_MergeOperation();
492
+
493
+ // Test 6: Clear Positions Dry Run
494
+ await test6_ClearPositionsDryRun();
495
+
496
+ } catch (error) {
497
+ console.error('\n❌ Test suite failed:', error);
498
+ } finally {
499
+ printSummary();
500
+ }
501
+ }
502
+
503
+ main().catch(console.error);
@@ -0,0 +1,109 @@
1
+ # ArbitrageService Tests
2
+
3
+ Comprehensive test suite for arbitrage functionality including unit tests and integration tests.
4
+
5
+ ## Running Tests
6
+
7
+ ```bash
8
+ # Unit tests (fast, no API calls)
9
+ npx tsx scripts/arb-tests/01-unit-tests.ts
10
+
11
+ # Integration tests (real API calls, ~2 minutes)
12
+ npx tsx scripts/arb-tests/02-integration-tests.ts
13
+
14
+ # Or from monorepo root
15
+ pnpm -F @catalyst-team/poly-sdk tsx scripts/arb-tests/01-unit-tests.ts
16
+ pnpm -F @catalyst-team/poly-sdk tsx scripts/arb-tests/02-integration-tests.ts
17
+ ```
18
+
19
+ ## Test Coverage
20
+
21
+ ### 01-unit-tests.ts
22
+
23
+ Tests for `getEffectivePrices()` and `checkArbitrage()` functions from `src/utils/price-utils.ts`.
24
+
25
+ **getEffectivePrices() Tests (7 tests):**
26
+ - Normal market scenarios
27
+ - Long arbitrage opportunities
28
+ - Short arbitrage opportunities
29
+ - Mirror relationship validation
30
+ - Edge cases (prices near 0, near 1, 50/50 market)
31
+
32
+ **checkArbitrage() Tests (20 tests):**
33
+ - Long arbitrage detection (clear and small opportunities)
34
+ - Short arbitrage detection (various scenarios)
35
+ - No arbitrage scenarios (balanced markets, tight spreads)
36
+ - Edge cases (extreme arb, prices near boundaries)
37
+ - Boundary conditions (break-even scenarios)
38
+ - Mirror relationship effects
39
+ - Real-world scenarios (FaZe BO3 example)
40
+
41
+ ### Key Insights from Tests
42
+
43
+ 1. **Mirror Relationship**: In Polymarket, buying YES at price P is equivalent to selling NO at (1-P). The effective price functions correctly account for this by using `min()` for buy prices and `max()` for sell prices.
44
+
45
+ 2. **Long Arb Priority**: When both long and short arbitrage exist simultaneously (which happens when mirrored orders create inefficiencies), the `checkArbitrage()` function returns long arbitrage first. This is intentional since long arb is typically easier to execute (buy two assets, merge immediately).
46
+
47
+ 3. **Effective Prices**:
48
+ - `effectiveBuyYes = min(yesAsk, 1 - noBid)` - Best price to acquire YES tokens
49
+ - `effectiveBuyNo = min(noAsk, 1 - yesBid)` - Best price to acquire NO tokens
50
+ - `effectiveSellYes = max(yesBid, 1 - noAsk)` - Best price to sell YES tokens
51
+ - `effectiveSellNo = max(noBid, 1 - yesAsk)` - Best price to sell NO tokens
52
+
53
+ 4. **Arbitrage Detection**:
54
+ - Long arb: `effectiveBuyYes + effectiveBuyNo < 1.00`
55
+ - Short arb: `effectiveSellYes + effectiveSellNo > 1.00`
56
+
57
+ ## Test Results Format
58
+
59
+ Each test outputs:
60
+ - Input prices (YES ask/bid, NO ask/bid)
61
+ - Calculated result
62
+ - Expected result
63
+ - Pass/Fail status
64
+
65
+ Summary shows:
66
+ - Total tests run
67
+ - Number passed
68
+ - Number failed
69
+ - List of failed tests (if any)
70
+
71
+ ### 02-integration-tests.ts
72
+
73
+ Integration tests for ArbitrageService using real Polymarket APIs. No private key required (runs in monitor-only mode).
74
+
75
+ **Test 1: Service Initialization (1 test)**
76
+ - Validates ArbitrageService can be instantiated without private key
77
+ - Confirms monitor-only mode configuration
78
+
79
+ **Test 2: Market Scanning (2 tests)**
80
+ - Tests `scanMarkets()` with various criteria
81
+ - Validates ScanResult structure contains all required fields
82
+ - Verifies market data includes: conditionId, tokenIds, effective prices, volume, etc.
83
+
84
+ **Test 3: Quick Scan (2 tests)**
85
+ - Tests `quickScan()` with default and custom parameters
86
+ - Validates profit threshold and limit parameters work correctly
87
+
88
+ **Test 4: WebSocket Connection (4 tests)**
89
+ - Tests real-time WebSocket connection to Polymarket
90
+ - Monitors orderbook updates for 20 seconds
91
+ - Validates service statistics tracking
92
+ - Tests clean shutdown
93
+
94
+ **Duration**: ~115 seconds total
95
+ - 11s for market scanning
96
+ - 42s for first quick scan
97
+ - 42s for second quick scan
98
+ - 20s for WebSocket monitoring
99
+
100
+ **Expected Results**:
101
+ - 9 tests total
102
+ - All tests should pass
103
+ - No arbitrage opportunities required for tests to pass
104
+ - WebSocket should connect successfully even without opportunities
105
+
106
+ ## Exit Codes
107
+
108
+ - `0`: All tests passed
109
+ - `1`: One or more tests failed
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Verify all Polymarket API responses against SDK type definitions
3
3
  *
4
- * Run: pnpm -F @prediction-router/poly-sdk tsx scripts/verify-all-apis.ts
4
+ * Run: pnpm -F @catalyst-team/poly-sdk tsx scripts/verify-all-apis.ts
5
5
  */
6
6
 
7
7
  const DATA_API = 'https://data-api.polymarket.com';
@@ -12,7 +12,7 @@
12
12
  *
13
13
  * @example
14
14
  * ```typescript
15
- * import { ClobApiClient, RateLimiter, Cache } from '@prediction-router/poly-sdk';
15
+ * import { ClobApiClient, RateLimiter, Cache } from '@catalyst-team/poly-sdk';
16
16
  *
17
17
  * const client = new ClobApiClient(new RateLimiter(), new Cache());
18
18
  *
@@ -12,7 +12,7 @@
12
12
  *
13
13
  * @example
14
14
  * ```typescript
15
- * import { GammaApiClient, RateLimiter, Cache } from '@prediction-router/poly-sdk';
15
+ * import { GammaApiClient, RateLimiter, Cache } from '@catalyst-team/poly-sdk';
16
16
  *
17
17
  * const client = new GammaApiClient(new RateLimiter(), new Cache());
18
18
  *
@@ -6,7 +6,7 @@
6
6
  * 2. New CacheAdapter interface (async, second TTL)
7
7
  */
8
8
 
9
- import type { CacheAdapter } from '@prediction-router/cache';
9
+ import type { CacheAdapter } from '@catalyst-team/cache';
10
10
  import { Cache } from './cache.js';
11
11
 
12
12
  /**
package/src/core/types.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * Common types used across the SDK
3
3
  */
4
4
 
5
- import type { CacheAdapter } from '@prediction-router/cache';
5
+ import type { CacheAdapter } from '@catalyst-team/cache';
6
6
 
7
7
  /**
8
8
  * SDK Configuration Options
@@ -11,8 +11,8 @@ import type { CacheAdapter } from '@prediction-router/cache';
11
11
  *
12
12
  * @example
13
13
  * ```typescript
14
- * import { createMemoryCache } from '@prediction-router/cache';
15
- * import { PolymarketSDK } from '@prediction-router/poly-sdk';
14
+ * import { createMemoryCache } from '@catalyst-team/cache';
15
+ * import { PolymarketSDK } from '@catalyst-team/poly-sdk';
16
16
  *
17
17
  * // Use external cache adapter
18
18
  * const cache = createMemoryCache({ defaultTTL: 120 });
@@ -9,7 +9,7 @@
9
9
  * backward compatibility with existing code.
10
10
  */
11
11
 
12
- import type { CacheAdapter } from '@prediction-router/cache';
12
+ import type { CacheAdapter } from '@catalyst-team/cache';
13
13
  import { Cache, CACHE_TTL } from './cache.js';
14
14
 
15
15
  /**