@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,211 +0,0 @@
1
- #!/usr/bin/env npx tsx
2
- /**
3
- * Example 13: ArbitrageService - Complete Workflow
4
- *
5
- * Demonstrates the full arbitrage workflow:
6
- * 1. Scan markets for opportunities
7
- * 2. Start real-time monitoring
8
- * 3. Auto-execute arbitrage
9
- * 4. Stop and clear positions
10
- *
11
- * Environment variables:
12
- * POLY_PRIVKEY - Private key for trading (optional for scan-only mode)
13
- *
14
- * Run with:
15
- * pnpm example:arb-service
16
- *
17
- * Or scan-only (no trading):
18
- * npx tsx examples/13-arbitrage-service.ts --scan-only
19
- */
20
-
21
- import { ArbitrageService } from '../src/index.js';
22
-
23
- // Parse arguments
24
- const args = process.argv.slice(2);
25
- const SCAN_ONLY = args.includes('--scan-only');
26
- const RUN_DURATION = parseInt(args.find(a => a.startsWith('--duration='))?.split('=')[1] || '60') * 1000; // default 60s
27
-
28
- async function main() {
29
- console.log('╔════════════════════════════════════════════════════════════════╗');
30
- console.log('║ ArbitrageService - Complete Workflow ║');
31
- console.log('╚════════════════════════════════════════════════════════════════╝');
32
- console.log();
33
-
34
- const privateKey = process.env.POLY_PRIVKEY;
35
-
36
- if (!privateKey && !SCAN_ONLY) {
37
- console.log('No POLY_PRIVKEY provided. Running in scan-only mode.\n');
38
- }
39
-
40
- // ========== Initialize ArbitrageService ==========
41
- const arbService = new ArbitrageService({
42
- privateKey: SCAN_ONLY ? undefined : privateKey,
43
- profitThreshold: 0.005, // 0.5% minimum profit
44
- minTradeSize: 5, // $5 minimum
45
- maxTradeSize: 100, // $100 maximum
46
- autoExecute: !SCAN_ONLY && !!privateKey,
47
- enableLogging: true,
48
-
49
- // Rebalancer config
50
- enableRebalancer: !SCAN_ONLY && !!privateKey,
51
- minUsdcRatio: 0.2,
52
- maxUsdcRatio: 0.8,
53
- targetUsdcRatio: 0.5,
54
- imbalanceThreshold: 5,
55
- rebalanceInterval: 10000,
56
- rebalanceCooldown: 30000,
57
-
58
- // Execution safety
59
- sizeSafetyFactor: 0.8,
60
- autoFixImbalance: true,
61
- });
62
-
63
- // ========== Set up event listeners ==========
64
- arbService.on('opportunity', (opp) => {
65
- console.log(`\n🎯 ${opp.type.toUpperCase()} ARB: ${opp.profitPercent.toFixed(2)}%`);
66
- console.log(` ${opp.description}`);
67
- console.log(` Recommended size: ${opp.recommendedSize.toFixed(2)}, Est profit: $${opp.estimatedProfit.toFixed(2)}`);
68
- });
69
-
70
- arbService.on('execution', (result) => {
71
- if (result.success) {
72
- console.log(`\n✅ Execution succeeded!`);
73
- console.log(` Type: ${result.type}, Size: ${result.size.toFixed(2)}`);
74
- console.log(` Profit: $${result.profit.toFixed(2)}`);
75
- console.log(` Time: ${result.executionTimeMs}ms`);
76
- } else {
77
- console.log(`\n❌ Execution failed: ${result.error}`);
78
- }
79
- });
80
-
81
- arbService.on('rebalance', (result) => {
82
- if (result.success) {
83
- console.log(`\n🔄 Rebalance: ${result.action.type} ${result.action.amount.toFixed(2)}`);
84
- console.log(` Reason: ${result.action.reason}`);
85
- } else {
86
- console.log(`\n⚠️ Rebalance failed: ${result.error}`);
87
- }
88
- });
89
-
90
- arbService.on('balanceUpdate', (balance) => {
91
- console.log(`\n💰 Balance: USDC=${balance.usdc.toFixed(2)}, YES=${balance.yesTokens.toFixed(2)}, NO=${balance.noTokens.toFixed(2)}`);
92
- });
93
-
94
- arbService.on('error', (error) => {
95
- console.error(`\n🚨 Error: ${error.message}`);
96
- });
97
-
98
- // ========== Step 1: Scan Markets ==========
99
- console.log('═══════════════════════════════════════════════════════════════');
100
- console.log('Step 1: Scanning markets for arbitrage opportunities...');
101
- console.log('═══════════════════════════════════════════════════════════════\n');
102
-
103
- const scanResults = await arbService.scanMarkets(
104
- { minVolume24h: 5000, limit: 50 },
105
- 0.003 // 0.3% min profit for scanning
106
- );
107
-
108
- const opportunities = scanResults.filter(r => r.arbType !== 'none');
109
-
110
- console.log(`\nFound ${opportunities.length} opportunities out of ${scanResults.length} markets scanned\n`);
111
-
112
- if (opportunities.length > 0) {
113
- console.log('Top 5 opportunities:');
114
- console.log('┌──────────────────────────────────────────────────────────────────┐');
115
- for (const r of opportunities.slice(0, 5)) {
116
- console.log(`│ ${r.market.name.slice(0, 50).padEnd(50)} │`);
117
- console.log(`│ ${r.arbType.toUpperCase()} +${r.profitPercent.toFixed(2)}% Size: ${r.availableSize.toFixed(0)} Vol: $${r.volume24h.toLocaleString().padEnd(10)} │`);
118
- console.log(`├──────────────────────────────────────────────────────────────────┤`);
119
- }
120
- console.log('└──────────────────────────────────────────────────────────────────┘');
121
- }
122
-
123
- if (SCAN_ONLY || opportunities.length === 0) {
124
- console.log('\n✅ Scan complete.');
125
- if (SCAN_ONLY) {
126
- console.log(' (Running in scan-only mode, not starting arbitrage)');
127
- }
128
- if (opportunities.length === 0) {
129
- console.log(' (No profitable opportunities found)');
130
- }
131
- return;
132
- }
133
-
134
- // ========== Step 2: Start Arbitrage ==========
135
- console.log('\n═══════════════════════════════════════════════════════════════');
136
- console.log('Step 2: Starting arbitrage on best market...');
137
- console.log('═══════════════════════════════════════════════════════════════\n');
138
-
139
- const best = opportunities[0];
140
- console.log(`Selected: ${best.market.name}`);
141
- console.log(`Type: ${best.arbType.toUpperCase()}, Profit: +${best.profitPercent.toFixed(2)}%\n`);
142
-
143
- await arbService.start(best.market);
144
-
145
- // ========== Step 3: Run for duration ==========
146
- console.log('\n═══════════════════════════════════════════════════════════════');
147
- console.log(`Step 3: Running for ${RUN_DURATION / 1000} seconds...`);
148
- console.log('═══════════════════════════════════════════════════════════════\n');
149
- console.log('Monitoring for arbitrage opportunities...');
150
- console.log('(Press Ctrl+C to stop early)\n');
151
-
152
- // Handle graceful shutdown
153
- let stopped = false;
154
- const shutdown = async () => {
155
- if (stopped) return;
156
- stopped = true;
157
- console.log('\n\nShutting down...');
158
- await cleanup();
159
- process.exit(0);
160
- };
161
-
162
- process.on('SIGINT', shutdown);
163
- process.on('SIGTERM', shutdown);
164
-
165
- // Wait for duration
166
- await new Promise(resolve => setTimeout(resolve, RUN_DURATION));
167
-
168
- // ========== Step 4: Stop and Clear ==========
169
- async function cleanup() {
170
- console.log('\n═══════════════════════════════════════════════════════════════');
171
- console.log('Step 4: Stopping and clearing positions...');
172
- console.log('═══════════════════════════════════════════════════════════════\n');
173
-
174
- await arbService.stop();
175
-
176
- // Print stats
177
- const stats = arbService.getStats();
178
- console.log('Session Statistics:');
179
- console.log(` Opportunities detected: ${stats.opportunitiesDetected}`);
180
- console.log(` Executions attempted: ${stats.executionsAttempted}`);
181
- console.log(` Executions succeeded: ${stats.executionsSucceeded}`);
182
- console.log(` Total profit: $${stats.totalProfit.toFixed(2)}`);
183
- console.log(` Running time: ${(stats.runningTimeMs / 1000).toFixed(0)}s`);
184
-
185
- // Clear positions
186
- if (privateKey) {
187
- console.log('\nClearing positions...');
188
- const clearResult = await arbService.clearPositions(best.market, false);
189
-
190
- console.log(`\nPosition status:`);
191
- console.log(` Market status: ${clearResult.marketStatus}`);
192
- console.log(` YES balance: ${clearResult.yesBalance.toFixed(4)}`);
193
- console.log(` NO balance: ${clearResult.noBalance.toFixed(4)}`);
194
- console.log(` Expected recovery: $${clearResult.totalUsdcRecovered.toFixed(2)}`);
195
-
196
- if (clearResult.actions.length > 0) {
197
- console.log(`\nPlanned actions:`);
198
- for (const action of clearResult.actions) {
199
- console.log(` - ${action.type}: ${action.amount.toFixed(4)} → ~$${action.usdcResult.toFixed(2)}`);
200
- }
201
- console.log('\n(Run with --execute-clear to actually clear positions)');
202
- }
203
- }
204
-
205
- console.log('\n✅ Done!');
206
- }
207
-
208
- await cleanup();
209
- }
210
-
211
- main().catch(console.error);
@@ -1,179 +0,0 @@
1
- # Poly-SDK Examples
2
-
3
- Comprehensive examples demonstrating the Polymarket SDK capabilities.
4
-
5
- ## Running Examples
6
-
7
- ```bash
8
- # From poly-sdk directory
9
- npx tsx examples/01-basic-usage.ts
10
-
11
- # Or use pnpm scripts
12
- pnpm example:basic # 01-basic-usage.ts
13
- pnpm example:smart-money # 02-smart-money.ts
14
- ```
15
-
16
- ---
17
-
18
- ## Examples Overview
19
-
20
- | # | File | Description | Auth Required |
21
- |---|------|-------------|---------------|
22
- | 01 | `basic-usage.ts` | Trending markets, orderbook data | No |
23
- | 02 | `smart-money.ts` | Smart money wallet analysis | No |
24
- | 03 | `market-analysis.ts` | Market search and analysis | No |
25
- | 04 | `kline-aggregation.ts` | Price history and KLine data | No |
26
- | 05 | `follow-wallet-strategy.ts` | Copy trading simulation | No |
27
- | 06 | `services-demo.ts` | WalletService & MarketService | No |
28
- | 07 | `realtime-websocket.ts` | Real-time orderbook updates | No |
29
- | 08 | `trading-orders.ts` | Order placement and management | Yes |
30
- | 09 | `rewards-tracking.ts` | Liquidity rewards tracking | Yes |
31
- | 10 | `ctf-operations.ts` | Split/Merge/Redeem tokens | Yes |
32
- | 11 | `live-arbitrage-scan.ts` | Scan markets for arbitrage | No |
33
- | 12 | `trending-arb-monitor.ts` | Real-time arbitrage monitoring | No |
34
-
35
- ---
36
-
37
- ## Example Details
38
-
39
- ### 01 - Basic Usage
40
-
41
- Get started with the SDK. Fetches trending markets and orderbook data.
42
-
43
- ```typescript
44
- import { PolymarketSDK } from '@catalyst-team/poly-sdk';
45
- const sdk = new PolymarketSDK();
46
- const trending = await sdk.gammaApi.getTrendingMarkets(5);
47
- ```
48
-
49
- ### 02 - Smart Money Analysis
50
-
51
- Analyze wallet trading performance and identify profitable traders.
52
-
53
- - Fetch wallet positions and activity
54
- - Calculate P&L and win rate
55
- - Identify high-performing wallets
56
-
57
- ### 03 - Market Analysis
58
-
59
- Search and analyze markets by various criteria.
60
-
61
- - Search by keyword
62
- - Filter by volume, liquidity
63
- - Analyze market spreads
64
-
65
- ### 04 - KLine Aggregation
66
-
67
- Get price history for charting.
68
-
69
- - Multi-timeframe candles (1m, 5m, 1h, 1d)
70
- - OHLCV data
71
- - Dual YES/NO price tracking
72
-
73
- ### 05 - Follow Wallet Strategy
74
-
75
- Simulate copy trading based on smart money signals.
76
-
77
- - Monitor wallet activity
78
- - Generate trade signals
79
- - Backtest strategy performance
80
-
81
- ### 06 - Services Demo
82
-
83
- High-level service abstractions.
84
-
85
- - `WalletService` - Wallet analysis helpers
86
- - `MarketService` - Market data aggregation
87
-
88
- ### 07 - Real-time WebSocket
89
-
90
- Live orderbook streaming.
91
-
92
- - Connect to Polymarket WebSocket
93
- - Real-time price updates
94
- - Orderbook change events
95
-
96
- ### 08 - Trading Orders
97
-
98
- Place and manage orders (requires private key).
99
-
100
- ```bash
101
- POLY_PRIVKEY=0x... npx tsx examples/08-trading-orders.ts
102
- ```
103
-
104
- - Create limit/market orders
105
- - Cancel orders
106
- - Check order status
107
-
108
- ### 09 - Rewards Tracking
109
-
110
- Track liquidity provider rewards.
111
-
112
- - Earned rewards by market
113
- - Order scoring metrics
114
- - Reward rate analysis
115
-
116
- ### 10 - CTF Operations
117
-
118
- On-chain token operations (requires private key + USDC.e).
119
-
120
- ```bash
121
- POLY_PRIVKEY=0x... npx tsx examples/10-ctf-operations.ts
122
- ```
123
-
124
- **Critical:** Uses USDC.e (not native USDC):
125
- | Token | Address | CTF Compatible |
126
- |-------|---------|----------------|
127
- | USDC.e | `0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174` | Yes |
128
- | Native USDC | `0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359` | No |
129
-
130
- Operations:
131
- - **Split**: USDC.e → YES + NO tokens
132
- - **Merge**: YES + NO → USDC.e (arbitrage profit)
133
- - **Redeem**: Winning tokens → USDC.e
134
-
135
- ### 11 - Live Arbitrage Scan
136
-
137
- Scan markets for arbitrage opportunities (read-only).
138
-
139
- - Fetches active markets
140
- - Calculates effective prices
141
- - Detects long/short arb opportunities
142
-
143
- ### 12 - Trending Arbitrage Monitor
144
-
145
- Continuous monitoring of trending markets.
146
-
147
- - Real-time orderbook analysis
148
- - Correct effective price calculation
149
- - Configurable scan intervals
150
-
151
- ---
152
-
153
- ## Arbitrage Concepts
154
-
155
- Polymarket orderbooks have a mirroring property:
156
- - **Buying YES @ P = Selling NO @ (1-P)**
157
-
158
- Correct effective prices:
159
- ```
160
- effectiveBuyYes = min(YES.ask, 1 - NO.bid)
161
- effectiveBuyNo = min(NO.ask, 1 - YES.bid)
162
- effectiveSellYes = max(YES.bid, 1 - NO.ask)
163
- effectiveSellNo = max(NO.bid, 1 - YES.ask)
164
- ```
165
-
166
- | Arb Type | Condition | Action |
167
- |----------|-----------|--------|
168
- | Long | `effectiveBuyYes + effectiveBuyNo < 1` | Buy both, merge for $1 |
169
- | Short | `effectiveSellYes + effectiveSellNo > 1` | Split $1, sell both |
170
-
171
- ---
172
-
173
- ## Environment Variables
174
-
175
- | Variable | Description | Required For |
176
- |----------|-------------|--------------|
177
- | `POLY_PRIVKEY` | Private key for trading | 08, 09, 10 |
178
- | `SCAN_INTERVAL_MS` | Arb scan interval (ms) | 12 |
179
- | `PROFIT_THRESHOLD` | Min arb profit % | 11, 12 |
package/scripts/README.md DELETED
@@ -1,163 +0,0 @@
1
- # Poly-SDK Scripts
2
-
3
- Utility scripts for testing and operating with Polymarket.
4
-
5
- ## Environment Setup
6
-
7
- Set environment variable:
8
-
9
- ```bash
10
- export POLY_PRIVKEY=0x... # Your private key
11
- ```
12
-
13
- Or pass inline:
14
-
15
- ```bash
16
- POLY_PRIVKEY=0x... npx tsx scripts/...
17
- ```
18
-
19
- ---
20
-
21
- ## Directory Structure
22
-
23
- ```
24
- scripts/
25
- ├── approvals/ # ERC20/ERC1155 approval scripts
26
- ├── deposit/ # USDC deposit and swap scripts
27
- ├── trading/ # Order and position management
28
- ├── wallet/ # Wallet balance and verification
29
- ├── verify/ # API verification tests
30
- └── research/ # Market research and analysis
31
- ```
32
-
33
- ---
34
-
35
- ## Scripts Reference
36
-
37
- ### `approvals/` - Token Approvals
38
-
39
- | Script | Description |
40
- |--------|-------------|
41
- | `check-allowance.ts` | Check USDC allowance for CTF Exchange |
42
- | `check-all-allowances.ts` | Check all token allowances at once |
43
- | `check-ctf-approval.ts` | Check CTF/ERC1155 approval status |
44
- | `approve-neg-risk.ts` | Approve USDC for Neg Risk Exchange |
45
- | `approve-erc1155.ts` | Approve ERC1155 for CTF Exchange |
46
- | `approve-neg-risk-erc1155.ts` | Approve ERC1155 for Neg Risk Exchange |
47
-
48
- ```bash
49
- # Check all allowances
50
- npx tsx scripts/approvals/check-all-allowances.ts
51
-
52
- # Approve for neg risk markets
53
- npx tsx scripts/approvals/approve-neg-risk.ts
54
- ```
55
-
56
- ---
57
-
58
- ### `deposit/` - Deposits & Swaps
59
-
60
- | Script | Description |
61
- |--------|-------------|
62
- | `deposit-native-usdc.ts` | Deposit Native USDC via Bridge |
63
- | `deposit-usdc.ts` | Deposit USDC.e directly |
64
- | `swap-usdc-to-usdce.ts` | Swap Native USDC → USDC.e on DEX |
65
-
66
- ```bash
67
- # Check deposit address and status
68
- npx tsx scripts/deposit/deposit-native-usdc.ts check
69
-
70
- # Deposit $50 via Bridge
71
- npx tsx scripts/deposit/deposit-native-usdc.ts deposit 50
72
- ```
73
-
74
- **Important:** USDC.e is required for Polymarket CTF operations. Native USDC must be swapped or bridged first.
75
-
76
- ---
77
-
78
- ### `trading/` - Orders & Positions
79
-
80
- | Script | Description |
81
- |--------|-------------|
82
- | `check-orders.ts` | View open orders and recent trades |
83
- | `test-order.ts` | Test order placement |
84
- | `sell-nvidia-positions.ts` | Sell specific positions |
85
-
86
- ```bash
87
- # Check open orders
88
- npx tsx scripts/trading/check-orders.ts
89
-
90
- # Test order placement
91
- npx tsx scripts/trading/test-order.ts
92
- ```
93
-
94
- ---
95
-
96
- ### `wallet/` - Wallet Management
97
-
98
- | Script | Description |
99
- |--------|-------------|
100
- | `check-wallet-balances.ts` | Check all wallet balances |
101
- | `verify-wallet-tools.ts` | Verify wallet MCP tools |
102
- | `test-wallet-operations.ts` | Test wallet operations |
103
-
104
- ```bash
105
- # Check balances
106
- npx tsx scripts/wallet/check-wallet-balances.ts
107
- ```
108
-
109
- ---
110
-
111
- ### `verify/` - API Verification
112
-
113
- | Script | Description |
114
- |--------|-------------|
115
- | `verify-all-apis.ts` | Verify all API endpoints |
116
- | `test-search-mcp.ts` | Test MCP search tools |
117
- | `test-approve-trading.ts` | Test trading approvals |
118
-
119
- ```bash
120
- # Verify all APIs work
121
- npx tsx scripts/verify/verify-all-apis.ts
122
- ```
123
-
124
- ---
125
-
126
- ### `research/` - Market Research
127
-
128
- | Script | Description |
129
- |--------|-------------|
130
- | `research-markets.ts` | ARB/MM/Hybrid market analysis |
131
-
132
- ```bash
133
- # Find arbitrage and MM opportunities
134
- npx tsx scripts/research/research-markets.ts
135
- ```
136
-
137
- ---
138
-
139
- ## Important Concepts
140
-
141
- ### USDC Types
142
-
143
- | Token | Address | Use |
144
- |-------|---------|-----|
145
- | USDC.e (Bridged) | `0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174` | **Required for CTF** |
146
- | Native USDC | `0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359` | Must swap to USDC.e |
147
-
148
- ### Effective Prices
149
-
150
- Polymarket orderbooks have mirroring:
151
- - Buying YES @ P = Selling NO @ (1-P)
152
-
153
- ```
154
- effectiveBuyYes = min(YES.bestAsk, 1 - NO.bestBid)
155
- effectiveBuyNo = min(NO.bestAsk, 1 - YES.bestBid)
156
- ```
157
-
158
- ### Arbitrage Detection
159
-
160
- | Type | Condition | Action |
161
- |------|-----------|--------|
162
- | Long | `effectiveBuyYes + effectiveBuyNo < 1` | Buy both, merge |
163
- | Short | `effectiveSellYes + effectiveSellNo > 1` | Split, sell both |
@@ -1,129 +0,0 @@
1
- #!/usr/bin/env npx tsx
2
- /**
3
- * Approve ERC1155 for selling YES/NO tokens
4
- *
5
- * This sets setApprovalForAll on the Conditional Tokens contract
6
- * to allow the exchanges to transfer your YES/NO tokens.
7
- */
8
-
9
- import { ethers } from 'ethers';
10
- import * as fs from 'fs';
11
- import * as path from 'path';
12
- import { fileURLToPath } from 'url';
13
-
14
- const __filename = fileURLToPath(import.meta.url);
15
- const __dirname = path.dirname(__filename);
16
-
17
- // Read private key
18
- const envPath = path.resolve(__dirname, '../../earning-engine/dashboard-api/.env');
19
- const envContent = fs.readFileSync(envPath, 'utf8');
20
- const match = envContent.match(/^PRIVATE_KEY=(.+)$/m);
21
- const PRIVATE_KEY = match ? match[1].trim() : '';
22
-
23
- if (!PRIVATE_KEY) {
24
- console.error('PRIVATE_KEY not found');
25
- process.exit(1);
26
- }
27
-
28
- // Contract addresses
29
- const CONDITIONAL_TOKENS = '0x4D97DCd97eC945f40cF65F87097ACe5EA0476045';
30
- const CTF_EXCHANGE = '0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E';
31
- const NEG_RISK_CTF_EXCHANGE = '0xC5d563A36AE78145C45a50134d48A1215220f80a';
32
-
33
- const ERC1155_ABI = [
34
- 'function setApprovalForAll(address operator, bool approved) external',
35
- 'function isApprovedForAll(address account, address operator) view returns (bool)',
36
- ];
37
-
38
- async function main() {
39
- console.log('╔════════════════════════════════════════════════════════════════╗');
40
- console.log('║ ERC1155 APPROVAL FOR SELLING YES/NO TOKENS ║');
41
- console.log('╚════════════════════════════════════════════════════════════════╝');
42
- console.log('');
43
-
44
- const rpcs = [
45
- 'https://polygon-bor-rpc.publicnode.com',
46
- 'https://polygon.drpc.org',
47
- 'https://polygon-rpc.com',
48
- ];
49
-
50
- for (const rpc of rpcs) {
51
- console.log(`Trying RPC: ${rpc}`);
52
- try {
53
- const provider = new ethers.providers.JsonRpcProvider({
54
- url: rpc,
55
- timeout: 30000,
56
- });
57
-
58
- const network = await provider.getNetwork();
59
- console.log(`Connected to chain ${network.chainId}`);
60
-
61
- const wallet = new ethers.Wallet(PRIVATE_KEY, provider);
62
- console.log(`Wallet: ${wallet.address}`);
63
- console.log('');
64
-
65
- const conditionalTokens = new ethers.Contract(CONDITIONAL_TOKENS, ERC1155_ABI, wallet);
66
-
67
- const operators = [
68
- { name: 'CTF Exchange', address: CTF_EXCHANGE },
69
- { name: 'Neg Risk CTF Exchange', address: NEG_RISK_CTF_EXCHANGE },
70
- ];
71
-
72
- // Check current approvals
73
- console.log('─── Current ERC1155 Approvals ───');
74
- let needsApproval = [];
75
-
76
- for (const op of operators) {
77
- const isApproved = await conditionalTokens.isApprovedForAll(wallet.address, op.address);
78
- console.log(`${op.name}: ${isApproved ? '✅ Approved' : '❌ Not Approved'}`);
79
- if (!isApproved) {
80
- needsApproval.push(op);
81
- }
82
- }
83
- console.log('');
84
-
85
- if (needsApproval.length === 0) {
86
- console.log('✅ All ERC1155 approvals are set!');
87
- return;
88
- }
89
-
90
- // Approve missing operators
91
- console.log('─── Setting Approvals ───');
92
- const gasPrice = await provider.getGasPrice();
93
- const adjustedGas = gasPrice.mul(2);
94
- console.log(`Gas price: ${ethers.utils.formatUnits(adjustedGas, 'gwei')} Gwei`);
95
- console.log('');
96
-
97
- for (const op of needsApproval) {
98
- console.log(`Approving ${op.name}...`);
99
- try {
100
- const tx = await conditionalTokens.setApprovalForAll(op.address, true, {
101
- gasPrice: adjustedGas,
102
- gasLimit: 100000,
103
- });
104
- console.log(` TX: ${tx.hash}`);
105
- const receipt = await tx.wait();
106
- console.log(` ✅ Confirmed in block ${receipt.blockNumber}`);
107
- } catch (error: any) {
108
- console.log(` ❌ Failed: ${error.message}`);
109
- }
110
- }
111
-
112
- console.log('');
113
- console.log('─── Verifying Approvals ───');
114
- for (const op of operators) {
115
- const isApproved = await conditionalTokens.isApprovedForAll(wallet.address, op.address);
116
- console.log(`${op.name}: ${isApproved ? '✅ Approved' : '❌ Not Approved'}`);
117
- }
118
-
119
- return;
120
- } catch (error: any) {
121
- console.log(`Failed: ${error.message}`);
122
- console.log('');
123
- }
124
- }
125
-
126
- console.log('❌ All RPCs failed!');
127
- }
128
-
129
- main().catch(console.error);