@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
@@ -1,503 +0,0 @@
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);
@@ -1,109 +0,0 @@
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