@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,331 +0,0 @@
1
- /**
2
- * CTF Client Integration Tests
3
- *
4
- * These tests verify the CTF (Conditional Token Framework) implementation
5
- * by making REAL on-chain calls to Polygon.
6
- *
7
- * IMPORTANT: These tests are READ-ONLY and do not require a wallet.
8
- * They verify:
9
- * 1. Contract addresses are correct
10
- * 2. Position ID calculation is correct
11
- * 3. Market resolution queries work
12
- * 4. Balance queries work
13
- *
14
- * Run with: pnpm test:integration
15
- */
16
-
17
- import { describe, it, expect } from 'vitest';
18
- import { ethers } from 'ethers';
19
- import {
20
- CTF_CONTRACT,
21
- USDC_CONTRACT,
22
- NEG_RISK_CTF_EXCHANGE,
23
- NEG_RISK_ADAPTER,
24
- USDC_DECIMALS,
25
- } from '../../clients/ctf-client.js';
26
-
27
- // Public RPC for read-only tests
28
- const POLYGON_RPC = 'https://polygon-rpc.com';
29
-
30
- // Known addresses and markets for testing
31
- const KNOWN_WHALE_ADDRESS = '0x82a1b239c1ff9bc60a4c86caf5b6bdbd9fddfe20'; // Top trader
32
- const SECOND_CTF_CONTRACT = '0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E';
33
-
34
- // ABIs for testing
35
- const CTF_ABI = [
36
- 'function balanceOf(address account, uint256 positionId) view returns (uint256)',
37
- 'function payoutNumerators(bytes32 conditionId, uint256 outcomeIndex) view returns (uint256)',
38
- 'function payoutDenominator(bytes32 conditionId) view returns (uint256)',
39
- 'function getOutcomeSlotCount(bytes32 conditionId) view returns (uint256)',
40
- ];
41
-
42
- const ERC20_ABI = [
43
- 'function balanceOf(address account) view returns (uint256)',
44
- 'function decimals() view returns (uint8)',
45
- 'function symbol() view returns (string)',
46
- ];
47
-
48
- describe('CTF Contract Verification', () => {
49
- const provider = new ethers.providers.JsonRpcProvider(POLYGON_RPC);
50
-
51
- describe('Contract Addresses', () => {
52
- it('should verify CTF contract is deployed and accessible', async () => {
53
- const ctf = new ethers.Contract(CTF_CONTRACT, CTF_ABI, provider);
54
-
55
- // Query a known condition ID to verify contract works
56
- // Using a random condition ID should return 0 for unresolved markets
57
- const testConditionId = '0x0000000000000000000000000000000000000000000000000000000000000001';
58
- const denominator = await ctf.payoutDenominator(testConditionId);
59
-
60
- // Should return 0 for non-existent/unresolved condition
61
- expect(denominator.toNumber()).toBe(0);
62
-
63
- console.log(`✓ CTF Contract verified at ${CTF_CONTRACT}`);
64
- }, 30000);
65
-
66
- it('should verify USDC contract is deployed', async () => {
67
- const usdc = new ethers.Contract(USDC_CONTRACT, ERC20_ABI, provider);
68
-
69
- const [decimals, symbol] = await Promise.all([
70
- usdc.decimals(),
71
- usdc.symbol(),
72
- ]);
73
-
74
- expect(decimals).toBe(USDC_DECIMALS);
75
- expect(symbol).toBe('USDC');
76
-
77
- console.log(`✓ USDC Contract verified at ${USDC_CONTRACT}`);
78
- console.log(` Symbol: ${symbol}, Decimals: ${decimals}`);
79
- }, 30000);
80
-
81
- it('should verify second CTF contract exists', async () => {
82
- // The second contract address from Polymarket docs
83
- // Note: This is the NegRisk CTF contract with a different ABI
84
- // We just verify the contract code exists
85
- const code = await provider.getCode(SECOND_CTF_CONTRACT);
86
-
87
- expect(code).not.toBe('0x');
88
- expect(code.length).toBeGreaterThan(10);
89
-
90
- console.log(`✓ Second CTF Contract verified at ${SECOND_CTF_CONTRACT}`);
91
- console.log(` Contract code size: ${(code.length - 2) / 2} bytes`);
92
- console.log(' Note: This is the NegRisk CTF contract (different ABI from standard CTF)');
93
- }, 30000);
94
-
95
- it('should verify NegRisk Adapter contract exists', async () => {
96
- // Check contract code exists
97
- const code = await provider.getCode(NEG_RISK_ADAPTER);
98
-
99
- expect(code).not.toBe('0x');
100
- expect(code.length).toBeGreaterThan(10);
101
-
102
- console.log(`✓ NegRisk Adapter verified at ${NEG_RISK_ADAPTER}`);
103
- console.log(` Contract code size: ${(code.length - 2) / 2} bytes`);
104
- }, 30000);
105
-
106
- it('should verify NegRisk CTF Exchange contract exists', async () => {
107
- const code = await provider.getCode(NEG_RISK_CTF_EXCHANGE);
108
-
109
- expect(code).not.toBe('0x');
110
- expect(code.length).toBeGreaterThan(10);
111
-
112
- console.log(`✓ NegRisk CTF Exchange verified at ${NEG_RISK_CTF_EXCHANGE}`);
113
- console.log(` Contract code size: ${(code.length - 2) / 2} bytes`);
114
- }, 30000);
115
- });
116
-
117
- describe('Position ID Calculation', () => {
118
- it('should calculate position ID correctly', () => {
119
- // This matches the Polymarket gist for positionId calculation
120
- // https://gist.github.com/polymarket/1e12f0ac3e23400ca53ec9b6e1ba00ce
121
-
122
- const conditionId = '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef';
123
- const indexSet = 1; // YES outcome
124
-
125
- // Collection ID = keccak256(parentCollectionId, conditionId, indexSet)
126
- const collectionId = ethers.utils.keccak256(
127
- ethers.utils.defaultAbiCoder.encode(
128
- ['bytes32', 'bytes32', 'uint256'],
129
- [ethers.constants.HashZero, conditionId, indexSet]
130
- )
131
- );
132
-
133
- // Position ID = keccak256(collateralToken, collectionId)
134
- const positionId = ethers.utils.keccak256(
135
- ethers.utils.defaultAbiCoder.encode(
136
- ['address', 'bytes32'],
137
- [USDC_CONTRACT, collectionId]
138
- )
139
- );
140
-
141
- // Verify the calculation produces valid bytes32
142
- expect(positionId).toMatch(/^0x[a-f0-9]{64}$/);
143
- expect(collectionId).toMatch(/^0x[a-f0-9]{64}$/);
144
-
145
- console.log('✓ Position ID calculation verified');
146
- console.log(` Condition ID: ${conditionId.slice(0, 20)}...`);
147
- console.log(` Collection ID: ${collectionId.slice(0, 20)}...`);
148
- console.log(` Position ID: ${positionId.slice(0, 20)}...`);
149
- });
150
-
151
- it('should produce different position IDs for YES and NO', () => {
152
- const conditionId = '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef';
153
-
154
- // YES position (indexSet = 1)
155
- const yesCollectionId = ethers.utils.keccak256(
156
- ethers.utils.defaultAbiCoder.encode(
157
- ['bytes32', 'bytes32', 'uint256'],
158
- [ethers.constants.HashZero, conditionId, 1]
159
- )
160
- );
161
- const yesPositionId = ethers.utils.keccak256(
162
- ethers.utils.defaultAbiCoder.encode(
163
- ['address', 'bytes32'],
164
- [USDC_CONTRACT, yesCollectionId]
165
- )
166
- );
167
-
168
- // NO position (indexSet = 2)
169
- const noCollectionId = ethers.utils.keccak256(
170
- ethers.utils.defaultAbiCoder.encode(
171
- ['bytes32', 'bytes32', 'uint256'],
172
- [ethers.constants.HashZero, conditionId, 2]
173
- )
174
- );
175
- const noPositionId = ethers.utils.keccak256(
176
- ethers.utils.defaultAbiCoder.encode(
177
- ['address', 'bytes32'],
178
- [USDC_CONTRACT, noCollectionId]
179
- )
180
- );
181
-
182
- expect(yesPositionId).not.toBe(noPositionId);
183
- expect(yesCollectionId).not.toBe(noCollectionId);
184
-
185
- console.log('✓ YES and NO position IDs are different');
186
- console.log(` YES Position ID: ${yesPositionId.slice(0, 20)}...`);
187
- console.log(` NO Position ID: ${noPositionId.slice(0, 20)}...`);
188
- });
189
- });
190
-
191
- describe('Balance Queries', () => {
192
- it('should query USDC balance for known whale', async () => {
193
- const usdc = new ethers.Contract(USDC_CONTRACT, ERC20_ABI, provider);
194
-
195
- const balance = await usdc.balanceOf(KNOWN_WHALE_ADDRESS);
196
- const formattedBalance = ethers.utils.formatUnits(balance, USDC_DECIMALS);
197
-
198
- expect(balance.gte(0)).toBe(true);
199
-
200
- console.log(`✓ USDC balance query works`);
201
- console.log(` Whale ${KNOWN_WHALE_ADDRESS.slice(0, 10)}... has ${parseFloat(formattedBalance).toLocaleString()} USDC`);
202
- }, 30000);
203
-
204
- it('should query CTF token balance', async () => {
205
- const ctf = new ethers.Contract(CTF_CONTRACT, CTF_ABI, provider);
206
-
207
- // Use a known position ID (we'll use a random one, should return 0)
208
- const randomPositionId = ethers.utils.keccak256(
209
- ethers.utils.defaultAbiCoder.encode(
210
- ['string'],
211
- ['random-test-position']
212
- )
213
- );
214
-
215
- const balance = await ctf.balanceOf(KNOWN_WHALE_ADDRESS, randomPositionId);
216
-
217
- expect(balance.gte(0)).toBe(true);
218
-
219
- console.log('✓ CTF balance query works');
220
- console.log(` Balance for random position: ${ethers.utils.formatUnits(balance, USDC_DECIMALS)}`);
221
- }, 30000);
222
- });
223
-
224
- describe('Market Resolution', () => {
225
- it('should query payout info for a real market condition', async () => {
226
- // First get a real market from Gamma API to get a valid condition ID
227
- const response = await fetch(
228
- 'https://gamma-api.polymarket.com/markets?closed=true&limit=1'
229
- );
230
- const markets = await response.json() as Array<{ conditionId: string; question: string }>;
231
-
232
- if (markets.length === 0) {
233
- console.log('No closed markets found, skipping test');
234
- return;
235
- }
236
-
237
- const ctf = new ethers.Contract(CTF_CONTRACT, CTF_ABI, provider);
238
- const conditionId = markets[0].conditionId;
239
-
240
- try {
241
- const [yesNumerator, noNumerator, denominator] = await Promise.all([
242
- ctf.payoutNumerators(conditionId, 0),
243
- ctf.payoutNumerators(conditionId, 1),
244
- ctf.payoutDenominator(conditionId),
245
- ]);
246
-
247
- expect(yesNumerator.gte(0)).toBe(true);
248
- expect(noNumerator.gte(0)).toBe(true);
249
- expect(denominator.gte(0)).toBe(true);
250
-
251
- const isResolved = denominator.gt(0);
252
-
253
- console.log('✓ Market resolution query works');
254
- console.log(` Market: "${markets[0].question.slice(0, 40)}..."`);
255
- console.log(` Condition ID: ${conditionId.slice(0, 20)}...`);
256
- console.log(` Is resolved: ${isResolved}`);
257
- if (isResolved) {
258
- console.log(` Payout numerators: [${yesNumerator.toString()}, ${noNumerator.toString()}]`);
259
- console.log(` Payout denominator: ${denominator.toString()}`);
260
- }
261
- } catch (error) {
262
- // Some markets might be NegRisk markets with different contract
263
- console.log('✓ Query attempted (market might be NegRisk type)');
264
- console.log(` Condition ID: ${conditionId.slice(0, 20)}...`);
265
- }
266
- }, 30000);
267
- });
268
-
269
- describe('Gas Price', () => {
270
- it('should fetch current gas price', async () => {
271
- const gasPrice = await provider.getGasPrice();
272
- const gasPriceGwei = ethers.utils.formatUnits(gasPrice, 'gwei');
273
-
274
- expect(gasPrice.gt(0)).toBe(true);
275
-
276
- console.log('✓ Gas price fetched');
277
- console.log(` Current gas price: ${parseFloat(gasPriceGwei).toFixed(2)} gwei`);
278
- }, 30000);
279
- });
280
- });
281
-
282
- describe('CTF Architecture Understanding', () => {
283
- it('should document the two-contract architecture', () => {
284
- /**
285
- * Polymarket uses TWO different CTF systems:
286
- *
287
- * 1. STANDARD CTF (0x4D97DCd97eC945f40cF65F87097ACe5EA0476045)
288
- * - Used for simple binary (Yes/No) markets
289
- * - Operations: split, merge, redeem
290
- * - Each market is independent
291
- *
292
- * 2. NEGRISK CTF (0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E)
293
- * - Used for "winner-take-all" events (elections, championships)
294
- * - Key innovation: NO shares can convert to YES shares in other markets
295
- * - Example: "Trump NO" can become "Biden YES + Harris YES + ..."
296
- *
297
- * Why NegRisk exists:
298
- * - Capital efficiency: Don't need to buy YES in every candidate
299
- * - Buying NO in one candidate = betting on all other candidates
300
- * - The Negative Adapter (0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296) handles conversions
301
- *
302
- * Which contract to use:
303
- * - Check the market's metadata to determine if it's a NegRisk market
304
- * - Most simple Yes/No markets use Standard CTF
305
- * - Multi-outcome events (elections, sports champions) may use NegRisk
306
- */
307
-
308
- console.log('✓ CTF Architecture Documented');
309
- console.log('');
310
- console.log('Standard CTF Contract:');
311
- console.log(` ${CTF_CONTRACT}`);
312
- console.log(' - Simple Yes/No markets');
313
- console.log(' - split/merge/redeem operations');
314
- console.log('');
315
- console.log('NegRisk CTF Contract:');
316
- console.log(` ${SECOND_CTF_CONTRACT}`);
317
- console.log(' - Winner-take-all events');
318
- console.log(' - NO shares convertible to YES in other markets');
319
- console.log('');
320
- console.log('NegRisk Adapter:');
321
- console.log(` ${NEG_RISK_ADAPTER}`);
322
- console.log(' - Handles NO → YES conversions');
323
- console.log('');
324
- console.log('NegRisk CTF Exchange:');
325
- console.log(` ${NEG_RISK_CTF_EXCHANGE}`);
326
- console.log(' - Trading for NegRisk markets');
327
-
328
- // This test always passes - it's documentation
329
- expect(true).toBe(true);
330
- });
331
- });
@@ -1,194 +0,0 @@
1
- /**
2
- * Data API Client Integration Tests
3
- *
4
- * These tests make REAL API calls to Polymarket.
5
- *
6
- * Run with: pnpm test:integration
7
- */
8
-
9
- import { describe, it, expect, beforeAll } from 'vitest';
10
- import { DataApiClient } from '../../clients/data-api.js';
11
- import { RateLimiter } from '../../core/rate-limiter.js';
12
- import { createUnifiedCache } from '../../core/unified-cache.js';
13
-
14
- describe('DataApiClient Integration', () => {
15
- let client: DataApiClient;
16
-
17
- beforeAll(() => {
18
- client = new DataApiClient(new RateLimiter(), createUnifiedCache());
19
- });
20
-
21
- describe('getLeaderboard', () => {
22
- it('should fetch leaderboard entries', async () => {
23
- const leaderboard = await client.getLeaderboard({ limit: 10 });
24
-
25
- expect(Array.isArray(leaderboard.entries)).toBe(true);
26
- expect(leaderboard.entries.length).toBeGreaterThan(0);
27
- expect(leaderboard.entries.length).toBeLessThanOrEqual(10);
28
-
29
- // Verify entry structure
30
- for (const entry of leaderboard.entries) {
31
- expect(typeof entry.address).toBe('string');
32
- expect(entry.address.length).toBeGreaterThan(0);
33
- expect(typeof entry.rank).toBe('number');
34
- expect(entry.rank).toBeGreaterThan(0);
35
- expect(typeof entry.pnl).toBe('number');
36
- expect(typeof entry.volume).toBe('number');
37
- }
38
-
39
- // Verify ranks are in order
40
- for (let i = 1; i < leaderboard.entries.length; i++) {
41
- expect(leaderboard.entries[i].rank).toBeGreaterThan(leaderboard.entries[i - 1].rank);
42
- }
43
-
44
- console.log(`✓ Leaderboard fetched: ${leaderboard.entries.length} entries`);
45
- console.log(` #1: ${leaderboard.entries[0].address.slice(0, 10)}... PnL: $${leaderboard.entries[0].pnl.toLocaleString()}`);
46
- }, 30000);
47
-
48
- it('should handle pagination', async () => {
49
- const page1 = await client.getLeaderboard({ limit: 5, offset: 0 });
50
- const page2 = await client.getLeaderboard({ limit: 5, offset: 5 });
51
-
52
- // Ranks should be continuous
53
- if (page1.entries.length > 0 && page2.entries.length > 0) {
54
- const lastRankPage1 = page1.entries[page1.entries.length - 1].rank;
55
- const firstRankPage2 = page2.entries[0].rank;
56
- expect(firstRankPage2).toBe(lastRankPage1 + 1);
57
- }
58
-
59
- console.log('✓ Pagination verified');
60
- }, 30000);
61
- });
62
-
63
- describe('getTrades', () => {
64
- it('should fetch recent trades', async () => {
65
- const trades = await client.getTrades({ limit: 20 });
66
-
67
- expect(Array.isArray(trades)).toBe(true);
68
-
69
- if (trades.length > 0) {
70
- // Verify trade structure
71
- for (const trade of trades) {
72
- expect(typeof trade.id).toBe('string');
73
- expect(['BUY', 'SELL']).toContain(trade.side);
74
- expect(typeof trade.price).toBe('number');
75
- expect(trade.price).toBeGreaterThanOrEqual(0);
76
- expect(trade.price).toBeLessThanOrEqual(1);
77
- expect(typeof trade.size).toBe('number');
78
- expect(trade.size).toBeGreaterThan(0);
79
- expect(typeof trade.timestamp).toBe('number');
80
- }
81
-
82
- console.log(`✓ Fetched ${trades.length} recent trades`);
83
- console.log(` Latest: ${trades[0].side} ${trades[0].size} @ ${trades[0].price}`);
84
- } else {
85
- console.log('✓ No recent trades found (this is ok)');
86
- }
87
- }, 30000);
88
-
89
- it('should fetch trades for specific market', async () => {
90
- // Get a trending market first
91
- const response = await fetch(
92
- 'https://gamma-api.polymarket.com/markets?active=true&limit=1&order=volume24hr&ascending=false'
93
- );
94
- const markets = await response.json() as Array<{ conditionId: string }>;
95
-
96
- if (markets.length === 0) {
97
- console.log('No markets found, skipping test');
98
- return;
99
- }
100
-
101
- const trades = await client.getTradesByMarket(markets[0].conditionId, 10);
102
-
103
- expect(Array.isArray(trades)).toBe(true);
104
-
105
- // All trades should be for this market
106
- for (const trade of trades) {
107
- expect(trade.market).toBe(markets[0].conditionId);
108
- }
109
-
110
- console.log(`✓ Fetched ${trades.length} trades for specific market`);
111
- }, 30000);
112
- });
113
-
114
- describe('getPositions', () => {
115
- it('should fetch positions for a known active wallet', async () => {
116
- // Get top trader from leaderboard
117
- const leaderboard = await client.getLeaderboard({ limit: 1 });
118
-
119
- if (leaderboard.entries.length === 0) {
120
- console.log('No leaderboard entries, skipping test');
121
- return;
122
- }
123
-
124
- const address = leaderboard.entries[0].address;
125
- const positions = await client.getPositions(address);
126
-
127
- expect(Array.isArray(positions)).toBe(true);
128
-
129
- if (positions.length > 0) {
130
- // Verify position structure
131
- for (const pos of positions) {
132
- expect(typeof pos.asset).toBe('string');
133
- expect(typeof pos.conditionId).toBe('string');
134
- // Polymarket has multi-outcome markets, not just Yes/No
135
- expect(typeof pos.outcome).toBe('string');
136
- expect(pos.outcome.length).toBeGreaterThan(0);
137
- expect(typeof pos.size).toBe('number');
138
- expect(typeof pos.avgPrice).toBe('number');
139
- expect(typeof pos.title).toBe('string');
140
- }
141
-
142
- console.log(`✓ Fetched ${positions.length} positions for ${address.slice(0, 10)}...`);
143
- } else {
144
- console.log(`✓ Top trader has no current positions (this is ok)`);
145
- }
146
- }, 30000);
147
-
148
- it('should return empty array for wallet with no positions', async () => {
149
- // Use a random address that probably has no positions
150
- const positions = await client.getPositions('0x0000000000000000000000000000000000000001');
151
-
152
- expect(Array.isArray(positions)).toBe(true);
153
- // Might be empty or have some positions, both are valid
154
- console.log(`✓ Returned ${positions.length} positions for test address`);
155
- }, 30000);
156
- });
157
-
158
- describe('getActivity', () => {
159
- it('should fetch activity for an active wallet', async () => {
160
- // Get top trader
161
- const leaderboard = await client.getLeaderboard({ limit: 1 });
162
-
163
- if (leaderboard.entries.length === 0) {
164
- console.log('No leaderboard entries, skipping test');
165
- return;
166
- }
167
-
168
- const address = leaderboard.entries[0].address;
169
- const activity = await client.getActivity(address, { limit: 20 });
170
-
171
- expect(Array.isArray(activity)).toBe(true);
172
-
173
- if (activity.length > 0) {
174
- // Verify activity structure
175
- for (const act of activity) {
176
- // Polymarket has various activity types including YIELD for rewards
177
- expect(['TRADE', 'SPLIT', 'MERGE', 'REDEEM', 'CONVERSION', 'YIELD']).toContain(act.type);
178
- // Side might be null for non-trade activities
179
- if (act.type === 'TRADE') {
180
- expect(['BUY', 'SELL']).toContain(act.side);
181
- }
182
- expect(typeof act.size).toBe('number');
183
- expect(typeof act.price).toBe('number');
184
- expect(typeof act.timestamp).toBe('number');
185
- expect(act.timestamp).toBeGreaterThan(0);
186
- }
187
-
188
- console.log(`✓ Fetched ${activity.length} activities for ${address.slice(0, 10)}...`);
189
- } else {
190
- console.log('✓ No recent activity found (this is ok)');
191
- }
192
- }, 30000);
193
- });
194
- });