@catalyst-team/poly-sdk 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +354 -78
  3. package/docs/00-design.md +1 -1
  4. package/docs/02-API.md +21 -21
  5. package/docs/arbitrage.md +754 -0
  6. package/docs/reports/smart-money-analysis-2025-12-23-cn.md +840 -0
  7. package/examples/13-arbitrage-service.ts +211 -0
  8. package/examples/README.md +1 -1
  9. package/package.json +19 -19
  10. package/scripts/arb/faze-bo3-arb.ts +385 -0
  11. package/scripts/arb/settle-position.ts +190 -0
  12. package/scripts/arb/token-rebalancer.ts +420 -0
  13. package/scripts/verify/verify-all-apis.ts +1 -1
  14. package/src/clients/clob-api.ts +1 -1
  15. package/src/clients/gamma-api.ts +1 -1
  16. package/src/core/cache-adapter-bridge.ts +1 -1
  17. package/src/core/types.ts +3 -3
  18. package/src/core/unified-cache.ts +1 -1
  19. package/src/index.ts +25 -19
  20. package/src/services/arbitrage-service.ts +1807 -0
  21. package/.env +0 -0
  22. package/dist/__tests__/clob-api.test.d.ts +0 -5
  23. package/dist/__tests__/clob-api.test.d.ts.map +0 -1
  24. package/dist/__tests__/clob-api.test.js +0 -240
  25. package/dist/__tests__/clob-api.test.js.map +0 -1
  26. package/dist/__tests__/integration/bridge-client.integration.test.d.ts +0 -11
  27. package/dist/__tests__/integration/bridge-client.integration.test.d.ts.map +0 -1
  28. package/dist/__tests__/integration/bridge-client.integration.test.js +0 -260
  29. package/dist/__tests__/integration/bridge-client.integration.test.js.map +0 -1
  30. package/dist/__tests__/integration/clob-api.integration.test.d.ts +0 -13
  31. package/dist/__tests__/integration/clob-api.integration.test.d.ts.map +0 -1
  32. package/dist/__tests__/integration/clob-api.integration.test.js +0 -170
  33. package/dist/__tests__/integration/clob-api.integration.test.js.map +0 -1
  34. package/dist/__tests__/integration/ctf-client.integration.test.d.ts +0 -17
  35. package/dist/__tests__/integration/ctf-client.integration.test.d.ts.map +0 -1
  36. package/dist/__tests__/integration/ctf-client.integration.test.js +0 -234
  37. package/dist/__tests__/integration/ctf-client.integration.test.js.map +0 -1
  38. package/dist/__tests__/integration/data-api.integration.test.d.ts +0 -9
  39. package/dist/__tests__/integration/data-api.integration.test.d.ts.map +0 -1
  40. package/dist/__tests__/integration/data-api.integration.test.js +0 -161
  41. package/dist/__tests__/integration/data-api.integration.test.js.map +0 -1
  42. package/dist/__tests__/integration/gamma-api.integration.test.d.ts +0 -9
  43. package/dist/__tests__/integration/gamma-api.integration.test.d.ts.map +0 -1
  44. package/dist/__tests__/integration/gamma-api.integration.test.js +0 -170
  45. package/dist/__tests__/integration/gamma-api.integration.test.js.map +0 -1
  46. package/dist/__tests__/test-utils.d.ts +0 -92
  47. package/dist/__tests__/test-utils.d.ts.map +0 -1
  48. package/dist/__tests__/test-utils.js +0 -143
  49. package/dist/__tests__/test-utils.js.map +0 -1
  50. package/dist/clients/bridge-client.d.ts +0 -388
  51. package/dist/clients/bridge-client.d.ts.map +0 -1
  52. package/dist/clients/bridge-client.js +0 -587
  53. package/dist/clients/bridge-client.js.map +0 -1
  54. package/dist/clients/clob-api.d.ts +0 -318
  55. package/dist/clients/clob-api.d.ts.map +0 -1
  56. package/dist/clients/clob-api.js +0 -388
  57. package/dist/clients/clob-api.js.map +0 -1
  58. package/dist/clients/ctf-client.d.ts +0 -473
  59. package/dist/clients/ctf-client.d.ts.map +0 -1
  60. package/dist/clients/ctf-client.js +0 -915
  61. package/dist/clients/ctf-client.js.map +0 -1
  62. package/dist/clients/data-api.d.ts +0 -134
  63. package/dist/clients/data-api.d.ts.map +0 -1
  64. package/dist/clients/data-api.js +0 -265
  65. package/dist/clients/data-api.js.map +0 -1
  66. package/dist/clients/gamma-api.d.ts +0 -401
  67. package/dist/clients/gamma-api.d.ts.map +0 -1
  68. package/dist/clients/gamma-api.js +0 -352
  69. package/dist/clients/gamma-api.js.map +0 -1
  70. package/dist/clients/trading-client.d.ts +0 -252
  71. package/dist/clients/trading-client.d.ts.map +0 -1
  72. package/dist/clients/trading-client.js +0 -543
  73. package/dist/clients/trading-client.js.map +0 -1
  74. package/dist/clients/websocket-manager.d.ts +0 -100
  75. package/dist/clients/websocket-manager.d.ts.map +0 -1
  76. package/dist/clients/websocket-manager.js +0 -193
  77. package/dist/clients/websocket-manager.js.map +0 -1
  78. package/dist/core/cache-adapter-bridge.d.ts +0 -36
  79. package/dist/core/cache-adapter-bridge.d.ts.map +0 -1
  80. package/dist/core/cache-adapter-bridge.js +0 -81
  81. package/dist/core/cache-adapter-bridge.js.map +0 -1
  82. package/dist/core/cache.d.ts +0 -40
  83. package/dist/core/cache.d.ts.map +0 -1
  84. package/dist/core/cache.js +0 -71
  85. package/dist/core/cache.js.map +0 -1
  86. package/dist/core/errors.d.ts +0 -38
  87. package/dist/core/errors.d.ts.map +0 -1
  88. package/dist/core/errors.js +0 -84
  89. package/dist/core/errors.js.map +0 -1
  90. package/dist/core/rate-limiter.d.ts +0 -31
  91. package/dist/core/rate-limiter.d.ts.map +0 -1
  92. package/dist/core/rate-limiter.js +0 -70
  93. package/dist/core/rate-limiter.js.map +0 -1
  94. package/dist/core/types.d.ts +0 -314
  95. package/dist/core/types.d.ts.map +0 -1
  96. package/dist/core/types.js +0 -19
  97. package/dist/core/types.js.map +0 -1
  98. package/dist/core/unified-cache.d.ts +0 -63
  99. package/dist/core/unified-cache.d.ts.map +0 -1
  100. package/dist/core/unified-cache.js +0 -114
  101. package/dist/core/unified-cache.js.map +0 -1
  102. package/dist/index.d.ts +0 -94
  103. package/dist/index.d.ts.map +0 -1
  104. package/dist/index.js +0 -258
  105. package/dist/index.js.map +0 -1
  106. package/dist/mcp/errors.d.ts +0 -33
  107. package/dist/mcp/errors.d.ts.map +0 -1
  108. package/dist/mcp/errors.js +0 -86
  109. package/dist/mcp/errors.js.map +0 -1
  110. package/dist/mcp/index.d.ts +0 -62
  111. package/dist/mcp/index.d.ts.map +0 -1
  112. package/dist/mcp/index.js +0 -173
  113. package/dist/mcp/index.js.map +0 -1
  114. package/dist/mcp/server.d.ts +0 -17
  115. package/dist/mcp/server.d.ts.map +0 -1
  116. package/dist/mcp/server.js +0 -155
  117. package/dist/mcp/server.js.map +0 -1
  118. package/dist/mcp/tools/guide.d.ts +0 -12
  119. package/dist/mcp/tools/guide.d.ts.map +0 -1
  120. package/dist/mcp/tools/guide.js +0 -801
  121. package/dist/mcp/tools/guide.js.map +0 -1
  122. package/dist/mcp/tools/index.d.ts +0 -11
  123. package/dist/mcp/tools/index.d.ts.map +0 -1
  124. package/dist/mcp/tools/index.js +0 -27
  125. package/dist/mcp/tools/index.js.map +0 -1
  126. package/dist/mcp/tools/market.d.ts +0 -11
  127. package/dist/mcp/tools/market.d.ts.map +0 -1
  128. package/dist/mcp/tools/market.js +0 -314
  129. package/dist/mcp/tools/market.js.map +0 -1
  130. package/dist/mcp/tools/order.d.ts +0 -10
  131. package/dist/mcp/tools/order.d.ts.map +0 -1
  132. package/dist/mcp/tools/order.js +0 -258
  133. package/dist/mcp/tools/order.js.map +0 -1
  134. package/dist/mcp/tools/trade.d.ts +0 -38
  135. package/dist/mcp/tools/trade.d.ts.map +0 -1
  136. package/dist/mcp/tools/trade.js +0 -314
  137. package/dist/mcp/tools/trade.js.map +0 -1
  138. package/dist/mcp/tools/trader.d.ts +0 -11
  139. package/dist/mcp/tools/trader.d.ts.map +0 -1
  140. package/dist/mcp/tools/trader.js +0 -277
  141. package/dist/mcp/tools/trader.js.map +0 -1
  142. package/dist/mcp/tools/wallet.d.ts +0 -274
  143. package/dist/mcp/tools/wallet.d.ts.map +0 -1
  144. package/dist/mcp/tools/wallet.js +0 -579
  145. package/dist/mcp/tools/wallet.js.map +0 -1
  146. package/dist/mcp/types.d.ts +0 -413
  147. package/dist/mcp/types.d.ts.map +0 -1
  148. package/dist/mcp/types.js +0 -5
  149. package/dist/mcp/types.js.map +0 -1
  150. package/dist/services/authorization-service.d.ts +0 -97
  151. package/dist/services/authorization-service.d.ts.map +0 -1
  152. package/dist/services/authorization-service.js +0 -279
  153. package/dist/services/authorization-service.js.map +0 -1
  154. package/dist/services/market-service.d.ts +0 -108
  155. package/dist/services/market-service.d.ts.map +0 -1
  156. package/dist/services/market-service.js +0 -458
  157. package/dist/services/market-service.js.map +0 -1
  158. package/dist/services/realtime-service.d.ts +0 -82
  159. package/dist/services/realtime-service.d.ts.map +0 -1
  160. package/dist/services/realtime-service.js +0 -150
  161. package/dist/services/realtime-service.js.map +0 -1
  162. package/dist/services/swap-service.d.ts +0 -217
  163. package/dist/services/swap-service.d.ts.map +0 -1
  164. package/dist/services/swap-service.js +0 -695
  165. package/dist/services/swap-service.js.map +0 -1
  166. package/dist/services/wallet-service.d.ts +0 -94
  167. package/dist/services/wallet-service.d.ts.map +0 -1
  168. package/dist/services/wallet-service.js +0 -173
  169. package/dist/services/wallet-service.js.map +0 -1
  170. package/dist/utils/price-utils.d.ts +0 -153
  171. package/dist/utils/price-utils.d.ts.map +0 -1
  172. package/dist/utils/price-utils.js +0 -236
  173. package/dist/utils/price-utils.js.map +0 -1
  174. package/docs/01-mcp.md +0 -2041
  175. package/docs/e2e/01-trader-tools.md +0 -159
  176. package/docs/e2e/02-market-tools.md +0 -180
  177. package/docs/e2e/03-order-tools.md +0 -166
  178. package/docs/e2e/04-wallet-tools.md +0 -224
  179. package/docs/e2e/05-trading-tools.md +0 -327
  180. package/docs/e2e/06-integration-scenarios.md +0 -481
  181. package/docs/e2e/coordinator.md +0 -376
  182. package/scripts/truth.md +0 -440
  183. package/src/mcp/README.md +0 -380
  184. package/src/mcp/errors.ts +0 -124
  185. package/src/mcp/index.ts +0 -309
  186. package/src/mcp/server.ts +0 -183
  187. package/src/mcp/tools/guide.ts +0 -821
  188. package/src/mcp/tools/index.ts +0 -73
  189. package/src/mcp/tools/market.ts +0 -363
  190. package/src/mcp/tools/order.ts +0 -326
  191. package/src/mcp/tools/trade.ts +0 -417
  192. package/src/mcp/tools/trader.ts +0 -322
  193. package/src/mcp/tools/wallet.ts +0 -683
  194. package/src/mcp/types.ts +0 -472
@@ -0,0 +1,190 @@
1
+ #!/usr/bin/env npx tsx
2
+ /**
3
+ * Settle Position - 市场结束后清算脚本
4
+ *
5
+ * 功能:
6
+ * 1. 查看当前持仓 (YES + NO)
7
+ * 2. Merge 所有配对的 tokens → 回收 USDC
8
+ * 3. 显示剩余的单边 tokens(等市场结算后 redeem)
9
+ *
10
+ * 用法:
11
+ * # 查看持仓
12
+ * POLY_PRIVKEY=0x... npx tsx scripts/v2/settle-position.ts
13
+ *
14
+ * # 执行 merge
15
+ * POLY_PRIVKEY=0x... npx tsx scripts/v2/settle-position.ts --merge
16
+ *
17
+ * # 指定市场
18
+ * POLY_PRIVKEY=0x... npx tsx scripts/v2/settle-position.ts --merge --market map1
19
+ * POLY_PRIVKEY=0x... npx tsx scripts/v2/settle-position.ts --merge --market bo3
20
+ */
21
+
22
+ import { CTFClient } from '../../src/index.js';
23
+
24
+ // ============== Market Configurations ==============
25
+ const MARKETS = {
26
+ map1: {
27
+ name: 'CS2: FaZe vs Passion UA - Map 1 Winner',
28
+ conditionId: '0x8307e29e55c51624bf7dc2448f640902deda12a798bf4f9389f50effed5ca8e3',
29
+ yesTokenId: '43483263124644478520592164117863889505064690344162739837819619686304683165329',
30
+ noTokenId: '82507526040280959004054227385878378176592321458993996786469194286964091170010',
31
+ outcomes: ['FaZe', 'Passion UA'],
32
+ },
33
+ map2: {
34
+ name: 'CS2: FaZe vs Passion UA - Map 2 Winner',
35
+ conditionId: '0x42b6312bfef1d4d996239fb2975a0201fed896beb9020c7117222cb9c63fb8a0',
36
+ yesTokenId: '98500029478540181701955943314626655950009912089703692217392489784365890894034',
37
+ noTokenId: '6600108613901488464286039277243478584438419930859899257744834420246596461241',
38
+ outcomes: ['FaZe', 'Passion UA'],
39
+ },
40
+ bo3: {
41
+ name: 'CS2: FaZe vs Passion UA (BO3)',
42
+ conditionId: '0x5ac2e92a82ea41ec3a4d9332d323d8d198a8c9acc732b7e6373bd61f45e1df49',
43
+ yesTokenId: '89062136554637645106569570664838812035010963361832797298254486917225439629146',
44
+ noTokenId: '54956090965819006918015199317329813503156478664679332459223691084797135448319',
45
+ outcomes: ['FaZe', 'Passion UA'],
46
+ },
47
+ cs2_b8_navi: {
48
+ name: 'CS2: B8 vs Navi - Map 2 Winner',
49
+ conditionId: '0xed4f4efc641b2cc65d172115527298780c2763e38392411080446d00624de188',
50
+ yesTokenId: '98356217078946559304776425059619763149078508549007892630440851408503070133487',
51
+ noTokenId: '9564639153871441133338469591798901837693814970886235799643024453135563888010',
52
+ outcomes: ['B8', 'Natus Vincere'],
53
+ },
54
+ };
55
+
56
+ // ============== Parse Arguments ==============
57
+ const args = process.argv.slice(2);
58
+ const EXECUTE_MERGE = args.includes('--merge');
59
+ const marketIdx = args.indexOf('--market');
60
+ const MARKET_KEY = marketIdx !== -1 ? args[marketIdx + 1] : 'all';
61
+
62
+ const PRIVATE_KEY = process.env.POLY_PRIVKEY || '';
63
+ const RPC_URL = process.env.POLYGON_RPC_URL || 'https://polygon-rpc.com';
64
+
65
+ // ============== Main ==============
66
+ async function main() {
67
+ console.log('╔════════════════════════════════════════════════════════════════╗');
68
+ console.log('║ SETTLE POSITION - 清算脚本 ║');
69
+ console.log('╚════════════════════════════════════════════════════════════════╝');
70
+ console.log();
71
+
72
+ if (!PRIVATE_KEY) {
73
+ console.error('Error: POLY_PRIVKEY environment variable is required');
74
+ process.exit(1);
75
+ }
76
+
77
+ // Initialize clients
78
+ const ctf = new CTFClient({ privateKey: PRIVATE_KEY, rpcUrl: RPC_URL });
79
+
80
+ console.log(`Wallet: ${ctf.getAddress()}`);
81
+ console.log(`Mode: ${EXECUTE_MERGE ? 'MERGE (will execute)' : 'VIEW ONLY'}`);
82
+ console.log();
83
+
84
+ // Get USDC balance
85
+ const usdcBalance = await ctf.getUsdcBalance();
86
+ console.log(`USDC.e Balance: $${parseFloat(usdcBalance).toFixed(2)}`);
87
+ console.log();
88
+
89
+ // Process markets
90
+ const marketsToProcess = MARKET_KEY === 'all'
91
+ ? Object.entries(MARKETS)
92
+ : [[MARKET_KEY, MARKETS[MARKET_KEY as keyof typeof MARKETS]]].filter(([_, m]) => m);
93
+
94
+ if (marketsToProcess.length === 0) {
95
+ console.error(`Unknown market: ${MARKET_KEY}`);
96
+ console.log(`Available markets: ${Object.keys(MARKETS).join(', ')}`);
97
+ process.exit(1);
98
+ }
99
+
100
+ let totalMerged = 0;
101
+ let totalUnpairedYes = 0;
102
+ let totalUnpairedNo = 0;
103
+
104
+ for (const [key, market] of marketsToProcess) {
105
+ if (!market) continue;
106
+
107
+ console.log('═══════════════════════════════════════════════════════════════');
108
+ console.log(`Market: ${market.name}`);
109
+ console.log(`Condition: ${market.conditionId.slice(0, 20)}...`);
110
+ console.log();
111
+
112
+ // Get token balances
113
+ const tokenIds = { yesTokenId: market.yesTokenId, noTokenId: market.noTokenId };
114
+ const positions = await ctf.getPositionBalanceByTokenIds(market.conditionId, tokenIds);
115
+ const yesBalance = parseFloat(positions.yesBalance);
116
+ const noBalance = parseFloat(positions.noBalance);
117
+
118
+ console.log(` ${market.outcomes[0]} (YES): ${yesBalance.toFixed(6)}`);
119
+ console.log(` ${market.outcomes[1]} (NO): ${noBalance.toFixed(6)}`);
120
+
121
+ // Calculate pairs and unpaired
122
+ const pairs = Math.min(yesBalance, noBalance);
123
+ const unpairedYes = yesBalance - pairs;
124
+ const unpairedNo = noBalance - pairs;
125
+
126
+ console.log();
127
+ console.log(` Paired tokens: ${pairs.toFixed(6)} (can merge → $${pairs.toFixed(2)} USDC)`);
128
+
129
+ if (unpairedYes > 0.001) {
130
+ console.log(` ⚠️ Unpaired YES: ${unpairedYes.toFixed(6)} (wait for market settlement to redeem if ${market.outcomes[0]} wins)`);
131
+ totalUnpairedYes += unpairedYes;
132
+ }
133
+ if (unpairedNo > 0.001) {
134
+ console.log(` ⚠️ Unpaired NO: ${unpairedNo.toFixed(6)} (wait for market settlement to redeem if ${market.outcomes[1]} wins)`);
135
+ totalUnpairedNo += unpairedNo;
136
+ }
137
+
138
+ // Execute merge if requested
139
+ if (EXECUTE_MERGE && pairs >= 1) {
140
+ const mergeAmount = Math.floor(pairs * 1e6) / 1e6;
141
+ console.log();
142
+ console.log(` 🔄 Merging ${mergeAmount.toFixed(6)} token pairs...`);
143
+
144
+ try {
145
+ // Use mergeByTokenIds to bypass the deprecated getPositionBalance check
146
+ const result = await ctf.mergeByTokenIds(market.conditionId, tokenIds, mergeAmount.toString());
147
+ console.log(` ✅ Merge TX: ${result.txHash}`);
148
+ console.log(` ✅ Recovered: $${mergeAmount.toFixed(2)} USDC`);
149
+ totalMerged += mergeAmount;
150
+ } catch (error: any) {
151
+ console.log(` ❌ Merge failed: ${error.message}`);
152
+ }
153
+ } else if (pairs >= 1) {
154
+ console.log();
155
+ console.log(` 💡 Run with --merge to recover $${pairs.toFixed(2)} USDC`);
156
+ }
157
+
158
+ console.log();
159
+ }
160
+
161
+ // Summary
162
+ console.log('═══════════════════════════════════════════════════════════════');
163
+ console.log('SUMMARY');
164
+ console.log('═══════════════════════════════════════════════════════════════');
165
+
166
+ if (EXECUTE_MERGE) {
167
+ console.log(`Total Merged: $${totalMerged.toFixed(2)} USDC`);
168
+ const newUsdcBalance = await ctf.getUsdcBalance();
169
+ console.log(`New USDC.e Balance: $${parseFloat(newUsdcBalance).toFixed(2)}`);
170
+ }
171
+
172
+ if (totalUnpairedYes > 0.001 || totalUnpairedNo > 0.001) {
173
+ console.log();
174
+ console.log('Unpaired tokens (waiting for market settlement):');
175
+ if (totalUnpairedYes > 0.001) {
176
+ console.log(` YES tokens: ${totalUnpairedYes.toFixed(6)}`);
177
+ }
178
+ if (totalUnpairedNo > 0.001) {
179
+ console.log(` NO tokens: ${totalUnpairedNo.toFixed(6)}`);
180
+ }
181
+ console.log();
182
+ console.log('Note: Unpaired tokens can be redeemed after market settles');
183
+ console.log(' - If your outcome wins: redeem for $1 per token');
184
+ console.log(' - If your outcome loses: tokens have no value');
185
+ }
186
+
187
+ console.log();
188
+ }
189
+
190
+ main().catch(console.error);
@@ -0,0 +1,420 @@
1
+ #!/usr/bin/env npx tsx
2
+ /**
3
+ * Token Rebalancer V2 - 动态平衡 USDC 和 Token 的持有量
4
+ *
5
+ * 核心功能:
6
+ * 1. 维持 USDC + Token 的目标比例
7
+ * 2. ⚠️ 关键:保持 YES 和 NO 数量一致,避免风险敞口
8
+ *
9
+ * 资金模型:
10
+ * - 1 USDC split → 1 YES + 1 NO
11
+ * - 1 YES + 1 NO merge → 1 USDC
12
+ * - 所以 N YES + N NO 配对价值 = N USDC
13
+ *
14
+ * 策略 (以 50% USDC 为例, 1000u 总资金):
15
+ * - 500 USDC (50%)
16
+ * - 500 YES + 500 NO (配对价值 = 500 USDC)
17
+ * - 总价值 = 500 + 500 = 1000 USDC
18
+ *
19
+ * - Token 不足时自动 Split 补充
20
+ * - Token 过多时自动 Merge 回收
21
+ * - YES ≠ NO 时,卖出多余的一方来平衡
22
+ *
23
+ * 用法:
24
+ * POLY_PRIVKEY=0x... npx tsx scripts/v2/token-rebalancer.ts [options]
25
+ *
26
+ * Options:
27
+ * --condition <id> Condition ID
28
+ * --yes-token <id> YES token ID
29
+ * --no-token <id> NO token ID
30
+ * --total <amount> Total capital in USDC (default: auto-detect)
31
+ * --usdc-ratio <n> USDC ratio 0-1 (default: 0.5)
32
+ * --interval <ms> Check interval in ms (default: 5000)
33
+ * --threshold <n> Rebalance threshold 0-1 (default: 0.2)
34
+ * --imbalance-threshold Max YES/NO difference before fix (default: 5)
35
+ * --dry-run Show what would happen without executing
36
+ */
37
+
38
+ import {
39
+ CTFClient,
40
+ TradingClient,
41
+ RateLimiter,
42
+ } from '../../src/index.js';
43
+
44
+ // ============== Market Configuration ==============
45
+ // Default: FaZe vs Passion UA - Map 2 Winner
46
+ const DEFAULT_CONFIG = {
47
+ conditionId: '0x42b6312bfef1d4d996239fb2975a0201fed896beb9020c7117222cb9c63fb8a0',
48
+ yesTokenId: '98500029478540181701955943314626655950009912089703692217392489784365890894034',
49
+ noTokenId: '6600108613901488464286039277243478584438419930859899257744834420246596461241',
50
+ name: 'FaZe vs Passion UA - Map 2'
51
+ };
52
+
53
+ // ============== Parse Arguments ==============
54
+ const args = process.argv.slice(2);
55
+
56
+ function getArg(name: string, defaultValue?: string): string | undefined {
57
+ const idx = args.indexOf(`--${name}`);
58
+ if (idx !== -1 && args[idx + 1]) {
59
+ return args[idx + 1];
60
+ }
61
+ return defaultValue;
62
+ }
63
+
64
+ const CONDITION_ID = getArg('condition', DEFAULT_CONFIG.conditionId)!;
65
+ const YES_TOKEN_ID = getArg('yes-token', DEFAULT_CONFIG.yesTokenId)!;
66
+ const NO_TOKEN_ID = getArg('no-token', DEFAULT_CONFIG.noTokenId)!;
67
+ const TOTAL_CAPITAL = getArg('total') ? parseFloat(getArg('total')!) : undefined;
68
+ const USDC_RATIO = parseFloat(getArg('usdc-ratio', '0.5')!);
69
+ const CHECK_INTERVAL = parseInt(getArg('interval', '5000')!);
70
+ const REBALANCE_THRESHOLD = parseFloat(getArg('threshold', '0.2')!);
71
+ const IMBALANCE_THRESHOLD = parseFloat(getArg('imbalance-threshold', '5')!);
72
+ const DRY_RUN = args.includes('--dry-run');
73
+
74
+ // Token ratio: YES and NO should each equal the non-USDC portion
75
+ // Because: 1 USDC = 1 YES + 1 NO, so paired tokens (N YES + N NO) = N USDC value
76
+ // Example with 1000u total and 50% USDC:
77
+ // - 500 USDC
78
+ // - 500 YES + 500 NO (paired value = 500 USDC)
79
+ // - Total value = 500 + 500 = 1000 USDC
80
+ const TOKEN_RATIO = 1 - USDC_RATIO;
81
+
82
+ // Minimum amounts
83
+ const MIN_REBALANCE_AMOUNT = 5;
84
+ const MIN_SELL_AMOUNT = 5;
85
+
86
+ // ============== State ==============
87
+ interface Balance {
88
+ usdc: number;
89
+ yes: number;
90
+ no: number;
91
+ total: number;
92
+ }
93
+
94
+ type ActionType = 'split' | 'merge' | 'sell_yes' | 'sell_no' | 'none';
95
+
96
+ interface RebalanceAction {
97
+ type: ActionType;
98
+ amount: number;
99
+ reason: string;
100
+ priority: number; // Higher = more urgent
101
+ }
102
+
103
+ // ============== Main ==============
104
+ async function main() {
105
+ console.log('╔════════════════════════════════════════════════════════════════╗');
106
+ console.log('║ TOKEN REBALANCER V2 (with Risk Control) ║');
107
+ console.log('╚════════════════════════════════════════════════════════════════╝');
108
+ console.log();
109
+
110
+ // Initialize clients
111
+ const privateKey = process.env.POLY_PRIVKEY;
112
+ if (!privateKey) {
113
+ console.error('Error: POLY_PRIVKEY environment variable is required');
114
+ process.exit(1);
115
+ }
116
+
117
+ const ctf = new CTFClient({
118
+ privateKey,
119
+ rpcUrl: 'https://polygon-rpc.com',
120
+ });
121
+
122
+ // Initialize trading client for selling excess tokens
123
+ const rateLimiter = new RateLimiter();
124
+ const tradingClient = new TradingClient(rateLimiter, {
125
+ privateKey,
126
+ chainId: 137,
127
+ });
128
+ await tradingClient.initialize();
129
+
130
+ console.log(`Wallet: ${ctf.getAddress()}`);
131
+ console.log(`Condition: ${CONDITION_ID.slice(0, 20)}...`);
132
+ console.log(`Target: ${(USDC_RATIO * 100).toFixed(0)}% USDC + ${(TOKEN_RATIO * 100).toFixed(0)}% Tokens (${(TOKEN_RATIO * 100).toFixed(0)} YES + ${(TOKEN_RATIO * 100).toFixed(0)} NO paired)`);
133
+ console.log(`Rebalance Threshold: ${(REBALANCE_THRESHOLD * 100).toFixed(0)}%`);
134
+ console.log(`Imbalance Threshold: ${IMBALANCE_THRESHOLD} tokens (YES must equal NO)`);
135
+ console.log(`Check Interval: ${CHECK_INTERVAL}ms`);
136
+ console.log(`Mode: ${DRY_RUN ? 'DRY RUN (no execution)' : 'LIVE'}`);
137
+ console.log();
138
+
139
+ // Get initial balance
140
+ const balance = await getBalance(ctf, tradingClient);
141
+ const totalCapital = TOTAL_CAPITAL || balance.total;
142
+
143
+ console.log(`Total Capital: $${totalCapital.toFixed(2)}`);
144
+ console.log(`Initial: USDC=${balance.usdc.toFixed(2)} YES=${balance.yes.toFixed(2)} NO=${balance.no.toFixed(2)}`);
145
+
146
+ const initialImbalance = Math.abs(balance.yes - balance.no);
147
+ if (initialImbalance > IMBALANCE_THRESHOLD) {
148
+ console.log(`\n⚠️ WARNING: Token imbalance detected! YES-NO=${(balance.yes - balance.no).toFixed(2)}`);
149
+ console.log(` This creates risk exposure. Will auto-fix by selling excess tokens.`);
150
+ }
151
+
152
+ console.log();
153
+ console.log('═══════════════════════════════════════════════════════════════');
154
+ console.log('Starting rebalancer loop...');
155
+ console.log();
156
+
157
+ // Main loop
158
+ let lastActionTime = 0;
159
+ const MIN_ACTION_INTERVAL = 10000; // Wait at least 10s between actions
160
+ const CONFIRM_DELAY = 5000; // Wait 5s before confirming imbalance action
161
+ const BALANCE_CHANGE_THRESHOLD = 1; // If balance changes by more than this, reset confirmation
162
+ let pendingImbalanceAction: RebalanceAction | null = null;
163
+ let pendingImbalanceTime = 0;
164
+ let lastConfirmBalance: Balance | null = null;
165
+
166
+ while (true) {
167
+ try {
168
+ const currentBalance = await getBalance(ctf, tradingClient);
169
+ const actions = calculateRebalanceActions(currentBalance, totalCapital);
170
+
171
+ // Get highest priority action
172
+ const action = actions.sort((a, b) => b.priority - a.priority)[0];
173
+
174
+ // Display status
175
+ const usdcPct = (currentBalance.usdc / totalCapital * 100).toFixed(1);
176
+ const yesPct = (currentBalance.yes / totalCapital * 100).toFixed(1);
177
+ const noPct = (currentBalance.no / totalCapital * 100).toFixed(1);
178
+ const imbalance = currentBalance.yes - currentBalance.no;
179
+ const imbalanceStr = imbalance >= 0 ? `+${imbalance.toFixed(1)}` : imbalance.toFixed(1);
180
+
181
+ const timestamp = new Date().toLocaleTimeString('en-US', { hour12: false });
182
+ const statusLine = `[${timestamp}] USDC: $${currentBalance.usdc.toFixed(0)} (${usdcPct}%) | YES: ${currentBalance.yes.toFixed(0)} (${yesPct}%) | NO: ${currentBalance.no.toFixed(0)} (${noPct}%) | Δ: ${imbalanceStr} | ${action.type}`;
183
+
184
+ process.stdout.write(`\r${statusLine.padEnd(130)}`);
185
+
186
+ // Execute action if needed
187
+ if (action.type !== 'none' && action.amount >= MIN_SELL_AMOUNT) {
188
+ const now = Date.now();
189
+ if (now - lastActionTime < MIN_ACTION_INTERVAL) {
190
+ await sleep(CHECK_INTERVAL);
191
+ continue;
192
+ }
193
+
194
+ // For imbalance actions (sell_yes/sell_no), require confirmation after delay
195
+ // This prevents reacting to temporary imbalance during CLOB settlement
196
+ if (action.type === 'sell_yes' || action.type === 'sell_no') {
197
+ // Check if balance has changed significantly since last check
198
+ const balanceChanged = lastConfirmBalance && (
199
+ Math.abs(currentBalance.yes - lastConfirmBalance.yes) > BALANCE_CHANGE_THRESHOLD ||
200
+ Math.abs(currentBalance.no - lastConfirmBalance.no) > BALANCE_CHANGE_THRESHOLD
201
+ );
202
+
203
+ if (!pendingImbalanceAction || pendingImbalanceAction.type !== action.type || balanceChanged) {
204
+ // New imbalance detected or balance changed, (re)start waiting
205
+ if (balanceChanged && pendingImbalanceAction) {
206
+ console.log(`\n⚠️ Balance changed during confirmation, restarting ${CONFIRM_DELAY/1000}s wait...`);
207
+ } else if (!pendingImbalanceAction) {
208
+ console.log(`\n⏳ Imbalance detected (${action.type}), waiting ${CONFIRM_DELAY/1000}s to confirm...`);
209
+ }
210
+ pendingImbalanceAction = action;
211
+ pendingImbalanceTime = now;
212
+ lastConfirmBalance = { ...currentBalance };
213
+ await sleep(CHECK_INTERVAL);
214
+ continue;
215
+ } else if (now - pendingImbalanceTime < CONFIRM_DELAY) {
216
+ // Still waiting for confirmation
217
+ await sleep(CHECK_INTERVAL);
218
+ continue;
219
+ }
220
+ // Confirmed - imbalance persisted for CONFIRM_DELAY with stable balance, proceed with action
221
+ console.log(`\n✓ Imbalance confirmed after ${CONFIRM_DELAY/1000}s delay (balance stable)`);
222
+ pendingImbalanceAction = null;
223
+ lastConfirmBalance = null;
224
+ }
225
+
226
+ console.log(); // New line for action log
227
+ console.log(`\n🔄 Action: ${action.type.toUpperCase()} ${action.amount.toFixed(2)}`);
228
+ console.log(` Reason: ${action.reason}`);
229
+ console.log(` Priority: ${action.priority}`);
230
+
231
+ if (!DRY_RUN) {
232
+ try {
233
+ let success = false;
234
+
235
+ switch (action.type) {
236
+ case 'split':
237
+ const splitResult = await ctf.split(CONDITION_ID, action.amount.toString());
238
+ console.log(` ✅ Split TX: ${splitResult.txHash}`);
239
+ success = true;
240
+ break;
241
+
242
+ case 'merge':
243
+ const mergeResult = await ctf.merge(CONDITION_ID, action.amount.toString());
244
+ console.log(` ✅ Merge TX: ${mergeResult.txHash}`);
245
+ success = true;
246
+ break;
247
+
248
+ case 'sell_yes':
249
+ const sellYesResult = await tradingClient.createMarketOrder({
250
+ tokenId: YES_TOKEN_ID,
251
+ side: 'SELL',
252
+ amount: action.amount,
253
+ orderType: 'FOK',
254
+ });
255
+ if (sellYesResult.success) {
256
+ console.log(` ✅ Sold ${action.amount.toFixed(2)} YES tokens`);
257
+ success = true;
258
+ } else {
259
+ console.log(` ❌ Sell YES failed: ${sellYesResult.errorMsg || 'unknown error'}`);
260
+ }
261
+ break;
262
+
263
+ case 'sell_no':
264
+ const sellNoResult = await tradingClient.createMarketOrder({
265
+ tokenId: NO_TOKEN_ID,
266
+ side: 'SELL',
267
+ amount: action.amount,
268
+ orderType: 'FOK',
269
+ });
270
+ if (sellNoResult.success) {
271
+ console.log(` ✅ Sold ${action.amount.toFixed(2)} NO tokens`);
272
+ success = true;
273
+ } else {
274
+ console.log(` ❌ Sell NO failed: ${sellNoResult.errorMsg || 'unknown error'}`);
275
+ }
276
+ break;
277
+ }
278
+
279
+ if (success) {
280
+ lastActionTime = now;
281
+ }
282
+ } catch (error: any) {
283
+ console.log(` ❌ Failed: ${error.message}`);
284
+ }
285
+ } else {
286
+ console.log(` [DRY RUN] Would execute ${action.type}`);
287
+ }
288
+ console.log();
289
+ }
290
+
291
+ await sleep(CHECK_INTERVAL);
292
+ } catch (error: any) {
293
+ console.error(`\nError: ${error.message}`);
294
+ await sleep(CHECK_INTERVAL);
295
+ }
296
+ }
297
+ }
298
+
299
+ async function getBalance(ctf: CTFClient, _tradingClient: TradingClient): Promise<Balance> {
300
+ // Get USDC.e balance
301
+ const usdcBalance = await ctf.getUsdcBalance();
302
+ const usdc = parseFloat(usdcBalance);
303
+
304
+ // Get token balances using getPositionBalanceByTokenIds
305
+ const tokenIds = { yesTokenId: YES_TOKEN_ID, noTokenId: NO_TOKEN_ID };
306
+ const positions = await ctf.getPositionBalanceByTokenIds(CONDITION_ID, tokenIds);
307
+
308
+ const yes = parseFloat(positions.yesBalance);
309
+ const no = parseFloat(positions.noBalance);
310
+
311
+ // Total = USDC + min(YES, NO) as paired tokens
312
+ const pairedTokens = Math.min(yes, no);
313
+ const total = usdc + pairedTokens;
314
+
315
+ return { usdc, yes, no, total };
316
+ }
317
+
318
+ function calculateRebalanceActions(balance: Balance, totalCapital: number): RebalanceAction[] {
319
+ const actions: RebalanceAction[] = [];
320
+
321
+ const targetUsdc = totalCapital * USDC_RATIO;
322
+ const targetToken = totalCapital * TOKEN_RATIO;
323
+
324
+ const usdcDiff = balance.usdc - targetUsdc;
325
+ const yesDiff = balance.yes - targetToken;
326
+ const noDiff = balance.no - targetToken;
327
+ const tokenImbalance = balance.yes - balance.no;
328
+
329
+ // ============================================
330
+ // PRIORITY 1: Fix YES/NO imbalance (HIGHEST)
331
+ // This is critical for risk management!
332
+ // ============================================
333
+ if (Math.abs(tokenImbalance) > IMBALANCE_THRESHOLD) {
334
+ if (tokenImbalance > 0) {
335
+ // YES > NO, sell excess YES
336
+ const sellAmount = Math.floor(Math.min(tokenImbalance, balance.yes * 0.5) * 1e6) / 1e6;
337
+ if (sellAmount >= MIN_SELL_AMOUNT) {
338
+ actions.push({
339
+ type: 'sell_yes',
340
+ amount: sellAmount,
341
+ reason: `⚠️ RISK: YES > NO by ${tokenImbalance.toFixed(2)}. Selling excess YES to balance.`,
342
+ priority: 100, // Highest priority
343
+ });
344
+ }
345
+ } else {
346
+ // NO > YES, sell excess NO
347
+ const sellAmount = Math.floor(Math.min(-tokenImbalance, balance.no * 0.5) * 1e6) / 1e6;
348
+ if (sellAmount >= MIN_SELL_AMOUNT) {
349
+ actions.push({
350
+ type: 'sell_no',
351
+ amount: sellAmount,
352
+ reason: `⚠️ RISK: NO > YES by ${(-tokenImbalance).toFixed(2)}. Selling excess NO to balance.`,
353
+ priority: 100, // Highest priority
354
+ });
355
+ }
356
+ }
357
+ }
358
+
359
+ // ============================================
360
+ // PRIORITY 2: Merge excess paired tokens
361
+ // ============================================
362
+ const pairedTokens = Math.min(balance.yes, balance.no);
363
+ const excessPairs = pairedTokens - targetToken;
364
+
365
+ if (excessPairs > MIN_REBALANCE_AMOUNT && usdcDiff < 0) {
366
+ const mergeAmount = Math.floor(Math.min(excessPairs * 0.5, Math.abs(usdcDiff)) * 100) / 100;
367
+ if (mergeAmount >= MIN_REBALANCE_AMOUNT) {
368
+ actions.push({
369
+ type: 'merge',
370
+ amount: mergeAmount,
371
+ reason: `Excess token pairs (${pairedTokens.toFixed(0)} > ${targetToken.toFixed(0)}), USDC low`,
372
+ priority: 50,
373
+ });
374
+ }
375
+ }
376
+
377
+ // ============================================
378
+ // PRIORITY 3: Split to create more tokens
379
+ // ============================================
380
+ const usdcDeviation = Math.abs(usdcDiff) / targetUsdc;
381
+
382
+ if (usdcDeviation > REBALANCE_THRESHOLD && usdcDiff > 0) {
383
+ // Check if both tokens are low
384
+ if (yesDiff < 0 && noDiff < 0) {
385
+ const splitAmount = Math.floor(Math.min(
386
+ usdcDiff * 0.5,
387
+ Math.abs(Math.min(yesDiff, noDiff)),
388
+ balance.usdc * 0.3
389
+ ) * 100) / 100;
390
+
391
+ if (splitAmount >= MIN_REBALANCE_AMOUNT) {
392
+ actions.push({
393
+ type: 'split',
394
+ amount: splitAmount,
395
+ reason: `USDC high (${(usdcDeviation * 100).toFixed(0)}% over), tokens low`,
396
+ priority: 30,
397
+ });
398
+ }
399
+ }
400
+ }
401
+
402
+ // Default: no action needed
403
+ if (actions.length === 0) {
404
+ actions.push({
405
+ type: 'none',
406
+ amount: 0,
407
+ reason: 'Balanced',
408
+ priority: 0,
409
+ });
410
+ }
411
+
412
+ return actions;
413
+ }
414
+
415
+ function sleep(ms: number): Promise<void> {
416
+ return new Promise(resolve => setTimeout(resolve, ms));
417
+ }
418
+
419
+ // Run
420
+ main().catch(console.error);
@@ -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
  /**