@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,420 +0,0 @@
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);