@exagent/agent 0.3.2 → 0.3.4

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 (146) hide show
  1. package/dist/{chunk-VDK4XPAC.js → chunk-WTECTX2Z.js} +31 -4
  2. package/dist/cli.js +212 -77
  3. package/dist/index.js +1 -1
  4. package/package.json +1 -1
  5. package/src/cli.ts +122 -3
  6. package/src/config.ts +19 -2
  7. package/src/runtime.ts +18 -2
  8. package/src/setup.ts +118 -67
  9. package/dist/chunk-25J5ZDKX.js +0 -5622
  10. package/dist/chunk-2ML4XS5X.js +0 -5626
  11. package/dist/chunk-2OKYNZ3J.js +0 -5622
  12. package/dist/chunk-2PAASZJN.js +0 -5132
  13. package/dist/chunk-2WAYVOLU.js +0 -5624
  14. package/dist/chunk-2XBVVY3I.js +0 -5621
  15. package/dist/chunk-37HCPVBZ.js +0 -2941
  16. package/dist/chunk-3DZAZBLF.js +0 -5652
  17. package/dist/chunk-3IXCKNSV.js +0 -5008
  18. package/dist/chunk-3MXFTRXB.js +0 -3326
  19. package/dist/chunk-4MURFLNJ.js +0 -5136
  20. package/dist/chunk-4UVMO6ZM.js +0 -6318
  21. package/dist/chunk-56YQROFU.js +0 -5639
  22. package/dist/chunk-5B3ZEGMD.js +0 -4330
  23. package/dist/chunk-5NU6FDDE.js +0 -6020
  24. package/dist/chunk-5WADKPJU.js +0 -1552
  25. package/dist/chunk-6LOIFEEV.js +0 -4895
  26. package/dist/chunk-6YIXPNL4.js +0 -5626
  27. package/dist/chunk-72HK2V74.js +0 -5224
  28. package/dist/chunk-7Q72QQIV.js +0 -4697
  29. package/dist/chunk-7V3XTBIF.js +0 -4896
  30. package/dist/chunk-A4CM4F7Q.js +0 -5633
  31. package/dist/chunk-ADXXR2MA.js +0 -4816
  32. package/dist/chunk-AG6CJPIC.js +0 -4895
  33. package/dist/chunk-AJPXHBTF.js +0 -4459
  34. package/dist/chunk-AQ6R37XV.js +0 -4809
  35. package/dist/chunk-AS4UEZMU.js +0 -5001
  36. package/dist/chunk-ASYMD22Y.js +0 -5624
  37. package/dist/chunk-AU4MCQCE.js +0 -5624
  38. package/dist/chunk-B4VHIITU.js +0 -5748
  39. package/dist/chunk-B6GVDNKQ.js +0 -5624
  40. package/dist/chunk-BCIAW6ZL.js +0 -5132
  41. package/dist/chunk-BJZ5PCG3.js +0 -5358
  42. package/dist/chunk-BS4J5QSM.js +0 -5622
  43. package/dist/chunk-BV2AUUX6.js +0 -2940
  44. package/dist/chunk-BWNSH2LK.js +0 -1574
  45. package/dist/chunk-C3GMBW3R.js +0 -5640
  46. package/dist/chunk-C6CVQGJ4.js +0 -5624
  47. package/dist/chunk-CGXKXNUJ.js +0 -5626
  48. package/dist/chunk-CIEZAYOU.js +0 -4701
  49. package/dist/chunk-CORZCEAQ.js +0 -5621
  50. package/dist/chunk-CS5LGZWP.js +0 -5357
  51. package/dist/chunk-CVT3KC24.js +0 -5624
  52. package/dist/chunk-D5MJ45R7.js +0 -3258
  53. package/dist/chunk-DSBRZ5DZ.js +0 -5624
  54. package/dist/chunk-E2X7JARQ.js +0 -4437
  55. package/dist/chunk-E3GY36ZP.js +0 -3258
  56. package/dist/chunk-E6NCIFKB.js +0 -4733
  57. package/dist/chunk-EOXLKW4D.js +0 -4895
  58. package/dist/chunk-FCI7LX4Q.js +0 -5624
  59. package/dist/chunk-FFJSKTOL.js +0 -4539
  60. package/dist/chunk-FOQYP3IB.js +0 -2950
  61. package/dist/chunk-GNEYTZDH.js +0 -4686
  62. package/dist/chunk-GPMXUMYH.js +0 -5991
  63. package/dist/chunk-GZWPAQPU.js +0 -4593
  64. package/dist/chunk-H5DXDKMX.js +0 -5619
  65. package/dist/chunk-HFQRTMS6.js +0 -3377
  66. package/dist/chunk-HQKRHX6Y.js +0 -5626
  67. package/dist/chunk-HTF3TNBY.js +0 -4834
  68. package/dist/chunk-IADSQBBY.js +0 -5523
  69. package/dist/chunk-IE2SXMZK.js +0 -4890
  70. package/dist/chunk-IGUQVJCB.js +0 -5622
  71. package/dist/chunk-IIREL7SL.js +0 -5615
  72. package/dist/chunk-IJK4EFTJ.js +0 -6043
  73. package/dist/chunk-J2MQ3Y5O.js +0 -5223
  74. package/dist/chunk-J3NG7AGT.js +0 -6047
  75. package/dist/chunk-JIBBZ3NV.js +0 -5132
  76. package/dist/chunk-JIPSBE6S.js +0 -5622
  77. package/dist/chunk-JPG755XK.js +0 -4589
  78. package/dist/chunk-JQBNL5GX.js +0 -5230
  79. package/dist/chunk-KS3F5WSX.js +0 -4831
  80. package/dist/chunk-KUYTQ4FR.js +0 -4808
  81. package/dist/chunk-KVP4CMJ5.js +0 -4711
  82. package/dist/chunk-LAR2I44B.js +0 -5626
  83. package/dist/chunk-LBTHSED2.js +0 -1531
  84. package/dist/chunk-M6OAMYVM.js +0 -5621
  85. package/dist/chunk-MFN5WWOY.js +0 -5132
  86. package/dist/chunk-MMTSKXLK.js +0 -5624
  87. package/dist/chunk-MPUSQLTH.js +0 -5626
  88. package/dist/chunk-MREXDTWL.js +0 -1555
  89. package/dist/chunk-MUEDKRFC.js +0 -5624
  90. package/dist/chunk-NOVPL2JH.js +0 -3327
  91. package/dist/chunk-NQIP4MHV.js +0 -4334
  92. package/dist/chunk-NXXKMYLS.js +0 -5624
  93. package/dist/chunk-OBYNZXNM.js +0 -4756
  94. package/dist/chunk-OFY4HBOJ.js +0 -5624
  95. package/dist/chunk-OJNUEZEK.js +0 -5602
  96. package/dist/chunk-OQCJOMUQ.js +0 -5624
  97. package/dist/chunk-OZH75GY6.js +0 -5132
  98. package/dist/chunk-P3IJVDMZ.js +0 -4700
  99. package/dist/chunk-PMYMYMBH.js +0 -4877
  100. package/dist/chunk-PRELNRVN.js +0 -5623
  101. package/dist/chunk-PSQUSNSI.js +0 -4703
  102. package/dist/chunk-QAIQ5IB6.js +0 -5624
  103. package/dist/chunk-QG22GADV.js +0 -6316
  104. package/dist/chunk-QNE2KGGK.js +0 -3315
  105. package/dist/chunk-RH7ZBSG4.js +0 -5132
  106. package/dist/chunk-RLD5MUCR.js +0 -5626
  107. package/dist/chunk-S42VEBNR.js +0 -3268
  108. package/dist/chunk-SEM6UXU4.js +0 -3324
  109. package/dist/chunk-SI5WP77M.js +0 -4430
  110. package/dist/chunk-SID4SQSY.js +0 -4837
  111. package/dist/chunk-SIELPKWF.js +0 -1558
  112. package/dist/chunk-SVBLY6QT.js +0 -5742
  113. package/dist/chunk-SVFTC5V2.js +0 -6021
  114. package/dist/chunk-SXHTX62B.js +0 -4823
  115. package/dist/chunk-T2YCEA5U.js +0 -4730
  116. package/dist/chunk-TARCHIOU.js +0 -4718
  117. package/dist/chunk-TDACLKD7.js +0 -5867
  118. package/dist/chunk-TGCBM3NP.js +0 -4890
  119. package/dist/chunk-TIWG6KAK.js +0 -4769
  120. package/dist/chunk-TKLKATVM.js +0 -1534
  121. package/dist/chunk-TSLZ4A5P.js +0 -5222
  122. package/dist/chunk-TWSDKORW.js +0 -4698
  123. package/dist/chunk-U5QHYVMJ.js +0 -3341
  124. package/dist/chunk-UAP5CTHB.js +0 -5985
  125. package/dist/chunk-UK6SEUWU.js +0 -3210
  126. package/dist/chunk-UKU5YO65.js +0 -5132
  127. package/dist/chunk-UOZQXP4Q.js +0 -5144
  128. package/dist/chunk-UPTN2TSS.js +0 -4727
  129. package/dist/chunk-UQT2APOE.js +0 -2944
  130. package/dist/chunk-V32QDZKW.js +0 -5132
  131. package/dist/chunk-VKY2CDCD.js +0 -5622
  132. package/dist/chunk-VUCSYMCY.js +0 -3323
  133. package/dist/chunk-VVLNBD5Y.js +0 -5132
  134. package/dist/chunk-W3TQ22O6.js +0 -4459
  135. package/dist/chunk-WA4DSGOM.js +0 -3355
  136. package/dist/chunk-WI6MIICK.js +0 -4687
  137. package/dist/chunk-XRHJLL74.js +0 -4893
  138. package/dist/chunk-XXWXEBJQ.js +0 -4885
  139. package/dist/chunk-YC6TH2H3.js +0 -5624
  140. package/dist/chunk-YDH6HCUJ.js +0 -5624
  141. package/dist/chunk-YJD35VKQ.js +0 -4890
  142. package/dist/chunk-ZBIQJBY7.js +0 -5620
  143. package/dist/chunk-ZKTSA2AE.js +0 -5629
  144. package/dist/chunk-ZKZZL3PE.js +0 -3379
  145. package/dist/chunk-ZM5KCPRK.js +0 -4541
  146. package/dist/chunk-ZTYPDSE3.js +0 -3258
@@ -1,4890 +0,0 @@
1
- // src/config.ts
2
- import { readFileSync, existsSync, writeFileSync } from "fs";
3
- import { z } from "zod";
4
- var configSchema = z.object({
5
- agentId: z.string(),
6
- apiUrl: z.string().url(),
7
- apiToken: z.string(),
8
- wallet: z.object({
9
- privateKey: z.string()
10
- }).optional(),
11
- llm: z.object({
12
- provider: z.enum(["openai", "anthropic", "google", "deepseek", "mistral", "groq", "together", "ollama"]),
13
- model: z.string().optional(),
14
- apiKey: z.string().optional(),
15
- endpoint: z.string().optional(),
16
- temperature: z.number().min(0).max(2).optional(),
17
- maxTokens: z.number().optional()
18
- }),
19
- strategy: z.object({
20
- file: z.string().optional(),
21
- template: z.string().optional()
22
- }),
23
- trading: z.object({
24
- mode: z.enum(["live", "paper"]).default("paper"),
25
- timeHorizon: z.enum(["intraday", "swing", "position"]).default("swing"),
26
- maxPositionSizeBps: z.number().min(100).max(1e4).default(2e3),
27
- maxDailyLossBps: z.number().min(0).max(1e4).default(500),
28
- maxConcurrentPositions: z.number().min(1).max(100).default(5),
29
- tradingIntervalMs: z.number().min(1e3).default(6e4),
30
- maxSlippageBps: z.number().min(10).max(1e3).default(100),
31
- minTradeValueUSD: z.number().min(0).default(10),
32
- initialCapitalUSD: z.number().optional()
33
- }),
34
- venues: z.object({
35
- hyperliquid_perp: z.object({
36
- enabled: z.boolean().default(false),
37
- apiUrl: z.string().default("https://api.hyperliquid.xyz"),
38
- wsUrl: z.string().default("wss://api.hyperliquid.xyz/ws"),
39
- maxLeverage: z.number().min(1).max(50).default(10),
40
- maxNotionalUSD: z.number().default(5e4),
41
- allowedInstruments: z.array(z.string()).optional()
42
- }).optional(),
43
- polymarket: z.object({
44
- enabled: z.boolean().default(false),
45
- clobApiUrl: z.string().default("https://clob.polymarket.com"),
46
- gammaApiUrl: z.string().default("https://gamma-api.polymarket.com"),
47
- maxNotionalUSD: z.number().default(1e3),
48
- maxTotalExposureUSD: z.number().default(5e3),
49
- allowedCategories: z.array(z.string()).optional()
50
- }).optional(),
51
- spot: z.object({
52
- enabled: z.boolean().default(false),
53
- chains: z.array(z.string()).default(["base"]),
54
- defaultChain: z.string().default("base"),
55
- maxSlippageBps: z.number().min(1).max(1e3).default(50),
56
- maxSwapValueUSD: z.number().default(1e4)
57
- }).optional(),
58
- bridge: z.object({
59
- enabled: z.boolean().default(false),
60
- defaultBridge: z.string().default("across"),
61
- maxBridgeValueUSD: z.number().default(1e4),
62
- fillTimeoutMs: z.number().default(3e5),
63
- pollIntervalMs: z.number().default(2e3)
64
- }).optional()
65
- }).optional(),
66
- relay: z.object({
67
- url: z.string(),
68
- heartbeatIntervalMs: z.number().default(3e4),
69
- reconnectMaxAttempts: z.number().default(50)
70
- })
71
- });
72
- function loadConfig(path = "agent-config.json") {
73
- if (!existsSync(path)) {
74
- throw new Error(`Config file not found: ${path}. Run 'exagent init' first.`);
75
- }
76
- const raw = readFileSync(path, "utf-8");
77
- let parsed;
78
- try {
79
- parsed = JSON.parse(raw);
80
- } catch {
81
- throw new Error(`Invalid JSON in ${path}`);
82
- }
83
- const config = parsed;
84
- const llm = config.llm || {};
85
- if (process.env.EXAGENT_LLM_PROVIDER) llm.provider = process.env.EXAGENT_LLM_PROVIDER;
86
- if (process.env.EXAGENT_LLM_MODEL) llm.model = process.env.EXAGENT_LLM_MODEL;
87
- if (process.env.EXAGENT_LLM_API_KEY) llm.apiKey = process.env.EXAGENT_LLM_API_KEY;
88
- if (process.env.EXAGENT_API_URL) config.apiUrl = process.env.EXAGENT_API_URL;
89
- if (process.env.EXAGENT_API_TOKEN) config.apiToken = process.env.EXAGENT_API_TOKEN;
90
- if (process.env.EXAGENT_WALLET_PRIVATE_KEY) {
91
- config.wallet = { privateKey: process.env.EXAGENT_WALLET_PRIVATE_KEY };
92
- }
93
- config.llm = llm;
94
- const result = configSchema.safeParse(config);
95
- if (!result.success) {
96
- const issues = result.error.issues.map((i) => ` ${i.path.join(".")}: ${i.message}`).join("\n");
97
- throw new Error(`Invalid config:
98
- ${issues}`);
99
- }
100
- return result.data;
101
- }
102
- function generateSampleConfig(agentId, apiUrl) {
103
- const config = {
104
- agentId,
105
- apiUrl,
106
- apiToken: "<your-jwt-token>",
107
- wallet: {
108
- privateKey: "<your-hex-private-key>"
109
- },
110
- llm: {
111
- provider: "openai",
112
- model: "gpt-4o",
113
- apiKey: "<your-api-key>"
114
- },
115
- strategy: {
116
- template: "momentum"
117
- },
118
- trading: {
119
- mode: "paper",
120
- timeHorizon: "swing",
121
- maxPositionSizeBps: 2e3,
122
- maxDailyLossBps: 500,
123
- maxConcurrentPositions: 5,
124
- tradingIntervalMs: 6e4,
125
- maxSlippageBps: 100,
126
- minTradeValueUSD: 10,
127
- initialCapitalUSD: 1e4
128
- },
129
- venues: {
130
- hyperliquid_perp: {
131
- enabled: false,
132
- apiUrl: "https://api.hyperliquid.xyz",
133
- wsUrl: "wss://api.hyperliquid.xyz/ws",
134
- maxLeverage: 10,
135
- maxNotionalUSD: 5e4
136
- },
137
- polymarket: {
138
- enabled: false,
139
- clobApiUrl: "https://clob.polymarket.com",
140
- gammaApiUrl: "https://gamma-api.polymarket.com",
141
- maxNotionalUSD: 1e3,
142
- maxTotalExposureUSD: 5e3
143
- },
144
- spot: {
145
- enabled: false,
146
- chains: ["base"],
147
- defaultChain: "base",
148
- maxSlippageBps: 50,
149
- maxSwapValueUSD: 1e4
150
- },
151
- bridge: {
152
- enabled: false,
153
- defaultBridge: "across",
154
- maxBridgeValueUSD: 1e4,
155
- fillTimeoutMs: 3e5,
156
- pollIntervalMs: 2e3
157
- }
158
- },
159
- relay: {
160
- url: apiUrl.replace(/^http/, "ws") + "/ws/agent",
161
- heartbeatIntervalMs: 3e4,
162
- reconnectMaxAttempts: 50
163
- }
164
- };
165
- return JSON.stringify(config, null, 2);
166
- }
167
- function writeSampleConfig(agentId, apiUrl, path = "agent-config.json") {
168
- writeFileSync(path, generateSampleConfig(agentId, apiUrl));
169
- }
170
-
171
- // src/chains.ts
172
- import { base, arbitrum, polygon, mainnet } from "viem/chains";
173
- var CHAIN_CONFIGS = {
174
- base: {
175
- chainId: 8453,
176
- name: "base",
177
- viemChain: base,
178
- rpcUrl: "https://mainnet.base.org",
179
- nativeCurrency: "ETH",
180
- blockExplorer: "https://basescan.org",
181
- wethAddress: "0x4200000000000000000000000000000000000006",
182
- usdcAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
183
- dexRouters: {
184
- uniswap: "0x2626664c2603336E57B271c5C0b26F421741e481",
185
- aerodrome: "0xcF77a3Ba9A5CA399B7c97c74d54e5b1Beb874E43"
186
- },
187
- uniswapQuoter: "0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",
188
- acrossSpokePool: "0x09aea4b2242abC8bb4BB78D537A67a245A7bEC64"
189
- },
190
- ethereum: {
191
- chainId: 1,
192
- name: "ethereum",
193
- viemChain: mainnet,
194
- rpcUrl: "https://eth.llamarpc.com",
195
- nativeCurrency: "ETH",
196
- blockExplorer: "https://etherscan.io",
197
- wethAddress: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
198
- usdcAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
199
- dexRouters: {
200
- uniswap: "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"
201
- },
202
- uniswapQuoter: "0x61fFE014bA17989E743c5F6cB21bF9697530B21e",
203
- acrossSpokePool: "0x5c7BCd6E7De5423a257D81B442095A1a6ced35C5"
204
- },
205
- arbitrum: {
206
- chainId: 42161,
207
- name: "arbitrum",
208
- viemChain: arbitrum,
209
- rpcUrl: "https://arb1.arbitrum.io/rpc",
210
- nativeCurrency: "ETH",
211
- blockExplorer: "https://arbiscan.io",
212
- wethAddress: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
213
- usdcAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
214
- dexRouters: {
215
- uniswap: "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"
216
- },
217
- uniswapQuoter: "0x61fFE014bA17989E743c5F6cB21bF9697530B21e",
218
- acrossSpokePool: "0xe35e9842fceaCA96570B734083f4a58e8F7C5f2A"
219
- },
220
- polygon: {
221
- chainId: 137,
222
- name: "polygon",
223
- viemChain: polygon,
224
- rpcUrl: "https://polygon-bor-rpc.publicnode.com",
225
- nativeCurrency: "POL",
226
- blockExplorer: "https://polygonscan.com",
227
- wethAddress: "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",
228
- usdcAddress: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
229
- dexRouters: {
230
- uniswap: "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"
231
- },
232
- uniswapQuoter: "0x61fFE014bA17989E743c5F6cB21bF9697530B21e",
233
- acrossSpokePool: "0x9295ee1d8C5b022Be115A2AD3c30C72E34e7F096"
234
- }
235
- };
236
- function getChainConfig(nameOrId) {
237
- if (typeof nameOrId === "number") {
238
- return Object.values(CHAIN_CONFIGS).find((c) => c.chainId === nameOrId);
239
- }
240
- return CHAIN_CONFIGS[nameOrId.toLowerCase()];
241
- }
242
-
243
- // src/spot/types.ts
244
- var DEFAULT_SPOT_CONFIG = {
245
- enabled: false,
246
- chains: ["base"],
247
- defaultChain: "base",
248
- maxSlippageBps: 50,
249
- maxSwapValueUSD: 1e4
250
- };
251
- var ERC20_ABI = [
252
- {
253
- type: "function",
254
- name: "approve",
255
- inputs: [
256
- { name: "spender", type: "address" },
257
- { name: "amount", type: "uint256" }
258
- ],
259
- outputs: [{ type: "bool" }],
260
- stateMutability: "nonpayable"
261
- },
262
- {
263
- type: "function",
264
- name: "allowance",
265
- inputs: [
266
- { name: "owner", type: "address" },
267
- { name: "spender", type: "address" }
268
- ],
269
- outputs: [{ type: "uint256" }],
270
- stateMutability: "view"
271
- },
272
- {
273
- type: "function",
274
- name: "balanceOf",
275
- inputs: [{ name: "account", type: "address" }],
276
- outputs: [{ type: "uint256" }],
277
- stateMutability: "view"
278
- },
279
- {
280
- type: "function",
281
- name: "decimals",
282
- inputs: [],
283
- outputs: [{ type: "uint8" }],
284
- stateMutability: "view"
285
- },
286
- {
287
- type: "function",
288
- name: "symbol",
289
- inputs: [],
290
- outputs: [{ type: "string" }],
291
- stateMutability: "view"
292
- },
293
- {
294
- type: "function",
295
- name: "transfer",
296
- inputs: [
297
- { name: "to", type: "address" },
298
- { name: "amount", type: "uint256" }
299
- ],
300
- outputs: [{ type: "bool" }],
301
- stateMutability: "nonpayable"
302
- }
303
- ];
304
- var UNISWAP_QUOTER_V2_ABI = [
305
- {
306
- type: "function",
307
- name: "quoteExactInputSingle",
308
- inputs: [
309
- {
310
- name: "params",
311
- type: "tuple",
312
- components: [
313
- { name: "tokenIn", type: "address" },
314
- { name: "tokenOut", type: "address" },
315
- { name: "amountIn", type: "uint256" },
316
- { name: "fee", type: "uint24" },
317
- { name: "sqrtPriceLimitX96", type: "uint160" }
318
- ]
319
- }
320
- ],
321
- outputs: [
322
- { name: "amountOut", type: "uint256" },
323
- { name: "sqrtPriceX96After", type: "uint160" },
324
- { name: "initializedTicksCrossed", type: "uint32" },
325
- { name: "gasEstimate", type: "uint256" }
326
- ],
327
- stateMutability: "nonpayable"
328
- }
329
- ];
330
- var UNISWAP_SWAP_ROUTER_ABI = [
331
- {
332
- type: "function",
333
- name: "exactInputSingle",
334
- inputs: [
335
- {
336
- name: "params",
337
- type: "tuple",
338
- components: [
339
- { name: "tokenIn", type: "address" },
340
- { name: "tokenOut", type: "address" },
341
- { name: "fee", type: "uint24" },
342
- { name: "recipient", type: "address" },
343
- { name: "amountIn", type: "uint256" },
344
- { name: "amountOutMinimum", type: "uint256" },
345
- { name: "sqrtPriceLimitX96", type: "uint160" }
346
- ]
347
- }
348
- ],
349
- outputs: [{ name: "amountOut", type: "uint256" }],
350
- stateMutability: "payable"
351
- }
352
- ];
353
- var AERODROME_ROUTER_ABI = [
354
- {
355
- type: "function",
356
- name: "swapExactTokensForTokens",
357
- inputs: [
358
- { name: "amountIn", type: "uint256" },
359
- { name: "amountOutMin", type: "uint256" },
360
- {
361
- name: "routes",
362
- type: "tuple[]",
363
- components: [
364
- { name: "from", type: "address" },
365
- { name: "to", type: "address" },
366
- { name: "stable", type: "bool" },
367
- { name: "factory", type: "address" }
368
- ]
369
- },
370
- { name: "to", type: "address" },
371
- { name: "deadline", type: "uint256" }
372
- ],
373
- outputs: [{ name: "amounts", type: "uint256[]" }],
374
- stateMutability: "nonpayable"
375
- },
376
- {
377
- type: "function",
378
- name: "getAmountsOut",
379
- inputs: [
380
- { name: "amountIn", type: "uint256" },
381
- {
382
- name: "routes",
383
- type: "tuple[]",
384
- components: [
385
- { name: "from", type: "address" },
386
- { name: "to", type: "address" },
387
- { name: "stable", type: "bool" },
388
- { name: "factory", type: "address" }
389
- ]
390
- }
391
- ],
392
- outputs: [{ name: "amounts", type: "uint256[]" }],
393
- stateMutability: "view"
394
- }
395
- ];
396
- var AERODROME_DEFAULT_FACTORY = "0x420DD381b31aEf6683db6B902084cB0FFECe40Da";
397
-
398
- // src/relay.ts
399
- import WebSocket from "ws";
400
- var RelayClient = class {
401
- ws = null;
402
- config;
403
- heartbeatTimer = null;
404
- reconnectTimer = null;
405
- reconnectAttempts = 0;
406
- intentionalClose = false;
407
- authenticated = false;
408
- lastStatus = null;
409
- onCommand;
410
- onConnected;
411
- onDisconnected;
412
- constructor(config) {
413
- this.config = {
414
- url: config.url,
415
- agentId: config.agentId,
416
- token: config.token,
417
- heartbeatIntervalMs: config.heartbeatIntervalMs ?? 3e4,
418
- reconnectMaxAttempts: config.reconnectMaxAttempts ?? 50
419
- };
420
- this.onCommand = config.onCommand;
421
- this.onConnected = config.onConnected;
422
- this.onDisconnected = config.onDisconnected;
423
- }
424
- get isConnected() {
425
- return this.ws?.readyState === WebSocket.OPEN && this.authenticated;
426
- }
427
- async connect() {
428
- return new Promise((resolve2, reject) => {
429
- try {
430
- this.intentionalClose = false;
431
- this.ws = new WebSocket(this.config.url);
432
- const timeout = setTimeout(() => {
433
- if (this.ws && this.ws.readyState !== WebSocket.OPEN) {
434
- this.ws.terminate();
435
- reject(new Error("Connection timeout (15s)"));
436
- }
437
- }, 15e3);
438
- this.ws.on("open", () => {
439
- clearTimeout(timeout);
440
- this.reconnectAttempts = 0;
441
- this.authenticate();
442
- });
443
- this.ws.on("message", (data) => {
444
- try {
445
- const msg = JSON.parse(data.toString());
446
- this.handleMessage(msg, resolve2);
447
- } catch {
448
- console.error("[relay] Failed to parse message");
449
- }
450
- });
451
- this.ws.on("close", () => {
452
- this.cleanup();
453
- this.onDisconnected?.();
454
- if (!this.intentionalClose) {
455
- this.scheduleReconnect();
456
- }
457
- });
458
- this.ws.on("error", (err) => {
459
- console.error("[relay] WebSocket error:", err.message);
460
- if (!this.authenticated) {
461
- clearTimeout(timeout);
462
- reject(err);
463
- }
464
- });
465
- } catch (err) {
466
- reject(err);
467
- }
468
- });
469
- }
470
- disconnect() {
471
- this.intentionalClose = true;
472
- this.cleanup();
473
- if (this.ws) {
474
- this.ws.close();
475
- this.ws = null;
476
- }
477
- }
478
- authenticate() {
479
- this.send({
480
- type: "auth",
481
- agentId: this.config.agentId,
482
- token: this.config.token
483
- });
484
- }
485
- handleMessage(msg, onAuth) {
486
- switch (msg.type) {
487
- case "auth_success":
488
- this.authenticated = true;
489
- this.startHeartbeat();
490
- this.onConnected?.();
491
- onAuth?.();
492
- console.log(`[relay] Authenticated as agent ${this.config.agentId}`);
493
- break;
494
- case "auth_error":
495
- console.error("[relay] Auth failed:", msg.error);
496
- this.disconnect();
497
- break;
498
- case "command":
499
- this.onCommand?.(msg.command);
500
- break;
501
- case "pong":
502
- break;
503
- }
504
- }
505
- sendCommandAck(commandId, success, message) {
506
- this.send({
507
- type: "command_ack",
508
- agentId: this.config.agentId,
509
- commandId,
510
- success,
511
- message,
512
- timestamp: Date.now()
513
- });
514
- }
515
- send(msg) {
516
- if (this.ws?.readyState === WebSocket.OPEN) {
517
- this.ws.send(JSON.stringify(msg));
518
- }
519
- }
520
- sendHeartbeat(status) {
521
- this.lastStatus = status;
522
- this.send({
523
- type: "heartbeat",
524
- agentId: this.config.agentId,
525
- status,
526
- timestamp: Date.now()
527
- });
528
- }
529
- sendMessage(messageType, level, title, body, data) {
530
- this.send({
531
- type: "message",
532
- agentId: this.config.agentId,
533
- messageType,
534
- level,
535
- title,
536
- body,
537
- data,
538
- timestamp: Date.now()
539
- });
540
- }
541
- sendTradeSignal(signal) {
542
- this.send({
543
- type: "trade_signal",
544
- agentId: this.config.agentId,
545
- signal,
546
- timestamp: Date.now()
547
- });
548
- }
549
- startHeartbeat() {
550
- this.stopHeartbeat();
551
- this.heartbeatTimer = setInterval(() => {
552
- if (this.lastStatus) {
553
- this.sendHeartbeat(this.lastStatus);
554
- }
555
- }, this.config.heartbeatIntervalMs);
556
- }
557
- stopHeartbeat() {
558
- if (this.heartbeatTimer) {
559
- clearInterval(this.heartbeatTimer);
560
- this.heartbeatTimer = null;
561
- }
562
- }
563
- cleanup() {
564
- this.stopHeartbeat();
565
- this.authenticated = false;
566
- if (this.reconnectTimer) {
567
- clearTimeout(this.reconnectTimer);
568
- this.reconnectTimer = null;
569
- }
570
- }
571
- scheduleReconnect() {
572
- if (this.reconnectAttempts >= this.config.reconnectMaxAttempts) {
573
- console.error(`[relay] Max reconnect attempts (${this.config.reconnectMaxAttempts}) reached`);
574
- return;
575
- }
576
- const delay = Math.min(1e3 * Math.pow(2, this.reconnectAttempts), 3e4);
577
- this.reconnectAttempts++;
578
- console.log(`[relay] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);
579
- this.reconnectTimer = setTimeout(async () => {
580
- try {
581
- await this.connect();
582
- } catch (err) {
583
- console.error("[relay] Reconnect failed:", err.message);
584
- }
585
- }, delay);
586
- }
587
- };
588
-
589
- // src/signal.ts
590
- var SignalReporter = class {
591
- relay;
592
- constructor(relay) {
593
- this.relay = relay;
594
- }
595
- reportTrade(signal) {
596
- if (!this.relay.isConnected) {
597
- console.warn("[signal] Not connected to relay \u2014 trade signal queued locally");
598
- return;
599
- }
600
- this.relay.sendTradeSignal(signal);
601
- this.relay.sendMessage(
602
- "trade_executed",
603
- "success",
604
- `${signal.side.toUpperCase()} ${signal.symbol}`,
605
- `${signal.side} ${signal.size} ${signal.symbol} @ $${signal.price.toFixed(2)} on ${signal.venue}`,
606
- { signal }
607
- );
608
- }
609
- reportPerpFill(signal) {
610
- if (!this.relay.isConnected) return;
611
- this.relay.sendTradeSignal(signal);
612
- this.relay.sendMessage(
613
- "perp_fill",
614
- "success",
615
- `Perp ${signal.side.toUpperCase()} ${signal.symbol}`,
616
- `${signal.side} ${signal.size} ${signal.symbol} @ $${signal.price.toFixed(2)} (${signal.leverage ?? 1}x)`,
617
- { signal }
618
- );
619
- }
620
- reportPredictionFill(signal) {
621
- if (!this.relay.isConnected) return;
622
- this.relay.sendTradeSignal(signal);
623
- this.relay.sendMessage(
624
- "prediction_fill",
625
- "success",
626
- `Prediction ${signal.side.toUpperCase()}`,
627
- `${signal.side} $${signal.size.toFixed(2)} on ${signal.symbol} @ ${signal.price.toFixed(4)}`,
628
- { signal }
629
- );
630
- }
631
- reportSpotFill(signal) {
632
- if (!this.relay.isConnected) return;
633
- this.relay.sendTradeSignal(signal);
634
- this.relay.sendMessage(
635
- "spot_fill",
636
- "success",
637
- `Spot ${signal.side.toUpperCase()} ${signal.symbol}`,
638
- `${signal.side} ${signal.size} ${signal.symbol} @ $${signal.price.toFixed(4)} on ${signal.venue} (${signal.chain ?? "unknown"})`,
639
- { signal }
640
- );
641
- }
642
- reportBridgeFill(signal) {
643
- if (!this.relay.isConnected) return;
644
- this.relay.sendTradeSignal(signal);
645
- this.relay.sendMessage(
646
- "bridge_fill",
647
- "success",
648
- `Bridge ${signal.symbol}`,
649
- `Bridged ${signal.size} ${signal.symbol} to ${signal.chain ?? "unknown"} via ${signal.venue}`,
650
- { signal }
651
- );
652
- }
653
- reportError(title, body, data) {
654
- if (!this.relay.isConnected) return;
655
- this.relay.sendMessage("error", "error", title, body, data);
656
- }
657
- reportInfo(title, body, data) {
658
- if (!this.relay.isConnected) return;
659
- this.relay.sendMessage("info", "info", title, body, data);
660
- }
661
- };
662
-
663
- // src/store.ts
664
- import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, mkdirSync, existsSync as existsSync2 } from "fs";
665
- import { dirname } from "path";
666
- var FileStore = class {
667
- data = {};
668
- filePath;
669
- constructor(filePath = "data/strategy-store.json") {
670
- this.filePath = filePath;
671
- this.load();
672
- }
673
- load() {
674
- try {
675
- if (existsSync2(this.filePath)) {
676
- const raw = readFileSync2(this.filePath, "utf-8");
677
- this.data = JSON.parse(raw);
678
- }
679
- } catch {
680
- this.data = {};
681
- }
682
- }
683
- flush() {
684
- const dir = dirname(this.filePath);
685
- if (!existsSync2(dir)) {
686
- mkdirSync(dir, { recursive: true });
687
- }
688
- writeFileSync2(this.filePath, JSON.stringify(this.data, null, 2));
689
- }
690
- get(key) {
691
- return this.data[key];
692
- }
693
- set(key, value) {
694
- this.data[key] = value;
695
- this.flush();
696
- }
697
- delete(key) {
698
- delete this.data[key];
699
- this.flush();
700
- }
701
- keys() {
702
- return Object.keys(this.data);
703
- }
704
- };
705
-
706
- // src/position-tracker.ts
707
- var QUOTE_ASSETS = /* @__PURE__ */ new Set(["USDC", "USDbC", "DAI", "USDT", "EURC"]);
708
- var PERP_VENUES = /* @__PURE__ */ new Set(["hyperliquid_perp"]);
709
- var PREDICTION_VENUES = /* @__PURE__ */ new Set(["polymarket"]);
710
- var PositionTracker = class {
711
- positions = /* @__PURE__ */ new Map();
712
- trades = [];
713
- realizedPnL = 0;
714
- store;
715
- constructor(store) {
716
- this.store = store;
717
- this.load();
718
- }
719
- /** Build a unique position key: venue-scoped when venue is provided */
720
- positionKey(token, venue) {
721
- return venue ? `${venue}:${token}` : token;
722
- }
723
- load() {
724
- const saved = this.store.get("position_tracker");
725
- if (saved) {
726
- this.positions = new Map(saved.positions);
727
- this.trades = saved.trades;
728
- this.realizedPnL = saved.realizedPnL;
729
- }
730
- }
731
- save() {
732
- this.store.set("position_tracker", {
733
- positions: Array.from(this.positions.entries()),
734
- trades: this.trades.slice(-1e3),
735
- realizedPnL: this.realizedPnL
736
- });
737
- }
738
- /** Returns realized PnL from this trade (non-zero when closing/reducing a position) */
739
- recordBuy(token, quantity, price, fee, venue, chain, venueFillId) {
740
- const isPerp = venue ? PERP_VENUES.has(venue) : false;
741
- const isPrediction = venue ? PREDICTION_VENUES.has(venue) : false;
742
- if (!isPerp && !isPrediction && QUOTE_ASSETS.has(token)) return 0;
743
- const key = this.positionKey(token, venue);
744
- const existing = this.positions.get(key);
745
- let tradePnL = 0;
746
- if (existing) {
747
- if (isPerp && existing.quantity < 0) {
748
- const closedQty = Math.min(quantity, Math.abs(existing.quantity));
749
- tradePnL = (existing.costBasisPerUnit - price) * closedQty - fee;
750
- this.realizedPnL += tradePnL;
751
- existing.quantity += quantity;
752
- if (Math.abs(existing.quantity) <= 1e-6) {
753
- this.positions.delete(key);
754
- } else if (existing.quantity > 0) {
755
- existing.costBasisPerUnit = price;
756
- }
757
- } else {
758
- const totalQty = existing.quantity + quantity;
759
- const totalCost = existing.costBasisPerUnit * existing.quantity + price * quantity;
760
- existing.costBasisPerUnit = totalCost / totalQty;
761
- existing.quantity = totalQty;
762
- }
763
- } else {
764
- this.positions.set(key, {
765
- token,
766
- quantity,
767
- costBasisPerUnit: price,
768
- entryTimestamp: Date.now(),
769
- venue,
770
- chain
771
- });
772
- }
773
- this.trades.push({
774
- token,
775
- action: "buy",
776
- quantity,
777
- price,
778
- fee,
779
- timestamp: Date.now(),
780
- venue,
781
- chain,
782
- venueFillId
783
- });
784
- this.save();
785
- return tradePnL;
786
- }
787
- /** Returns realized PnL from this trade (non-zero when closing/reducing a position) */
788
- recordSell(token, quantity, price, fee, venue, chain, venueFillId) {
789
- const isPerp = venue ? PERP_VENUES.has(venue) : false;
790
- const isPrediction = venue ? PREDICTION_VENUES.has(venue) : false;
791
- if (!isPerp && !isPrediction && QUOTE_ASSETS.has(token)) return 0;
792
- const key = this.positionKey(token, venue);
793
- const existing = this.positions.get(key);
794
- let tradePnL = 0;
795
- if (existing) {
796
- if (isPerp && existing.quantity > 0) {
797
- const closedQty = Math.min(quantity, existing.quantity);
798
- tradePnL = (price - existing.costBasisPerUnit) * closedQty - fee;
799
- this.realizedPnL += tradePnL;
800
- existing.quantity -= quantity;
801
- if (Math.abs(existing.quantity) <= 1e-6) {
802
- this.positions.delete(key);
803
- } else if (existing.quantity < 0) {
804
- existing.costBasisPerUnit = price;
805
- }
806
- } else if (isPerp && existing.quantity <= 0) {
807
- const totalQty = Math.abs(existing.quantity) + quantity;
808
- const totalCost = existing.costBasisPerUnit * Math.abs(existing.quantity) + price * quantity;
809
- existing.costBasisPerUnit = totalCost / totalQty;
810
- existing.quantity -= quantity;
811
- } else {
812
- tradePnL = (price - existing.costBasisPerUnit) * quantity - fee;
813
- this.realizedPnL += tradePnL;
814
- existing.quantity -= quantity;
815
- if (existing.quantity <= 1e-6) {
816
- this.positions.delete(key);
817
- }
818
- }
819
- } else if (isPerp) {
820
- this.positions.set(key, {
821
- token,
822
- quantity: -quantity,
823
- costBasisPerUnit: price,
824
- entryTimestamp: Date.now(),
825
- venue,
826
- chain
827
- });
828
- }
829
- this.trades.push({
830
- token,
831
- action: "sell",
832
- quantity,
833
- price,
834
- fee,
835
- timestamp: Date.now(),
836
- venue,
837
- chain,
838
- venueFillId
839
- });
840
- this.save();
841
- return tradePnL;
842
- }
843
- getSummary(prices) {
844
- let totalUnrealizedPnL = 0;
845
- const openPositions = Array.from(this.positions.values());
846
- for (const pos of openPositions) {
847
- const currentPrice = prices[pos.token];
848
- if (currentPrice) {
849
- if (pos.quantity >= 0) {
850
- totalUnrealizedPnL += (currentPrice - pos.costBasisPerUnit) * pos.quantity;
851
- } else {
852
- totalUnrealizedPnL += (pos.costBasisPerUnit - currentPrice) * Math.abs(pos.quantity);
853
- }
854
- }
855
- }
856
- return {
857
- openPositions,
858
- totalUnrealizedPnL,
859
- totalRealizedPnL: this.realizedPnL
860
- };
861
- }
862
- getPositions() {
863
- return Array.from(this.positions.values());
864
- }
865
- getTrades(limit) {
866
- if (limit) return this.trades.slice(-limit);
867
- return [...this.trades];
868
- }
869
- getRealizedPnL() {
870
- return this.realizedPnL;
871
- }
872
- reset() {
873
- this.positions.clear();
874
- this.trades = [];
875
- this.realizedPnL = 0;
876
- this.save();
877
- }
878
- };
879
-
880
- // src/llm/base.ts
881
- var BaseLLMAdapter = class {
882
- config;
883
- constructor(config) {
884
- this.config = config;
885
- }
886
- getTemperature() {
887
- return this.config.temperature ?? 0.7;
888
- }
889
- getMaxTokens() {
890
- return this.config.maxTokens ?? 4096;
891
- }
892
- };
893
-
894
- // src/llm/openai.ts
895
- var OpenAIAdapter = class extends BaseLLMAdapter {
896
- endpoint;
897
- constructor(config) {
898
- super(config);
899
- this.endpoint = config.endpoint || "https://api.openai.com/v1";
900
- }
901
- async chat(messages) {
902
- const res = await fetch(`${this.endpoint}/chat/completions`, {
903
- method: "POST",
904
- headers: {
905
- "Content-Type": "application/json",
906
- Authorization: `Bearer ${this.config.apiKey}`
907
- },
908
- body: JSON.stringify({
909
- model: this.config.model || "gpt-4o",
910
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
911
- temperature: this.getTemperature(),
912
- max_tokens: this.getMaxTokens()
913
- })
914
- });
915
- if (!res.ok) {
916
- const body = await res.text();
917
- throw new Error(`OpenAI API error ${res.status}: ${body}`);
918
- }
919
- const data = await res.json();
920
- return {
921
- content: data.choices[0]?.message?.content || "",
922
- tokens: data.usage ? { input: data.usage.prompt_tokens, output: data.usage.completion_tokens } : void 0
923
- };
924
- }
925
- getMetadata() {
926
- return {
927
- provider: "openai",
928
- model: this.config.model || "gpt-4o"
929
- };
930
- }
931
- };
932
-
933
- // src/llm/anthropic.ts
934
- var AnthropicAdapter = class extends BaseLLMAdapter {
935
- endpoint;
936
- constructor(config) {
937
- super(config);
938
- this.endpoint = config.endpoint || "https://api.anthropic.com";
939
- }
940
- async chat(messages) {
941
- const systemMessage = messages.find((m) => m.role === "system");
942
- const nonSystemMessages = messages.filter((m) => m.role !== "system");
943
- const body = {
944
- model: this.config.model || "claude-sonnet-4-20250514",
945
- messages: nonSystemMessages.map((m) => ({ role: m.role, content: m.content })),
946
- max_tokens: this.getMaxTokens(),
947
- temperature: this.getTemperature()
948
- };
949
- if (systemMessage) {
950
- body.system = systemMessage.content;
951
- }
952
- const res = await fetch(`${this.endpoint}/v1/messages`, {
953
- method: "POST",
954
- headers: {
955
- "Content-Type": "application/json",
956
- "x-api-key": this.config.apiKey || "",
957
- "anthropic-version": "2023-06-01"
958
- },
959
- body: JSON.stringify(body)
960
- });
961
- if (!res.ok) {
962
- const text = await res.text();
963
- throw new Error(`Anthropic API error ${res.status}: ${text}`);
964
- }
965
- const data = await res.json();
966
- const textContent = data.content.find((c) => c.type === "text");
967
- return {
968
- content: textContent?.text || "",
969
- tokens: data.usage ? { input: data.usage.input_tokens, output: data.usage.output_tokens } : void 0
970
- };
971
- }
972
- getMetadata() {
973
- return {
974
- provider: "anthropic",
975
- model: this.config.model || "claude-sonnet-4-20250514"
976
- };
977
- }
978
- };
979
-
980
- // src/llm/google.ts
981
- var GoogleAdapter = class extends BaseLLMAdapter {
982
- constructor(config) {
983
- super(config);
984
- }
985
- async chat(messages) {
986
- const model = this.config.model || "gemini-2.5-flash";
987
- const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${this.config.apiKey}`;
988
- const systemMessage = messages.find((m) => m.role === "system");
989
- const nonSystemMessages = messages.filter((m) => m.role !== "system");
990
- const body = {
991
- contents: nonSystemMessages.map((m) => ({
992
- role: m.role === "assistant" ? "model" : "user",
993
- parts: [{ text: m.content }]
994
- })),
995
- generationConfig: {
996
- temperature: this.getTemperature(),
997
- maxOutputTokens: this.getMaxTokens()
998
- }
999
- };
1000
- if (systemMessage) {
1001
- body.systemInstruction = { parts: [{ text: systemMessage.content }] };
1002
- }
1003
- const res = await fetch(url, {
1004
- method: "POST",
1005
- headers: { "Content-Type": "application/json" },
1006
- body: JSON.stringify(body)
1007
- });
1008
- if (!res.ok) {
1009
- const text2 = await res.text();
1010
- throw new Error(`Google AI error ${res.status}: ${text2}`);
1011
- }
1012
- const data = await res.json();
1013
- const text = data.candidates[0]?.content?.parts[0]?.text || "";
1014
- return {
1015
- content: text,
1016
- tokens: data.usageMetadata ? { input: data.usageMetadata.promptTokenCount, output: data.usageMetadata.candidatesTokenCount } : void 0
1017
- };
1018
- }
1019
- getMetadata() {
1020
- return {
1021
- provider: "google",
1022
- model: this.config.model || "gemini-2.5-flash"
1023
- };
1024
- }
1025
- };
1026
-
1027
- // src/llm/deepseek.ts
1028
- var DeepSeekAdapter = class extends BaseLLMAdapter {
1029
- constructor(config) {
1030
- super(config);
1031
- }
1032
- async chat(messages) {
1033
- const res = await fetch("https://api.deepseek.com/chat/completions", {
1034
- method: "POST",
1035
- headers: {
1036
- "Content-Type": "application/json",
1037
- Authorization: `Bearer ${this.config.apiKey}`
1038
- },
1039
- body: JSON.stringify({
1040
- model: this.config.model || "deepseek-chat",
1041
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
1042
- temperature: this.getTemperature(),
1043
- max_tokens: this.getMaxTokens()
1044
- })
1045
- });
1046
- if (!res.ok) {
1047
- const body = await res.text();
1048
- throw new Error(`DeepSeek API error ${res.status}: ${body}`);
1049
- }
1050
- const data = await res.json();
1051
- return {
1052
- content: data.choices[0]?.message?.content || "",
1053
- tokens: data.usage ? { input: data.usage.prompt_tokens, output: data.usage.completion_tokens } : void 0
1054
- };
1055
- }
1056
- getMetadata() {
1057
- return {
1058
- provider: "deepseek",
1059
- model: this.config.model || "deepseek-chat"
1060
- };
1061
- }
1062
- };
1063
-
1064
- // src/llm/mistral.ts
1065
- var MistralAdapter = class extends BaseLLMAdapter {
1066
- constructor(config) {
1067
- super(config);
1068
- }
1069
- async chat(messages) {
1070
- const res = await fetch("https://api.mistral.ai/v1/chat/completions", {
1071
- method: "POST",
1072
- headers: {
1073
- "Content-Type": "application/json",
1074
- Authorization: `Bearer ${this.config.apiKey}`
1075
- },
1076
- body: JSON.stringify({
1077
- model: this.config.model || "mistral-large-latest",
1078
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
1079
- temperature: this.getTemperature(),
1080
- max_tokens: this.getMaxTokens()
1081
- })
1082
- });
1083
- if (!res.ok) {
1084
- const body = await res.text();
1085
- throw new Error(`Mistral API error ${res.status}: ${body}`);
1086
- }
1087
- const data = await res.json();
1088
- return {
1089
- content: data.choices[0]?.message?.content || "",
1090
- tokens: data.usage ? { input: data.usage.prompt_tokens, output: data.usage.completion_tokens } : void 0
1091
- };
1092
- }
1093
- getMetadata() {
1094
- return {
1095
- provider: "mistral",
1096
- model: this.config.model || "mistral-large-latest"
1097
- };
1098
- }
1099
- };
1100
-
1101
- // src/llm/groq.ts
1102
- var GroqAdapter = class extends BaseLLMAdapter {
1103
- constructor(config) {
1104
- super(config);
1105
- }
1106
- async chat(messages) {
1107
- const res = await fetch("https://api.groq.com/openai/v1/chat/completions", {
1108
- method: "POST",
1109
- headers: {
1110
- "Content-Type": "application/json",
1111
- Authorization: `Bearer ${this.config.apiKey}`
1112
- },
1113
- body: JSON.stringify({
1114
- model: this.config.model || "llama-3.3-70b-versatile",
1115
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
1116
- temperature: this.getTemperature(),
1117
- max_tokens: this.getMaxTokens()
1118
- })
1119
- });
1120
- if (!res.ok) {
1121
- const body = await res.text();
1122
- throw new Error(`Groq API error ${res.status}: ${body}`);
1123
- }
1124
- const data = await res.json();
1125
- return {
1126
- content: data.choices[0]?.message?.content || "",
1127
- tokens: data.usage ? { input: data.usage.prompt_tokens, output: data.usage.completion_tokens } : void 0
1128
- };
1129
- }
1130
- getMetadata() {
1131
- return {
1132
- provider: "groq",
1133
- model: this.config.model || "llama-3.3-70b-versatile"
1134
- };
1135
- }
1136
- };
1137
-
1138
- // src/llm/together.ts
1139
- var TogetherAdapter = class extends BaseLLMAdapter {
1140
- constructor(config) {
1141
- super(config);
1142
- }
1143
- async chat(messages) {
1144
- const res = await fetch("https://api.together.xyz/v1/chat/completions", {
1145
- method: "POST",
1146
- headers: {
1147
- "Content-Type": "application/json",
1148
- Authorization: `Bearer ${this.config.apiKey}`
1149
- },
1150
- body: JSON.stringify({
1151
- model: this.config.model || "meta-llama/Llama-3.3-70B-Instruct-Turbo",
1152
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
1153
- temperature: this.getTemperature(),
1154
- max_tokens: this.getMaxTokens()
1155
- })
1156
- });
1157
- if (!res.ok) {
1158
- const body = await res.text();
1159
- throw new Error(`Together API error ${res.status}: ${body}`);
1160
- }
1161
- const data = await res.json();
1162
- return {
1163
- content: data.choices[0]?.message?.content || "",
1164
- tokens: data.usage ? { input: data.usage.prompt_tokens, output: data.usage.completion_tokens } : void 0
1165
- };
1166
- }
1167
- getMetadata() {
1168
- return {
1169
- provider: "together",
1170
- model: this.config.model || "meta-llama/Llama-3.3-70B-Instruct-Turbo"
1171
- };
1172
- }
1173
- };
1174
-
1175
- // src/llm/ollama.ts
1176
- var OllamaAdapter = class extends BaseLLMAdapter {
1177
- endpoint;
1178
- constructor(config) {
1179
- super(config);
1180
- this.endpoint = config.endpoint || "http://localhost:11434";
1181
- }
1182
- async chat(messages) {
1183
- const res = await fetch(`${this.endpoint}/api/chat`, {
1184
- method: "POST",
1185
- headers: { "Content-Type": "application/json" },
1186
- body: JSON.stringify({
1187
- model: this.config.model || "llama3.3",
1188
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
1189
- stream: false,
1190
- options: {
1191
- temperature: this.getTemperature(),
1192
- num_predict: this.getMaxTokens()
1193
- }
1194
- })
1195
- });
1196
- if (!res.ok) {
1197
- const body = await res.text();
1198
- throw new Error(`Ollama error ${res.status}: ${body}`);
1199
- }
1200
- const data = await res.json();
1201
- return {
1202
- content: data.message?.content || "",
1203
- tokens: data.prompt_eval_count ? { input: data.prompt_eval_count, output: data.eval_count || 0 } : void 0
1204
- };
1205
- }
1206
- getMetadata() {
1207
- return {
1208
- provider: "ollama",
1209
- model: this.config.model || "llama3.3"
1210
- };
1211
- }
1212
- };
1213
-
1214
- // src/llm/index.ts
1215
- function createLLMAdapter(config) {
1216
- switch (config.provider) {
1217
- case "openai":
1218
- return new OpenAIAdapter(config);
1219
- case "anthropic":
1220
- return new AnthropicAdapter(config);
1221
- case "google":
1222
- return new GoogleAdapter(config);
1223
- case "deepseek":
1224
- return new DeepSeekAdapter(config);
1225
- case "mistral":
1226
- return new MistralAdapter(config);
1227
- case "groq":
1228
- return new GroqAdapter(config);
1229
- case "together":
1230
- return new TogetherAdapter(config);
1231
- case "ollama":
1232
- return new OllamaAdapter(config);
1233
- default:
1234
- throw new Error(`Unknown LLM provider: ${config.provider}`);
1235
- }
1236
- }
1237
-
1238
- // src/strategy/templates.ts
1239
- var templates = [
1240
- {
1241
- id: "momentum",
1242
- name: "Momentum Trader",
1243
- description: "Identifies tokens with strong upward price momentum and rides the trend. Uses LLM to analyze price action and market sentiment.",
1244
- category: "momentum",
1245
- venues: ["hyperliquid_perp", "hyperliquid_spot"],
1246
- riskLevel: "moderate",
1247
- systemPrompt: `You are a momentum trading agent. Analyze the provided market data and identify tokens with strong upward momentum.
1248
-
1249
- Rules:
1250
- - Only trade tokens with clear directional momentum (avoid choppy markets)
1251
- - Use trailing stops to protect gains
1252
- - Size positions based on conviction (higher confidence = larger position)
1253
- - Cut losses quickly if momentum reverses
1254
- - Consider volume as confirmation of momentum
1255
-
1256
- Return a JSON array of trade signals.`,
1257
- code: `
1258
- const prices = context.market.getPrices();
1259
- const positions = context.position.openPositions;
1260
-
1261
- const messages = [
1262
- { role: 'system', content: 'You are a momentum trading agent. Analyze market data and return trade signals as a JSON array. Each signal: { symbol, side: "buy"|"sell", confidence: 0-1, reasoning }. Return [] if no opportunities.' },
1263
- { role: 'user', content: 'Current prices: ' + JSON.stringify(prices) + '\\nOpen positions: ' + JSON.stringify(positions.map(p => p.token)) + '\\nAnalyze for momentum opportunities.' }
1264
- ];
1265
-
1266
- const response = await context.llm.chat(messages);
1267
- try {
1268
- const signals = JSON.parse(response.content);
1269
- return Array.isArray(signals) ? signals : [];
1270
- } catch {
1271
- return [];
1272
- }
1273
- `
1274
- },
1275
- {
1276
- id: "value",
1277
- name: "Value Investor",
1278
- description: "Identifies undervalued tokens based on fundamental analysis. Buys dips and holds for mean reversion.",
1279
- category: "value",
1280
- venues: ["hyperliquid_spot"],
1281
- riskLevel: "conservative",
1282
- systemPrompt: `You are a value investing agent. Identify tokens trading below their intrinsic value.
1283
-
1284
- Rules:
1285
- - Focus on established tokens with strong fundamentals
1286
- - Buy on significant dips (>10% from recent highs)
1287
- - Hold positions longer (swing/position timeframe)
1288
- - Avoid chasing pumps
1289
- - Diversify across sectors
1290
-
1291
- Return a JSON array of trade signals.`,
1292
- code: `
1293
- const prices = context.market.getPrices();
1294
- const positions = context.position.openPositions;
1295
-
1296
- const messages = [
1297
- { role: 'system', content: 'You are a value investing agent. Identify undervalued tokens. Return trade signals as JSON array: { symbol, side: "buy"|"sell", confidence: 0-1, reasoning }. Return [] if nothing is compelling.' },
1298
- { role: 'user', content: 'Current prices: ' + JSON.stringify(prices) + '\\nPositions: ' + JSON.stringify(positions.map(p => ({ token: p.token, entry: p.costBasisPerUnit }))) + '\\nLook for value opportunities.' }
1299
- ];
1300
-
1301
- const response = await context.llm.chat(messages);
1302
- try {
1303
- const signals = JSON.parse(response.content);
1304
- return Array.isArray(signals) ? signals : [];
1305
- } catch {
1306
- return [];
1307
- }
1308
- `
1309
- },
1310
- {
1311
- id: "arbitrage",
1312
- name: "Arbitrage Hunter",
1313
- description: "Scans for price discrepancies across venues and chains. Executes quickly to capture spreads.",
1314
- category: "arbitrage",
1315
- venues: ["hyperliquid_perp", "hyperliquid_spot", "uniswap", "aerodrome"],
1316
- riskLevel: "aggressive",
1317
- systemPrompt: `You are an arbitrage agent. Find price discrepancies between venues.
1318
-
1319
- Rules:
1320
- - Speed is critical \u2014 execute quickly before spreads close
1321
- - Account for fees and slippage in profitability calculations
1322
- - Only trade when net profit > 0.5% after all costs
1323
- - Monitor cross-chain opportunities (CEX vs DEX spreads)
1324
-
1325
- Return a JSON array of trade signals.`,
1326
- code: `
1327
- const prices = context.market.getPrices();
1328
-
1329
- const messages = [
1330
- { role: 'system', content: 'You are an arbitrage agent. Find price discrepancies. Return trade signals as JSON array: { symbol, side: "buy"|"sell", venue, confidence: 0-1, reasoning }. Return [] if no arb opportunities.' },
1331
- { role: 'user', content: 'Market prices: ' + JSON.stringify(prices) + '\\nScan for cross-venue arbitrage opportunities.' }
1332
- ];
1333
-
1334
- const response = await context.llm.chat(messages);
1335
- try {
1336
- const signals = JSON.parse(response.content);
1337
- return Array.isArray(signals) ? signals : [];
1338
- } catch {
1339
- return [];
1340
- }
1341
- `
1342
- },
1343
- {
1344
- id: "hold",
1345
- name: "Hold (No Trading)",
1346
- description: "Passive strategy that makes no trades. Useful for monitoring only.",
1347
- category: "custom",
1348
- venues: [],
1349
- riskLevel: "conservative",
1350
- systemPrompt: "",
1351
- code: `return [];`
1352
- }
1353
- ];
1354
- function getTemplate(id) {
1355
- return templates.find((t) => t.id === id);
1356
- }
1357
- function listTemplates() {
1358
- return [...templates];
1359
- }
1360
-
1361
- // src/strategy/loader.ts
1362
- import { existsSync as existsSync3 } from "fs";
1363
- import { resolve } from "path";
1364
- async function loadStrategy(config) {
1365
- if (config.file) {
1366
- return loadFromFile(config.file);
1367
- }
1368
- if (config.template) {
1369
- const template = getTemplate(config.template);
1370
- if (!template) {
1371
- throw new Error(`Unknown strategy template: ${config.template}. Available: momentum, value, arbitrage, hold`);
1372
- }
1373
- return loadFromCode(template.code);
1374
- }
1375
- return holdStrategy;
1376
- }
1377
- async function loadFromFile(filePath) {
1378
- const resolved = resolve(filePath);
1379
- if (!existsSync3(resolved)) {
1380
- throw new Error(`Strategy file not found: ${resolved}`);
1381
- }
1382
- try {
1383
- const mod = await import(resolved);
1384
- const fn = mod.default || mod.strategy;
1385
- if (typeof fn !== "function") {
1386
- throw new Error(`Strategy file must export a default function or 'strategy' function`);
1387
- }
1388
- return fn;
1389
- } catch (err) {
1390
- throw new Error(`Failed to load strategy from ${resolved}: ${err.message}`);
1391
- }
1392
- }
1393
- async function loadFromCode(code) {
1394
- const AsyncFunction = Object.getPrototypeOf(async function() {
1395
- }).constructor;
1396
- const fn = new AsyncFunction("context", code);
1397
- return fn;
1398
- }
1399
- var holdStrategy = async (_context) => {
1400
- return [];
1401
- };
1402
-
1403
- // src/trading/risk.ts
1404
- var RiskManager = class {
1405
- params;
1406
- dailyPnL = 0;
1407
- dailyFees = 0;
1408
- lastResetDate = "";
1409
- initialCapitalUSD;
1410
- constructor(params, initialCapitalUSD = 1e4) {
1411
- this.params = params;
1412
- this.initialCapitalUSD = initialCapitalUSD;
1413
- this.resetIfNewDay();
1414
- }
1415
- filterSignals(signals, market, openPositionCount) {
1416
- this.resetIfNewDay();
1417
- if (this.isDailyLossLimitHit()) {
1418
- console.log("[risk] Daily loss limit hit \u2014 blocking all trades");
1419
- return [];
1420
- }
1421
- return signals.filter((signal) => this.validateSignal(signal, market, openPositionCount));
1422
- }
1423
- validateSignal(signal, market, openPositionCount) {
1424
- const threshold = this.params.confidenceThreshold ?? 0.5;
1425
- if (signal.confidence !== void 0 && signal.confidence < threshold) {
1426
- console.log(`[risk] Blocked ${signal.symbol}: confidence ${signal.confidence} < ${threshold}`);
1427
- return false;
1428
- }
1429
- const leverage = signal.leverage || 1;
1430
- const tradeValue = signal.size * signal.price * leverage;
1431
- const maxPositionValue = this.params.maxPositionSizeBps / 1e4 * this.initialCapitalUSD;
1432
- if (tradeValue > maxPositionValue) {
1433
- console.log(`[risk] Blocked ${signal.symbol}: notional $${tradeValue.toFixed(0)} (${leverage}x leverage) > max $${maxPositionValue.toFixed(0)}`);
1434
- return false;
1435
- }
1436
- if (tradeValue < this.params.minTradeValueUSD) {
1437
- console.log(`[risk] Blocked ${signal.symbol}: trade $${tradeValue.toFixed(2)} < min $${this.params.minTradeValueUSD}`);
1438
- return false;
1439
- }
1440
- if ((signal.side === "buy" || signal.side === "long") && openPositionCount >= this.params.maxConcurrentPositions) {
1441
- console.log(`[risk] Blocked ${signal.symbol}: ${openPositionCount} positions >= max ${this.params.maxConcurrentPositions}`);
1442
- return false;
1443
- }
1444
- if (signal.orderType === "market") {
1445
- const currentPrice = market.getPrice(signal.symbol);
1446
- if (currentPrice) {
1447
- const slippageBps = Math.abs(signal.price - currentPrice) / currentPrice * 1e4;
1448
- if (slippageBps > this.params.maxSlippageBps) {
1449
- console.log(`[risk] Blocked ${signal.symbol}: slippage ${slippageBps.toFixed(0)}bps > max ${this.params.maxSlippageBps}bps`);
1450
- return false;
1451
- }
1452
- }
1453
- }
1454
- return true;
1455
- }
1456
- updateParams(updates) {
1457
- if (updates.maxPositionSizeBps !== void 0) this.params.maxPositionSizeBps = updates.maxPositionSizeBps;
1458
- if (updates.maxDailyLossBps !== void 0) this.params.maxDailyLossBps = updates.maxDailyLossBps;
1459
- if (updates.maxConcurrentPositions !== void 0) this.params.maxConcurrentPositions = updates.maxConcurrentPositions;
1460
- if (updates.maxSlippageBps !== void 0) this.params.maxSlippageBps = updates.maxSlippageBps;
1461
- if (updates.minTradeValueUSD !== void 0) this.params.minTradeValueUSD = updates.minTradeValueUSD;
1462
- console.log("[risk] Params updated:", JSON.stringify(this.params));
1463
- }
1464
- recordTrade(pnl, fee) {
1465
- this.dailyPnL += pnl;
1466
- this.dailyFees += fee;
1467
- }
1468
- isDailyLossLimitHit() {
1469
- const limit = this.params.maxDailyLossBps / 1e4 * this.initialCapitalUSD;
1470
- return this.dailyPnL < -limit;
1471
- }
1472
- getDailyPnL() {
1473
- return this.dailyPnL;
1474
- }
1475
- getDailyLossLimit() {
1476
- return this.params.maxDailyLossBps / 1e4 * this.initialCapitalUSD;
1477
- }
1478
- resetIfNewDay() {
1479
- const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
1480
- if (today !== this.lastResetDate) {
1481
- this.dailyPnL = 0;
1482
- this.dailyFees = 0;
1483
- this.lastResetDate = today;
1484
- }
1485
- }
1486
- };
1487
-
1488
- // src/trading/market.ts
1489
- var MarketDataService = class {
1490
- prices = {};
1491
- lastFetch = 0;
1492
- cacheTTL;
1493
- apiUrl;
1494
- ohlcvCache = /* @__PURE__ */ new Map();
1495
- constructor(cacheTTLMs = 3e4, apiUrl) {
1496
- this.cacheTTL = cacheTTLMs;
1497
- this.apiUrl = apiUrl || null;
1498
- }
1499
- async refreshPrices(symbols) {
1500
- if (symbols.length === 0) return this.prices;
1501
- const now = Date.now();
1502
- if (now - this.lastFetch < this.cacheTTL && Object.keys(this.prices).length > 0) {
1503
- return this.prices;
1504
- }
1505
- if (this.apiUrl) {
1506
- try {
1507
- const res = await fetch(`${this.apiUrl}/v1/prices`);
1508
- if (res.ok) {
1509
- const data = await res.json();
1510
- for (const [symbol, price] of Object.entries(data)) {
1511
- this.prices[symbol.toUpperCase()] = price;
1512
- }
1513
- this.lastFetch = now;
1514
- return this.prices;
1515
- }
1516
- } catch {
1517
- }
1518
- }
1519
- try {
1520
- const ids = symbols.map((s) => s.toLowerCase()).join(",");
1521
- const res = await fetch(
1522
- `https://api.coingecko.com/api/v3/simple/price?ids=${ids}&vs_currencies=usd`
1523
- );
1524
- if (res.ok) {
1525
- const data = await res.json();
1526
- for (const [id, price] of Object.entries(data)) {
1527
- this.prices[id.toUpperCase()] = price.usd;
1528
- }
1529
- this.lastFetch = now;
1530
- }
1531
- } catch (err) {
1532
- console.warn("[market] Price fetch failed:", err.message);
1533
- }
1534
- return this.prices;
1535
- }
1536
- getPrice(symbol) {
1537
- return this.prices[symbol.toUpperCase()];
1538
- }
1539
- getPrices() {
1540
- return { ...this.prices };
1541
- }
1542
- setPrice(symbol, price) {
1543
- this.prices[symbol.toUpperCase()] = price;
1544
- }
1545
- setPrices(prices) {
1546
- for (const [symbol, price] of Object.entries(prices)) {
1547
- this.prices[symbol.toUpperCase()] = price;
1548
- }
1549
- }
1550
- getOHLCV(symbol, timeframe) {
1551
- const cacheKey = `${symbol.toUpperCase()}:${timeframe}`;
1552
- const cached = this.ohlcvCache.get(cacheKey);
1553
- if (cached && Date.now() - cached.fetchedAt < this.cacheTTL) {
1554
- return cached.data;
1555
- }
1556
- this.fetchOHLCV(symbol, timeframe).catch(() => {
1557
- });
1558
- return cached?.data || [];
1559
- }
1560
- async fetchOHLCV(symbol, timeframe) {
1561
- const cacheKey = `${symbol.toUpperCase()}:${timeframe}`;
1562
- if (this.apiUrl) {
1563
- try {
1564
- const res = await fetch(
1565
- `${this.apiUrl}/v1/prices/${symbol.toUpperCase()}/ohlcv?interval=${timeframe}&limit=100`
1566
- );
1567
- if (res.ok) {
1568
- const bars = await res.json();
1569
- const ohlcv = bars.map((b) => ({
1570
- timestamp: b.t,
1571
- open: b.o,
1572
- high: b.h,
1573
- low: b.l,
1574
- close: b.c,
1575
- volume: b.v
1576
- }));
1577
- this.ohlcvCache.set(cacheKey, { data: ohlcv, fetchedAt: Date.now() });
1578
- return;
1579
- }
1580
- } catch {
1581
- }
1582
- }
1583
- }
1584
- };
1585
-
1586
- // src/paper/executor.ts
1587
- import { randomUUID } from "crypto";
1588
- var PaperExecutor = class {
1589
- cash;
1590
- positions = /* @__PURE__ */ new Map();
1591
- trades = [];
1592
- equityCurve = [];
1593
- slippageBps;
1594
- feeRate;
1595
- peakEquity;
1596
- maxDrawdown = 0;
1597
- constructor(initialCash = 1e4, slippageBps = 50, feeRate = 2e-3) {
1598
- this.cash = initialCash;
1599
- this.slippageBps = slippageBps;
1600
- this.feeRate = feeRate;
1601
- this.peakEquity = initialCash;
1602
- this.recordEquity();
1603
- }
1604
- execute(signal, market) {
1605
- const marketPrice = market.getPrice(signal.symbol);
1606
- if (!marketPrice) {
1607
- console.warn(`[paper] No price for ${signal.symbol}`);
1608
- return null;
1609
- }
1610
- const isBuy = signal.side === "buy" || signal.side === "long";
1611
- const slippage = this.slippageBps / 1e4 * marketPrice;
1612
- const executedPrice = isBuy ? marketPrice + slippage : marketPrice - slippage;
1613
- const fee = signal.size * executedPrice * this.feeRate;
1614
- let realizedPnL = 0;
1615
- if (isBuy) {
1616
- const totalCost = signal.size * executedPrice + fee;
1617
- if (totalCost > this.cash) {
1618
- console.warn(`[paper] Insufficient funds: need $${totalCost.toFixed(2)}, have $${this.cash.toFixed(2)}`);
1619
- return null;
1620
- }
1621
- this.cash -= totalCost;
1622
- const existing = this.positions.get(signal.symbol);
1623
- if (existing) {
1624
- const totalQty = existing.quantity + signal.size;
1625
- existing.avgPrice = (existing.avgPrice * existing.quantity + executedPrice * signal.size) / totalQty;
1626
- existing.quantity = totalQty;
1627
- } else {
1628
- this.positions.set(signal.symbol, { quantity: signal.size, avgPrice: executedPrice });
1629
- }
1630
- } else {
1631
- const existing = this.positions.get(signal.symbol);
1632
- if (!existing || existing.quantity < signal.size) {
1633
- console.warn(`[paper] No position to sell: ${signal.symbol}`);
1634
- return null;
1635
- }
1636
- realizedPnL = (executedPrice - existing.avgPrice) * signal.size - fee;
1637
- const proceeds = signal.size * executedPrice - fee;
1638
- this.cash += proceeds;
1639
- existing.quantity -= signal.size;
1640
- if (existing.quantity <= 1e-6) {
1641
- this.positions.delete(signal.symbol);
1642
- }
1643
- }
1644
- const trade = {
1645
- id: randomUUID(),
1646
- symbol: signal.symbol,
1647
- side: isBuy ? "buy" : "sell",
1648
- size: signal.size,
1649
- entryPrice: executedPrice,
1650
- fee,
1651
- pnl: realizedPnL !== 0 ? realizedPnL : void 0,
1652
- timestamp: Date.now(),
1653
- venue: `paper_${signal.venue}`
1654
- };
1655
- this.trades.push(trade);
1656
- this.recordEquity();
1657
- return trade;
1658
- }
1659
- /** Update equity snapshot with current market prices */
1660
- recordEquityWithPrices(prices) {
1661
- this.currentPrices = prices;
1662
- this.recordEquity();
1663
- }
1664
- currentPrices = {};
1665
- recordEquity() {
1666
- const equity = this.getEquity();
1667
- this.equityCurve.push({ timestamp: Date.now(), equity });
1668
- if (equity > this.peakEquity) this.peakEquity = equity;
1669
- const drawdown = (this.peakEquity - equity) / this.peakEquity;
1670
- if (drawdown > this.maxDrawdown) this.maxDrawdown = drawdown;
1671
- }
1672
- /** Calculate equity using current market prices (falls back to cost basis if no price available) */
1673
- getEquity() {
1674
- let positionValue = 0;
1675
- for (const [symbol, pos] of this.positions) {
1676
- const currentPrice = this.currentPrices[symbol.toUpperCase()] ?? this.currentPrices[symbol] ?? pos.avgPrice;
1677
- positionValue += pos.quantity * currentPrice;
1678
- }
1679
- return this.cash + positionValue;
1680
- }
1681
- getCash() {
1682
- return this.cash;
1683
- }
1684
- getPositions() {
1685
- return new Map(this.positions);
1686
- }
1687
- getTrades() {
1688
- return [...this.trades];
1689
- }
1690
- getEquityCurve() {
1691
- return [...this.equityCurve];
1692
- }
1693
- getMetrics() {
1694
- const initialEquity = this.equityCurve[0]?.equity || 0;
1695
- const currentEquity = this.getEquity();
1696
- const totalReturn = initialEquity > 0 ? (currentEquity - initialEquity) / initialEquity : 0;
1697
- const dailyReturns = this.calculateDailyReturns();
1698
- const sharpeRatio = this.calculateSharpe(dailyReturns);
1699
- let wins = 0;
1700
- let losses = 0;
1701
- let grossProfit = 0;
1702
- let grossLoss = 0;
1703
- const sellTrades = this.trades.filter((t) => t.side === "sell");
1704
- for (const sell of sellTrades) {
1705
- const buyTrades = this.trades.filter((t) => t.side === "buy" && t.symbol === sell.symbol);
1706
- const avgEntry = buyTrades.reduce((sum, t) => sum + t.entryPrice, 0) / (buyTrades.length || 1);
1707
- const pnl = (sell.entryPrice - avgEntry) * sell.size - sell.fee;
1708
- if (pnl > 0) {
1709
- wins++;
1710
- grossProfit += pnl;
1711
- } else {
1712
- losses++;
1713
- grossLoss += Math.abs(pnl);
1714
- }
1715
- }
1716
- return {
1717
- totalReturn,
1718
- sharpeRatio,
1719
- maxDrawdown: this.maxDrawdown,
1720
- winRate: wins + losses > 0 ? wins / (wins + losses) : 0,
1721
- profitFactor: grossLoss > 0 ? grossProfit / grossLoss : grossProfit > 0 ? Infinity : 0,
1722
- totalTrades: this.trades.length
1723
- };
1724
- }
1725
- calculateDailyReturns() {
1726
- if (this.equityCurve.length < 2) return [];
1727
- const dailyEquity = /* @__PURE__ */ new Map();
1728
- for (const point of this.equityCurve) {
1729
- const date = new Date(point.timestamp).toISOString().slice(0, 10);
1730
- dailyEquity.set(date, point.equity);
1731
- }
1732
- const dates = Array.from(dailyEquity.keys()).sort();
1733
- const returns = [];
1734
- for (let i = 1; i < dates.length; i++) {
1735
- const prev = dailyEquity.get(dates[i - 1]);
1736
- const curr = dailyEquity.get(dates[i]);
1737
- if (prev > 0) returns.push((curr - prev) / prev);
1738
- }
1739
- return returns;
1740
- }
1741
- calculateSharpe(returns) {
1742
- if (returns.length < 2) return 0;
1743
- const mean = returns.reduce((a, b) => a + b, 0) / returns.length;
1744
- const variance = returns.reduce((sum, r) => sum + (r - mean) ** 2, 0) / (returns.length - 1);
1745
- const std = Math.sqrt(variance);
1746
- if (std === 0) return 0;
1747
- return mean / std * Math.sqrt(365);
1748
- }
1749
- };
1750
-
1751
- // src/perp/client.ts
1752
- var HyperliquidClient = class {
1753
- apiUrl;
1754
- meta = null;
1755
- assetIndexCache = /* @__PURE__ */ new Map();
1756
- constructor(config) {
1757
- this.apiUrl = config.apiUrl;
1758
- }
1759
- // ── INFO API (read-only) ───────────────────────────────────
1760
- async getMeta() {
1761
- if (this.meta) return this.meta;
1762
- const resp = await this.infoRequest({ type: "meta" });
1763
- this.meta = resp.universe;
1764
- this.meta.forEach((asset, idx) => {
1765
- this.assetIndexCache.set(asset.name, idx);
1766
- });
1767
- return this.meta;
1768
- }
1769
- async getAssetIndex(coin) {
1770
- if (this.assetIndexCache.has(coin)) return this.assetIndexCache.get(coin);
1771
- await this.getMeta();
1772
- const idx = this.assetIndexCache.get(coin);
1773
- if (idx === void 0) throw new Error(`Unknown instrument: ${coin}`);
1774
- return idx;
1775
- }
1776
- /** Get the size decimal precision for an instrument (for order size rounding) */
1777
- async getSzDecimals(coin) {
1778
- const meta = await this.getMeta();
1779
- const asset = meta.find((a) => a.name === coin);
1780
- if (!asset) throw new Error(`Unknown instrument: ${coin}`);
1781
- return asset.szDecimals;
1782
- }
1783
- async getAllMids() {
1784
- return this.infoRequest({ type: "allMids" });
1785
- }
1786
- async getClearinghouseState(user) {
1787
- return this.infoRequest({ type: "clearinghouseState", user });
1788
- }
1789
- async getUserFills(user, startTime) {
1790
- return this.infoRequest({
1791
- type: "userFills",
1792
- user,
1793
- ...startTime !== void 0 && { startTime }
1794
- });
1795
- }
1796
- async getUserFillsByTime(user, startTime, endTime) {
1797
- return this.infoRequest({
1798
- type: "userFillsByTime",
1799
- user,
1800
- startTime,
1801
- ...endTime !== void 0 && { endTime }
1802
- });
1803
- }
1804
- async getOpenOrders(user) {
1805
- return this.infoRequest({ type: "openOrders", user });
1806
- }
1807
- async getL2Book(coin, depth) {
1808
- return this.infoRequest({
1809
- type: "l2Book",
1810
- coin,
1811
- ...depth !== void 0 && { nSigFigs: depth }
1812
- });
1813
- }
1814
- // ── HIGH-LEVEL HELPERS ─────────────────────────────────────
1815
- async getPositions(user) {
1816
- const state = await this.getClearinghouseState(user);
1817
- return state.assetPositions.filter((p) => parseFloat(p.position.szi) !== 0).map((p) => this.parsePosition(p));
1818
- }
1819
- async getAccountSummary(user) {
1820
- const state = await this.getClearinghouseState(user);
1821
- const cms = state.crossMarginSummary;
1822
- const totalEquity = parseFloat(cms.accountValue);
1823
- const totalNotional = parseFloat(cms.totalNtlPos);
1824
- const totalMarginUsed = parseFloat(cms.totalMarginUsed);
1825
- return {
1826
- totalEquity,
1827
- availableMargin: totalEquity - totalMarginUsed,
1828
- totalMarginUsed,
1829
- totalUnrealizedPnl: parseFloat(cms.totalRawUsd) - totalEquity,
1830
- totalNotional,
1831
- maintenanceMargin: totalMarginUsed * 0.5,
1832
- effectiveLeverage: totalEquity > 0 ? totalNotional / totalEquity : 0,
1833
- cashBalance: parseFloat(cms.accountValue) - state.assetPositions.reduce(
1834
- (sum, p) => sum + parseFloat(p.position.unrealizedPnl),
1835
- 0
1836
- )
1837
- };
1838
- }
1839
- async getMarketData(instruments) {
1840
- const mids = await this.getAllMids();
1841
- return instruments.filter((inst) => mids[inst] !== void 0).map((inst) => ({
1842
- instrument: inst,
1843
- midPrice: parseFloat(mids[inst]),
1844
- bestBid: parseFloat(mids[inst]),
1845
- bestAsk: parseFloat(mids[inst]),
1846
- funding8h: 0,
1847
- openInterest: 0,
1848
- volume24h: 0,
1849
- priceChange24h: 0
1850
- }));
1851
- }
1852
- parseFill(fill) {
1853
- return {
1854
- oid: fill.oid,
1855
- coin: fill.coin,
1856
- side: fill.side,
1857
- px: fill.px,
1858
- sz: fill.sz,
1859
- fee: fill.fee,
1860
- time: fill.time,
1861
- hash: fill.hash,
1862
- isMaker: fill.startPosition !== fill.px,
1863
- builderFee: fill.builderFee,
1864
- liquidation: fill.liquidation
1865
- };
1866
- }
1867
- // ── PRIVATE ────────────────────────────────────────────────
1868
- parsePosition(ap) {
1869
- const pos = ap.position;
1870
- const size = parseFloat(pos.szi);
1871
- const entryPrice = parseFloat(pos.entryPx || "0");
1872
- const markPrice = parseFloat(pos.positionValue || "0") / Math.abs(size || 1);
1873
- return {
1874
- instrument: pos.coin,
1875
- assetIndex: this.assetIndexCache.get(pos.coin) ?? -1,
1876
- size,
1877
- entryPrice,
1878
- markPrice,
1879
- unrealizedPnl: parseFloat(pos.unrealizedPnl),
1880
- leverage: parseFloat(pos.leverage?.value || "1"),
1881
- marginType: pos.leverage?.type === "isolated" ? "isolated" : "cross",
1882
- liquidationPrice: parseFloat(pos.liquidationPx || "0"),
1883
- notionalUSD: Math.abs(size) * markPrice,
1884
- marginUsed: parseFloat(pos.marginUsed)
1885
- };
1886
- }
1887
- async infoRequest(body) {
1888
- const resp = await fetch(`${this.apiUrl}/info`, {
1889
- method: "POST",
1890
- headers: { "Content-Type": "application/json" },
1891
- body: JSON.stringify(body)
1892
- });
1893
- if (!resp.ok) {
1894
- throw new Error(`Hyperliquid Info API error: ${resp.status} ${await resp.text()}`);
1895
- }
1896
- return resp.json();
1897
- }
1898
- };
1899
-
1900
- // src/perp/signer.ts
1901
- import { keccak256 } from "viem";
1902
-
1903
- // src/perp/msgpack.ts
1904
- var FOUR_BITS = 16;
1905
- var FIVE_BITS = 32;
1906
- var SEVEN_BITS = 128;
1907
- var EIGHT_BITS = 256;
1908
- var FIFTEEN_BITS = 32768;
1909
- var SIXTEEN_BITS = 65536;
1910
- var THIRTY_ONE_BITS = 2147483648;
1911
- var THIRTY_TWO_BITS = 4294967296;
1912
- var SIXTY_THREE_BITS = 9223372036854775808n;
1913
- var SIXTY_FOUR_BITS = 18446744073709551616n;
1914
- var textEncoder = new TextEncoder();
1915
- function encodeMsgpack(object) {
1916
- const byteParts = [];
1917
- encodeSlice(object, byteParts);
1918
- return concatBytes(...byteParts);
1919
- }
1920
- function concatBytes(...arrays) {
1921
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
1922
- const result = new Uint8Array(totalLength);
1923
- let offset = 0;
1924
- for (const arr of arrays) {
1925
- result.set(arr, offset);
1926
- offset += arr.length;
1927
- }
1928
- return result;
1929
- }
1930
- function encodeFloat64(num) {
1931
- const dataView = new DataView(new ArrayBuffer(9));
1932
- dataView.setFloat64(1, num);
1933
- dataView.setUint8(0, 203);
1934
- return new Uint8Array(dataView.buffer);
1935
- }
1936
- function encodeNumber(num) {
1937
- if (!Number.isInteger(num)) return encodeFloat64(num);
1938
- if (num < 0) {
1939
- if (num >= -FIVE_BITS) return new Uint8Array([num & 255]);
1940
- if (num >= -SEVEN_BITS) return new Uint8Array([208, num & 255]);
1941
- if (num >= -FIFTEEN_BITS) {
1942
- const dv = new DataView(new ArrayBuffer(3));
1943
- dv.setInt16(1, num);
1944
- dv.setUint8(0, 209);
1945
- return new Uint8Array(dv.buffer);
1946
- }
1947
- if (num >= -THIRTY_ONE_BITS) {
1948
- const dv = new DataView(new ArrayBuffer(5));
1949
- dv.setInt32(1, num);
1950
- dv.setUint8(0, 210);
1951
- return new Uint8Array(dv.buffer);
1952
- }
1953
- return encodeFloat64(num);
1954
- }
1955
- if (num <= 127) return new Uint8Array([num]);
1956
- if (num < EIGHT_BITS) return new Uint8Array([204, num]);
1957
- if (num < SIXTEEN_BITS) {
1958
- const dv = new DataView(new ArrayBuffer(3));
1959
- dv.setUint16(1, num);
1960
- dv.setUint8(0, 205);
1961
- return new Uint8Array(dv.buffer);
1962
- }
1963
- if (num < THIRTY_TWO_BITS) {
1964
- const dv = new DataView(new ArrayBuffer(5));
1965
- dv.setUint32(1, num);
1966
- dv.setUint8(0, 206);
1967
- return new Uint8Array(dv.buffer);
1968
- }
1969
- return encodeFloat64(num);
1970
- }
1971
- function encodeSlice(object, byteParts) {
1972
- if (object === null) {
1973
- byteParts.push(new Uint8Array([192]));
1974
- return;
1975
- }
1976
- if (object === false) {
1977
- byteParts.push(new Uint8Array([194]));
1978
- return;
1979
- }
1980
- if (object === true) {
1981
- byteParts.push(new Uint8Array([195]));
1982
- return;
1983
- }
1984
- if (typeof object === "number") {
1985
- byteParts.push(encodeNumber(object));
1986
- return;
1987
- }
1988
- if (typeof object === "bigint") {
1989
- if (object < 0) {
1990
- if (object < -SIXTY_THREE_BITS)
1991
- throw new Error("Cannot safely encode bigint larger than 64 bits");
1992
- const dv2 = new DataView(new ArrayBuffer(9));
1993
- dv2.setBigInt64(1, object);
1994
- dv2.setUint8(0, 211);
1995
- byteParts.push(new Uint8Array(dv2.buffer));
1996
- return;
1997
- }
1998
- if (object >= SIXTY_FOUR_BITS)
1999
- throw new Error("Cannot safely encode bigint larger than 64 bits");
2000
- const dv = new DataView(new ArrayBuffer(9));
2001
- dv.setBigUint64(1, object);
2002
- dv.setUint8(0, 207);
2003
- byteParts.push(new Uint8Array(dv.buffer));
2004
- return;
2005
- }
2006
- if (typeof object === "string") {
2007
- const encoded = textEncoder.encode(object);
2008
- const len = encoded.length;
2009
- if (len < FIVE_BITS) byteParts.push(new Uint8Array([160 | len]));
2010
- else if (len < EIGHT_BITS) byteParts.push(new Uint8Array([217, len]));
2011
- else if (len < SIXTEEN_BITS) {
2012
- const dv = new DataView(new ArrayBuffer(3));
2013
- dv.setUint16(1, len);
2014
- dv.setUint8(0, 218);
2015
- byteParts.push(new Uint8Array(dv.buffer));
2016
- } else if (len < THIRTY_TWO_BITS) {
2017
- const dv = new DataView(new ArrayBuffer(5));
2018
- dv.setUint32(1, len);
2019
- dv.setUint8(0, 219);
2020
- byteParts.push(new Uint8Array(dv.buffer));
2021
- } else {
2022
- throw new Error("Cannot safely encode string with size larger than 32 bits");
2023
- }
2024
- byteParts.push(encoded);
2025
- return;
2026
- }
2027
- if (object instanceof Uint8Array) {
2028
- if (object.length < EIGHT_BITS) {
2029
- byteParts.push(new Uint8Array([196, object.length]));
2030
- } else if (object.length < SIXTEEN_BITS) {
2031
- const dv = new DataView(new ArrayBuffer(3));
2032
- dv.setUint16(1, object.length);
2033
- dv.setUint8(0, 197);
2034
- byteParts.push(new Uint8Array(dv.buffer));
2035
- } else if (object.length < THIRTY_TWO_BITS) {
2036
- const dv = new DataView(new ArrayBuffer(5));
2037
- dv.setUint32(1, object.length);
2038
- dv.setUint8(0, 198);
2039
- byteParts.push(new Uint8Array(dv.buffer));
2040
- } else {
2041
- throw new Error("Cannot safely encode Uint8Array with size larger than 32 bits");
2042
- }
2043
- byteParts.push(object);
2044
- return;
2045
- }
2046
- if (Array.isArray(object)) {
2047
- if (object.length < FOUR_BITS) byteParts.push(new Uint8Array([144 | object.length]));
2048
- else if (object.length < SIXTEEN_BITS) {
2049
- const dv = new DataView(new ArrayBuffer(3));
2050
- dv.setUint16(1, object.length);
2051
- dv.setUint8(0, 220);
2052
- byteParts.push(new Uint8Array(dv.buffer));
2053
- } else if (object.length < THIRTY_TWO_BITS) {
2054
- const dv = new DataView(new ArrayBuffer(5));
2055
- dv.setUint32(1, object.length);
2056
- dv.setUint8(0, 221);
2057
- byteParts.push(new Uint8Array(dv.buffer));
2058
- } else {
2059
- throw new Error("Cannot safely encode array with size larger than 32 bits");
2060
- }
2061
- for (const obj of object) encodeSlice(obj, byteParts);
2062
- return;
2063
- }
2064
- if (typeof object === "object") {
2065
- const entries = Object.entries(object);
2066
- const numKeys = entries.length;
2067
- if (numKeys < FOUR_BITS) byteParts.push(new Uint8Array([128 | numKeys]));
2068
- else if (numKeys < SIXTEEN_BITS) {
2069
- const dv = new DataView(new ArrayBuffer(3));
2070
- dv.setUint16(1, numKeys);
2071
- dv.setUint8(0, 222);
2072
- byteParts.push(new Uint8Array(dv.buffer));
2073
- } else if (numKeys < THIRTY_TWO_BITS) {
2074
- const dv = new DataView(new ArrayBuffer(5));
2075
- dv.setUint32(1, numKeys);
2076
- dv.setUint8(0, 223);
2077
- byteParts.push(new Uint8Array(dv.buffer));
2078
- } else {
2079
- throw new Error("Cannot safely encode map with size larger than 32 bits");
2080
- }
2081
- for (const [key, value] of entries) {
2082
- encodeSlice(key, byteParts);
2083
- encodeSlice(value, byteParts);
2084
- }
2085
- return;
2086
- }
2087
- throw new Error("Cannot safely encode value into messagepack");
2088
- }
2089
- function largeIntToBigInt(obj) {
2090
- if (typeof obj === "number" && Number.isInteger(obj) && (obj >= 4294967296 || obj < -2147483648)) {
2091
- return BigInt(obj);
2092
- }
2093
- if (Array.isArray(obj)) return obj.map(largeIntToBigInt);
2094
- if (typeof obj === "object" && obj !== null && !(obj instanceof Uint8Array)) {
2095
- const result = {};
2096
- for (const key in obj) {
2097
- result[key] = largeIntToBigInt(obj[key]);
2098
- }
2099
- return result;
2100
- }
2101
- return obj;
2102
- }
2103
- function removeUndefinedKeys(obj) {
2104
- if (Array.isArray(obj)) return obj.map(removeUndefinedKeys);
2105
- if (typeof obj === "object" && obj !== null && !(obj instanceof Uint8Array)) {
2106
- const result = {};
2107
- for (const key in obj) {
2108
- const val = obj[key];
2109
- if (val !== void 0) {
2110
- result[key] = removeUndefinedKeys(val);
2111
- }
2112
- }
2113
- return result;
2114
- }
2115
- return obj;
2116
- }
2117
- function toUint64Bytes(n) {
2118
- const bytes = new Uint8Array(8);
2119
- new DataView(bytes.buffer).setBigUint64(0, BigInt(n));
2120
- return bytes;
2121
- }
2122
-
2123
- // src/perp/signer.ts
2124
- var HYPERLIQUID_DOMAIN = {
2125
- name: "Exchange",
2126
- version: "1",
2127
- chainId: 1337,
2128
- verifyingContract: "0x0000000000000000000000000000000000000000"
2129
- };
2130
- var HYPERLIQUID_USER_DOMAIN = {
2131
- name: "HyperliquidSignTransaction",
2132
- version: "1",
2133
- chainId: 42161,
2134
- verifyingContract: "0x0000000000000000000000000000000000000000"
2135
- };
2136
- var USER_ACTION_TYPES = {
2137
- withdraw: {
2138
- "HyperliquidTransaction:Withdraw": [
2139
- { name: "hyperliquidChain", type: "string" },
2140
- { name: "destination", type: "string" },
2141
- { name: "amount", type: "string" },
2142
- { name: "time", type: "uint64" }
2143
- ]
2144
- },
2145
- usdSend: {
2146
- "HyperliquidTransaction:UsdSend": [
2147
- { name: "hyperliquidChain", type: "string" },
2148
- { name: "destination", type: "string" },
2149
- { name: "amount", type: "string" },
2150
- { name: "time", type: "uint64" }
2151
- ]
2152
- }
2153
- };
2154
- var PHANTOM_AGENT_TYPES = {
2155
- Agent: [
2156
- { name: "source", type: "string" },
2157
- { name: "connectionId", type: "bytes32" }
2158
- ]
2159
- };
2160
- var lastNonce = 0n;
2161
- function getNextNonce() {
2162
- const now = BigInt(Date.now());
2163
- if (now <= lastNonce) {
2164
- lastNonce = lastNonce + 1n;
2165
- } else {
2166
- lastNonce = now;
2167
- }
2168
- return lastNonce;
2169
- }
2170
- function createL1ActionHash(args) {
2171
- const { action, nonce, vaultAddress } = args;
2172
- const cleaned = removeUndefinedKeys(action);
2173
- const withBigInts = largeIntToBigInt(cleaned);
2174
- const actionBytes = encodeMsgpack(withBigInts);
2175
- const nonceBytes = toUint64Bytes(nonce);
2176
- const vaultMarker = vaultAddress ? new Uint8Array([1]) : new Uint8Array([0]);
2177
- const vaultBytes = vaultAddress ? hexToBytes(vaultAddress.slice(2)) : new Uint8Array();
2178
- const bytes = concatBytes2(actionBytes, nonceBytes, vaultMarker, vaultBytes);
2179
- return keccak256(bytes);
2180
- }
2181
- var HyperliquidSigner = class {
2182
- constructor(walletClient, isTestnet = false) {
2183
- this.walletClient = walletClient;
2184
- this.isTestnet = isTestnet;
2185
- }
2186
- isTestnet;
2187
- /**
2188
- * Sign an L1 action (order, cancel, updateLeverage, etc.)
2189
- * using the phantom agent pattern.
2190
- */
2191
- async signAction(action, nonce, vaultAddress) {
2192
- const actionNonce = nonce ?? getNextNonce();
2193
- const nonceNumber = Number(actionNonce);
2194
- const account = this.walletClient.account;
2195
- if (!account) throw new Error("Wallet client has no account");
2196
- const connectionId = createL1ActionHash({
2197
- action,
2198
- nonce: nonceNumber,
2199
- vaultAddress
2200
- });
2201
- const signature = await this.walletClient.signTypedData({
2202
- account,
2203
- domain: HYPERLIQUID_DOMAIN,
2204
- types: PHANTOM_AGENT_TYPES,
2205
- primaryType: "Agent",
2206
- message: {
2207
- source: this.isTestnet ? "b" : "a",
2208
- connectionId
2209
- }
2210
- });
2211
- return { signature, nonce: actionNonce };
2212
- }
2213
- /**
2214
- * Sign a user-signed action (withdraw3, usdSend, approveAgent, etc.)
2215
- * using the HyperliquidSignTransaction domain (chainId 42161).
2216
- *
2217
- * Unlike trading actions, these use direct EIP-712 typed data signing
2218
- * with action-specific types — NOT the phantom agent pattern.
2219
- */
2220
- async signUserAction(actionType, message) {
2221
- const account = this.walletClient.account;
2222
- if (!account) throw new Error("Wallet client has no account");
2223
- const types = USER_ACTION_TYPES[actionType];
2224
- const primaryType = Object.keys(types)[0];
2225
- const signature = await this.walletClient.signTypedData({
2226
- account,
2227
- domain: HYPERLIQUID_USER_DOMAIN,
2228
- types,
2229
- primaryType,
2230
- message
2231
- });
2232
- return { signature };
2233
- }
2234
- /**
2235
- * Build and sign a withdraw3 action for withdrawing USDC from Hyperliquid to Arbitrum.
2236
- * Returns the complete payload ready to POST to /exchange.
2237
- *
2238
- * @param destination — The Arbitrum address to receive USDC
2239
- * @param amount — Amount as string (e.g., "10.0" for $10)
2240
- */
2241
- async signWithdraw(destination, amount) {
2242
- const timestamp = Date.now();
2243
- const message = {
2244
- hyperliquidChain: this.isTestnet ? "Testnet" : "Mainnet",
2245
- destination,
2246
- amount,
2247
- time: BigInt(timestamp)
2248
- };
2249
- const { signature } = await this.signUserAction("withdraw", message);
2250
- const action = {
2251
- type: "withdraw3",
2252
- hyperliquidChain: this.isTestnet ? "Testnet" : "Mainnet",
2253
- signatureChainId: "0xa4b1",
2254
- // Arbitrum chainId in hex
2255
- destination,
2256
- amount,
2257
- time: timestamp
2258
- };
2259
- return {
2260
- action,
2261
- signature: {
2262
- r: signature.slice(0, 66),
2263
- s: `0x${signature.slice(66, 130)}`,
2264
- v: parseInt(signature.slice(130, 132), 16)
2265
- },
2266
- nonce: timestamp
2267
- };
2268
- }
2269
- getAddress() {
2270
- const account = this.walletClient.account;
2271
- if (!account) throw new Error("Wallet client has no account");
2272
- return account.address;
2273
- }
2274
- };
2275
- function hexToBytes(hex) {
2276
- const bytes = new Uint8Array(hex.length / 2);
2277
- for (let i = 0; i < bytes.length; i++) {
2278
- bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
2279
- }
2280
- return bytes;
2281
- }
2282
- function concatBytes2(...arrays) {
2283
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
2284
- const result = new Uint8Array(totalLength);
2285
- let offset = 0;
2286
- for (const arr of arrays) {
2287
- result.set(arr, offset);
2288
- offset += arr.length;
2289
- }
2290
- return result;
2291
- }
2292
-
2293
- // src/perp/orders.ts
2294
- var HyperliquidOrderManager = class {
2295
- client;
2296
- signer;
2297
- config;
2298
- constructor(client, signer, config) {
2299
- this.client = client;
2300
- this.signer = signer;
2301
- this.config = config;
2302
- }
2303
- async placeOrder(signal) {
2304
- try {
2305
- if (!signal.reduceOnly) {
2306
- const notionalUSD = signal.size * signal.price;
2307
- if (notionalUSD > this.config.maxNotionalUSD) {
2308
- const msg = `Notional $${notionalUSD.toFixed(0)} exceeds max $${this.config.maxNotionalUSD} for ${signal.instrument}`;
2309
- console.warn(`[perp] Order rejected: ${msg}`);
2310
- return { success: false, status: "error", error: msg };
2311
- }
2312
- if (signal.leverage > this.config.maxLeverage) {
2313
- const msg = `Leverage ${signal.leverage}x exceeds max ${this.config.maxLeverage}x for ${signal.instrument}`;
2314
- console.warn(`[perp] Order rejected: ${msg}`);
2315
- return { success: false, status: "error", error: msg };
2316
- }
2317
- }
2318
- const assetIndex = await this.client.getAssetIndex(signal.instrument);
2319
- const isBuy = signal.action === "open_long" || signal.action === "close_short";
2320
- const szDecimals = await this.client.getSzDecimals(signal.instrument);
2321
- const factor = 10 ** szDecimals;
2322
- const roundedSize = Math.floor(signal.size * factor) / factor;
2323
- if (roundedSize <= 0) {
2324
- const msg = `Size ${signal.size} rounds to 0 at ${szDecimals} decimal places for ${signal.instrument}`;
2325
- console.warn(`[perp] Order rejected: ${msg}`);
2326
- return { success: false, status: "error", error: msg };
2327
- }
2328
- const orderWire = {
2329
- a: assetIndex,
2330
- b: isBuy,
2331
- p: signal.orderType === "market" ? this.getMarketPrice(signal) : signal.price.toString(),
2332
- s: roundedSize.toString(),
2333
- r: signal.reduceOnly,
2334
- t: signal.orderType === "market" ? { limit: { tif: "Ioc" } } : { limit: { tif: "Gtc" } }
2335
- };
2336
- const action = {
2337
- type: "order",
2338
- orders: [orderWire],
2339
- grouping: "na"
2340
- };
2341
- const nonce = getNextNonce();
2342
- const { signature } = await this.signer.signAction(action, nonce);
2343
- const resp = await this.exchangeRequest({
2344
- action,
2345
- nonce: Number(nonce),
2346
- signature: {
2347
- r: signature.slice(0, 66),
2348
- s: `0x${signature.slice(66, 130)}`,
2349
- v: parseInt(signature.slice(130, 132), 16)
2350
- },
2351
- vaultAddress: null
2352
- });
2353
- return this.parseOrderResponse(resp);
2354
- } catch (error) {
2355
- const message = error instanceof Error ? error.message : String(error);
2356
- console.error(`[perp] Order failed for ${signal.instrument}:`, message);
2357
- return { success: false, status: "error", error: message };
2358
- }
2359
- }
2360
- async cancelOrder(instrument, orderId) {
2361
- try {
2362
- const assetIndex = await this.client.getAssetIndex(instrument);
2363
- const action = {
2364
- type: "cancel",
2365
- cancels: [{ a: assetIndex, o: orderId }]
2366
- };
2367
- const nonce = getNextNonce();
2368
- const { signature } = await this.signer.signAction(action, nonce);
2369
- await this.exchangeRequest({
2370
- action,
2371
- nonce: Number(nonce),
2372
- signature: {
2373
- r: signature.slice(0, 66),
2374
- s: `0x${signature.slice(66, 130)}`,
2375
- v: parseInt(signature.slice(130, 132), 16)
2376
- },
2377
- vaultAddress: null
2378
- });
2379
- console.log(`[perp] Cancelled order ${orderId} for ${instrument}`);
2380
- return true;
2381
- } catch (error) {
2382
- const message = error instanceof Error ? error.message : String(error);
2383
- console.error(`[perp] Cancel failed for order ${orderId}:`, message);
2384
- return false;
2385
- }
2386
- }
2387
- async closePosition(instrument, positionSize) {
2388
- const isLong = positionSize > 0;
2389
- return this.placeOrder({
2390
- action: isLong ? "close_long" : "close_short",
2391
- instrument,
2392
- size: Math.abs(positionSize),
2393
- price: 0,
2394
- leverage: 1,
2395
- orderType: "market",
2396
- reduceOnly: true,
2397
- confidence: 1,
2398
- reasoning: "Position close"
2399
- });
2400
- }
2401
- async updateLeverage(instrument, leverage, isCross = true) {
2402
- try {
2403
- const assetIndex = await this.client.getAssetIndex(instrument);
2404
- const action = {
2405
- type: "updateLeverage",
2406
- asset: assetIndex,
2407
- isCross,
2408
- leverage
2409
- };
2410
- const nonce = getNextNonce();
2411
- const { signature } = await this.signer.signAction(action, nonce);
2412
- await this.exchangeRequest({
2413
- action,
2414
- nonce: Number(nonce),
2415
- signature: {
2416
- r: signature.slice(0, 66),
2417
- s: `0x${signature.slice(66, 130)}`,
2418
- v: parseInt(signature.slice(130, 132), 16)
2419
- },
2420
- vaultAddress: null
2421
- });
2422
- console.log(`[perp] Leverage set for ${instrument}: ${leverage}x (${isCross ? "cross" : "isolated"})`);
2423
- return true;
2424
- } catch (error) {
2425
- const message = error instanceof Error ? error.message : String(error);
2426
- console.error(`[perp] Leverage update failed for ${instrument}:`, message);
2427
- return false;
2428
- }
2429
- }
2430
- // ── PRIVATE ────────────────────────────────────────────────
2431
- getMarketPrice(signal) {
2432
- const isBuy = signal.action === "open_long" || signal.action === "close_short";
2433
- if (signal.price > 0) {
2434
- const slippage = isBuy ? 1.005 : 0.995;
2435
- return (signal.price * slippage).toString();
2436
- }
2437
- return "0";
2438
- }
2439
- parseOrderResponse(resp) {
2440
- if (resp?.status === "ok" && resp?.response?.type === "order") {
2441
- const statuses = resp.response.data?.statuses || [];
2442
- if (statuses.length > 0) {
2443
- const status = statuses[0];
2444
- if (status.filled) {
2445
- return {
2446
- success: true,
2447
- orderId: status.filled.oid,
2448
- status: "filled",
2449
- avgPrice: status.filled.avgPx,
2450
- filledSize: status.filled.totalSz
2451
- };
2452
- }
2453
- if (status.resting) {
2454
- return {
2455
- success: true,
2456
- orderId: status.resting.oid,
2457
- status: "resting"
2458
- };
2459
- }
2460
- if (status.error) {
2461
- return { success: false, status: "error", error: status.error };
2462
- }
2463
- }
2464
- }
2465
- return {
2466
- success: false,
2467
- status: "error",
2468
- error: `Unexpected response: ${JSON.stringify(resp)}`
2469
- };
2470
- }
2471
- async exchangeRequest(body) {
2472
- const resp = await fetch(`${this.config.apiUrl}/exchange`, {
2473
- method: "POST",
2474
- headers: { "Content-Type": "application/json" },
2475
- body: JSON.stringify(body)
2476
- });
2477
- if (!resp.ok) {
2478
- throw new Error(`Hyperliquid Exchange API error: ${resp.status} ${await resp.text()}`);
2479
- }
2480
- return resp.json();
2481
- }
2482
- };
2483
-
2484
- // src/perp/positions.ts
2485
- var HyperliquidPositionManager = class {
2486
- client;
2487
- userAddress;
2488
- cachedPositions = [];
2489
- cachedAccount = null;
2490
- lastRefreshAt = 0;
2491
- cacheTtlMs = 5e3;
2492
- constructor(client, userAddress) {
2493
- this.client = client;
2494
- this.userAddress = userAddress;
2495
- }
2496
- // ── POSITION QUERIES ───────────────────────────────────────
2497
- async getPositions(forceRefresh = false) {
2498
- if (!forceRefresh && this.isCacheFresh()) return this.cachedPositions;
2499
- await this.refresh();
2500
- return this.cachedPositions;
2501
- }
2502
- async getPosition(instrument) {
2503
- const positions = await this.getPositions();
2504
- return positions.find((p) => p.instrument === instrument) ?? null;
2505
- }
2506
- async getAccountSummary(forceRefresh = false) {
2507
- if (!forceRefresh && this.isCacheFresh() && this.cachedAccount) {
2508
- return this.cachedAccount;
2509
- }
2510
- await this.refresh();
2511
- return this.cachedAccount;
2512
- }
2513
- // ── LIQUIDATION MONITORING ─────────────────────────────────
2514
- async getLiquidationProximity() {
2515
- const positions = await this.getPositions();
2516
- const proximities = /* @__PURE__ */ new Map();
2517
- for (const pos of positions) {
2518
- if (pos.liquidationPrice <= 0 || pos.markPrice <= 0) {
2519
- proximities.set(pos.instrument, 0);
2520
- continue;
2521
- }
2522
- let proximity;
2523
- if (pos.size > 0) {
2524
- if (pos.markPrice <= pos.liquidationPrice) {
2525
- proximity = 1;
2526
- } else {
2527
- const distanceToLiq = pos.markPrice - pos.liquidationPrice;
2528
- const entryToLiq = pos.entryPrice - pos.liquidationPrice;
2529
- proximity = entryToLiq > 0 ? 1 - distanceToLiq / entryToLiq : 0;
2530
- }
2531
- } else {
2532
- if (pos.markPrice >= pos.liquidationPrice) {
2533
- proximity = 1;
2534
- } else {
2535
- const distanceToLiq = pos.liquidationPrice - pos.markPrice;
2536
- const entryToLiq = pos.liquidationPrice - pos.entryPrice;
2537
- proximity = entryToLiq > 0 ? 1 - distanceToLiq / entryToLiq : 0;
2538
- }
2539
- }
2540
- proximities.set(pos.instrument, Math.max(0, Math.min(1, proximity)));
2541
- }
2542
- return proximities;
2543
- }
2544
- async getDangerousPositions(threshold = 0.7) {
2545
- const positions = await this.getPositions();
2546
- const proximities = await this.getLiquidationProximity();
2547
- return positions.filter((p) => (proximities.get(p.instrument) ?? 0) > threshold);
2548
- }
2549
- // ── SUMMARY HELPERS ────────────────────────────────────────
2550
- async getTotalUnrealizedPnl() {
2551
- const positions = await this.getPositions();
2552
- return positions.reduce((sum, p) => sum + p.unrealizedPnl, 0);
2553
- }
2554
- async getTotalNotional() {
2555
- const positions = await this.getPositions();
2556
- return positions.reduce((sum, p) => sum + p.notionalUSD, 0);
2557
- }
2558
- async getPositionCount() {
2559
- return (await this.getPositions()).length;
2560
- }
2561
- // ── CACHE ──────────────────────────────────────────────────
2562
- async refresh() {
2563
- try {
2564
- const [positions, account] = await Promise.all([
2565
- this.client.getPositions(this.userAddress),
2566
- this.client.getAccountSummary(this.userAddress)
2567
- ]);
2568
- this.cachedPositions = positions;
2569
- this.cachedAccount = account;
2570
- this.lastRefreshAt = Date.now();
2571
- } catch (error) {
2572
- const message = error instanceof Error ? error.message : String(error);
2573
- console.error("[perp] Failed to refresh positions:", message);
2574
- }
2575
- }
2576
- isCacheFresh() {
2577
- return Date.now() - this.lastRefreshAt < this.cacheTtlMs;
2578
- }
2579
- };
2580
-
2581
- // src/perp/websocket.ts
2582
- import WebSocket2 from "ws";
2583
- var HyperliquidWebSocket = class {
2584
- wsUrl;
2585
- userAddress;
2586
- client;
2587
- ws = null;
2588
- reconnectAttempts = 0;
2589
- maxReconnectAttempts = 20;
2590
- baseReconnectMs = 1e3;
2591
- maxReconnectMs = 6e4;
2592
- reconnectTimer = null;
2593
- pingTimer = null;
2594
- isConnecting = false;
2595
- shouldReconnect = true;
2596
- lastProcessedFillTime = 0;
2597
- onFill = null;
2598
- onFunding = null;
2599
- onLiquidation = null;
2600
- constructor(config, userAddress, client) {
2601
- this.wsUrl = config.wsUrl;
2602
- this.userAddress = userAddress;
2603
- this.client = client;
2604
- }
2605
- // ── CONNECTION ─────────────────────────────────────────────
2606
- async connect() {
2607
- if (this.ws?.readyState === WebSocket2.OPEN || this.isConnecting) return;
2608
- this.isConnecting = true;
2609
- this.shouldReconnect = true;
2610
- return new Promise((resolve2, reject) => {
2611
- try {
2612
- this.ws = new WebSocket2(this.wsUrl);
2613
- this.ws.on("open", () => {
2614
- this.isConnecting = false;
2615
- this.reconnectAttempts = 0;
2616
- console.log("[perp-ws] Connected");
2617
- this.subscribe({
2618
- type: "subscribe",
2619
- subscription: { type: "userFills", user: this.userAddress }
2620
- });
2621
- this.subscribe({
2622
- type: "subscribe",
2623
- subscription: { type: "userFundings", user: this.userAddress }
2624
- });
2625
- this.startPing();
2626
- this.backfillMissedFills().catch((err) => {
2627
- console.warn("[perp-ws] Backfill failed:", err instanceof Error ? err.message : err);
2628
- });
2629
- resolve2();
2630
- });
2631
- this.ws.on("message", (data) => {
2632
- this.handleMessage(data);
2633
- });
2634
- this.ws.on("close", (code, reason) => {
2635
- this.isConnecting = false;
2636
- console.log(`[perp-ws] Closed: ${code} ${reason.toString()}`);
2637
- this.stopPing();
2638
- this.scheduleReconnect();
2639
- });
2640
- this.ws.on("error", (error) => {
2641
- this.isConnecting = false;
2642
- console.error("[perp-ws] Error:", error.message);
2643
- if (this.reconnectAttempts === 0) reject(error);
2644
- });
2645
- } catch (error) {
2646
- this.isConnecting = false;
2647
- reject(error);
2648
- }
2649
- });
2650
- }
2651
- disconnect() {
2652
- this.shouldReconnect = false;
2653
- if (this.reconnectTimer) {
2654
- clearTimeout(this.reconnectTimer);
2655
- this.reconnectTimer = null;
2656
- }
2657
- this.stopPing();
2658
- if (this.ws) {
2659
- this.ws.removeAllListeners();
2660
- if (this.ws.readyState === WebSocket2.OPEN) {
2661
- this.ws.close(1e3, "Client disconnect");
2662
- }
2663
- this.ws = null;
2664
- }
2665
- console.log("[perp-ws] Disconnected");
2666
- }
2667
- get isConnected() {
2668
- return this.ws?.readyState === WebSocket2.OPEN;
2669
- }
2670
- // ── EVENT HANDLERS ─────────────────────────────────────────
2671
- onFillReceived(callback) {
2672
- this.onFill = callback;
2673
- }
2674
- onFundingReceived(callback) {
2675
- this.onFunding = callback;
2676
- }
2677
- onLiquidationDetected(callback) {
2678
- this.onLiquidation = callback;
2679
- }
2680
- getLastProcessedFillTime() {
2681
- return this.lastProcessedFillTime;
2682
- }
2683
- // ── MESSAGE HANDLING ───────────────────────────────────────
2684
- handleMessage(data) {
2685
- try {
2686
- const msg = JSON.parse(data.toString());
2687
- if (msg.channel === "userFills") {
2688
- this.handleFillMessage(msg.data);
2689
- } else if (msg.channel === "userFundings") {
2690
- this.handleFundingMessage(msg.data);
2691
- }
2692
- } catch {
2693
- }
2694
- }
2695
- handleFillMessage(fills) {
2696
- if (!Array.isArray(fills) || !this.onFill) return;
2697
- for (const rawFill of fills) {
2698
- const fill = this.client.parseFill(rawFill);
2699
- if (fill.time > this.lastProcessedFillTime) {
2700
- this.lastProcessedFillTime = fill.time;
2701
- }
2702
- if (fill.liquidation && this.onLiquidation) {
2703
- this.onLiquidation(fill.coin, parseFloat(fill.sz));
2704
- }
2705
- this.onFill(fill);
2706
- }
2707
- }
2708
- handleFundingMessage(fundings) {
2709
- if (!Array.isArray(fundings) || !this.onFunding) return;
2710
- for (const funding of fundings) {
2711
- this.onFunding({
2712
- time: funding.time,
2713
- coin: funding.coin,
2714
- usdc: funding.usdc,
2715
- szi: funding.szi,
2716
- fundingRate: funding.fundingRate
2717
- });
2718
- }
2719
- }
2720
- // ── BACKFILL ───────────────────────────────────────────────
2721
- async backfillMissedFills() {
2722
- if (this.lastProcessedFillTime === 0 || !this.onFill) return;
2723
- console.log(`[perp-ws] Backfilling fills since ${new Date(this.lastProcessedFillTime).toISOString()}`);
2724
- const fills = await this.client.getUserFillsByTime(
2725
- this.userAddress,
2726
- this.lastProcessedFillTime + 1
2727
- );
2728
- if (fills.length > 0) {
2729
- console.log(`[perp-ws] Backfilled ${fills.length} missed fills`);
2730
- for (const rawFill of fills) {
2731
- const fill = this.client.parseFill(rawFill);
2732
- if (fill.time > this.lastProcessedFillTime) {
2733
- this.lastProcessedFillTime = fill.time;
2734
- }
2735
- if (fill.liquidation && this.onLiquidation) {
2736
- this.onLiquidation(fill.coin, parseFloat(fill.sz));
2737
- }
2738
- this.onFill(fill);
2739
- }
2740
- }
2741
- }
2742
- // ── RECONNECTION ───────────────────────────────────────────
2743
- scheduleReconnect() {
2744
- if (!this.shouldReconnect || this.reconnectAttempts >= this.maxReconnectAttempts) {
2745
- if (this.reconnectAttempts >= this.maxReconnectAttempts) {
2746
- console.error(`[perp-ws] Max reconnect attempts (${this.maxReconnectAttempts}) reached`);
2747
- }
2748
- return;
2749
- }
2750
- const delay = Math.min(
2751
- this.baseReconnectMs * Math.pow(2, this.reconnectAttempts),
2752
- this.maxReconnectMs
2753
- );
2754
- this.reconnectAttempts++;
2755
- console.log(`[perp-ws] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);
2756
- this.reconnectTimer = setTimeout(() => {
2757
- this.connect().catch((err) => {
2758
- console.error("[perp-ws] Reconnect failed:", err instanceof Error ? err.message : err);
2759
- });
2760
- }, delay);
2761
- }
2762
- // ── KEEPALIVE ──────────────────────────────────────────────
2763
- startPing() {
2764
- this.stopPing();
2765
- this.pingTimer = setInterval(() => {
2766
- if (this.ws?.readyState === WebSocket2.OPEN) {
2767
- this.ws.send(JSON.stringify({ method: "ping" }));
2768
- }
2769
- }, 25e3);
2770
- }
2771
- stopPing() {
2772
- if (this.pingTimer) {
2773
- clearInterval(this.pingTimer);
2774
- this.pingTimer = null;
2775
- }
2776
- }
2777
- // ── HELPERS ────────────────────────────────────────────────
2778
- subscribe(msg) {
2779
- if (this.ws?.readyState === WebSocket2.OPEN) {
2780
- this.ws.send(JSON.stringify(msg));
2781
- }
2782
- }
2783
- };
2784
-
2785
- // src/prediction/types.ts
2786
- var DEFAULT_PREDICTION_CONFIG = {
2787
- enabled: false,
2788
- clobApiUrl: "https://clob.polymarket.com",
2789
- gammaApiUrl: "https://gamma-api.polymarket.com",
2790
- maxNotionalUSD: 1e3,
2791
- maxTotalExposureUSD: 5e3
2792
- };
2793
- var POLYGON_CHAIN_ID = 137;
2794
- var PREDICTION_INSTRUMENT_PREFIX = "POLY:";
2795
- function encodePredictionInstrument(conditionId, outcomeIndex) {
2796
- return `${PREDICTION_INSTRUMENT_PREFIX}${conditionId}:${outcomeIndex}`;
2797
- }
2798
- function decodePredictionInstrument(instrument) {
2799
- if (!instrument.startsWith(PREDICTION_INSTRUMENT_PREFIX)) return null;
2800
- const parts = instrument.slice(PREDICTION_INSTRUMENT_PREFIX.length).split(":");
2801
- if (parts.length !== 2) return null;
2802
- return { conditionId: parts[0], outcomeIndex: parseInt(parts[1], 10) };
2803
- }
2804
-
2805
- // src/prediction/client.ts
2806
- import { ClobClient } from "@polymarket/clob-client";
2807
- import { Wallet } from "ethers";
2808
- var PolymarketClient = class {
2809
- config;
2810
- clobClient = null;
2811
- apiCreds = null;
2812
- signer;
2813
- walletAddress;
2814
- marketCache = /* @__PURE__ */ new Map();
2815
- CACHE_TTL_MS = 6e4;
2816
- constructor(privateKey, config) {
2817
- this.config = { ...DEFAULT_PREDICTION_CONFIG, ...config };
2818
- this.signer = new Wallet(privateKey);
2819
- this.walletAddress = this.signer.address;
2820
- }
2821
- // ── INITIALIZATION ─────────────────────────────────────────
2822
- async initialize() {
2823
- const initClient = new ClobClient(
2824
- this.config.clobApiUrl,
2825
- POLYGON_CHAIN_ID,
2826
- this.signer
2827
- );
2828
- this.apiCreds = await initClient.createOrDeriveApiKey();
2829
- this.clobClient = new ClobClient(
2830
- this.config.clobApiUrl,
2831
- POLYGON_CHAIN_ID,
2832
- this.signer,
2833
- this.apiCreds,
2834
- 0
2835
- );
2836
- console.log(`[prediction] CLOB initialized for ${this.walletAddress}`);
2837
- }
2838
- get isInitialized() {
2839
- return this.clobClient !== null && this.apiCreds !== null;
2840
- }
2841
- // ── CLOB API — ORDER BOOK & PRICES ─────────────────────────
2842
- async getOrderBook(tokenId) {
2843
- this.ensureInitialized();
2844
- const book = await this.clobClient.getOrderBook(tokenId);
2845
- return {
2846
- bids: (book.bids || []).map((b) => ({ price: parseFloat(b.price), size: parseFloat(b.size) })),
2847
- asks: (book.asks || []).map((a) => ({ price: parseFloat(a.price), size: parseFloat(a.size) }))
2848
- };
2849
- }
2850
- async getMidpointPrice(tokenId) {
2851
- const book = await this.getOrderBook(tokenId);
2852
- if (book.bids.length === 0 || book.asks.length === 0) return 0;
2853
- return (book.bids[0].price + book.asks[0].price) / 2;
2854
- }
2855
- async getLastTradePrice(tokenId) {
2856
- this.ensureInitialized();
2857
- const resp = await this.clobClient.getLastTradePrice(tokenId);
2858
- return parseFloat(resp?.price || "0");
2859
- }
2860
- // ── CLOB API — ORDERS ──────────────────────────────────────
2861
- async placeLimitOrder(params) {
2862
- this.ensureInitialized();
2863
- const order = await this.clobClient.createAndPostOrder({
2864
- tokenID: params.tokenId,
2865
- price: params.price,
2866
- side: params.side,
2867
- size: params.size
2868
- });
2869
- return {
2870
- orderId: order?.orderID || "",
2871
- success: !!order?.orderID
2872
- };
2873
- }
2874
- async placeMarketOrder(params) {
2875
- this.ensureInitialized();
2876
- const order = await this.clobClient.createMarketOrder({
2877
- tokenID: params.tokenId,
2878
- amount: params.amount,
2879
- side: params.side
2880
- });
2881
- const result = await this.clobClient.postOrder(order);
2882
- return {
2883
- orderId: result?.orderID || "",
2884
- success: !!result?.orderID
2885
- };
2886
- }
2887
- async cancelOrder(orderId) {
2888
- this.ensureInitialized();
2889
- try {
2890
- await this.clobClient.cancelOrder({ orderID: orderId });
2891
- return true;
2892
- } catch {
2893
- return false;
2894
- }
2895
- }
2896
- async cancelAllOrders() {
2897
- this.ensureInitialized();
2898
- try {
2899
- await this.clobClient.cancelAll();
2900
- return true;
2901
- } catch {
2902
- return false;
2903
- }
2904
- }
2905
- async getOpenOrders() {
2906
- this.ensureInitialized();
2907
- return this.clobClient.getOpenOrders();
2908
- }
2909
- async getTradeHistory() {
2910
- this.ensureInitialized();
2911
- const trades = await this.clobClient.getTrades();
2912
- return (trades || []).map((t) => this.parseRawFill(t));
2913
- }
2914
- // ── GAMMA API — MARKET DISCOVERY (public) ──────────────────
2915
- async getMarkets(params) {
2916
- const query = new URLSearchParams();
2917
- if (params?.limit) query.set("limit", String(params.limit));
2918
- if (params?.offset) query.set("offset", String(params.offset));
2919
- if (params?.active !== void 0) query.set("active", String(params.active));
2920
- if (params?.category) query.set("tag", params.category);
2921
- const url = `${this.config.gammaApiUrl}/markets?${query.toString()}`;
2922
- const resp = await fetch(url);
2923
- if (!resp.ok) throw new Error(`Gamma API error: ${resp.status} ${await resp.text()}`);
2924
- const raw = await resp.json();
2925
- return (raw || []).map((m) => this.parseGammaMarket(m));
2926
- }
2927
- async getMarketByConditionId(conditionId) {
2928
- const cached = this.marketCache.get(conditionId);
2929
- if (cached && Date.now() - cached.cachedAt < this.CACHE_TTL_MS) {
2930
- return cached.market;
2931
- }
2932
- const url = `${this.config.gammaApiUrl}/markets?condition_id=${conditionId}`;
2933
- const resp = await fetch(url);
2934
- if (!resp.ok) return null;
2935
- const raw = await resp.json();
2936
- if (!raw || raw.length === 0) return null;
2937
- const market = this.parseGammaMarket(raw[0]);
2938
- this.marketCache.set(conditionId, { market, cachedAt: Date.now() });
2939
- return market;
2940
- }
2941
- async searchMarkets(query, limit = 20) {
2942
- const url = `${this.config.gammaApiUrl}/markets?_q=${encodeURIComponent(query)}&limit=${limit}&active=true`;
2943
- const resp = await fetch(url);
2944
- if (!resp.ok) return [];
2945
- const raw = await resp.json();
2946
- return (raw || []).map((m) => this.parseGammaMarket(m));
2947
- }
2948
- async getTrendingMarkets(limit = 10) {
2949
- const url = `${this.config.gammaApiUrl}/markets?active=true&limit=${limit}&order=volume24hr&ascending=false`;
2950
- const resp = await fetch(url);
2951
- if (!resp.ok) return [];
2952
- const raw = await resp.json();
2953
- return (raw || []).map((m) => this.parseGammaMarket(m));
2954
- }
2955
- // ── WALLET ─────────────────────────────────────────────────
2956
- getWalletAddress() {
2957
- return this.walletAddress;
2958
- }
2959
- // ── PRIVATE ────────────────────────────────────────────────
2960
- ensureInitialized() {
2961
- if (!this.clobClient) {
2962
- throw new Error("PolymarketClient not initialized. Call initialize() first.");
2963
- }
2964
- }
2965
- parseGammaMarket(raw) {
2966
- const outcomes = raw.outcomes ? JSON.parse(raw.outcomes) : ["Yes", "No"];
2967
- const outcomePrices = raw.outcomePrices ? JSON.parse(raw.outcomePrices) : [0, 0];
2968
- const outcomeTokenIds = raw.clobTokenIds ? JSON.parse(raw.clobTokenIds) : [];
2969
- return {
2970
- conditionId: raw.conditionId || raw.condition_id || "",
2971
- question: raw.question || "",
2972
- description: raw.description || "",
2973
- category: raw.groupItemTitle || raw.category || "Other",
2974
- outcomes,
2975
- outcomeTokenIds,
2976
- outcomePrices: outcomePrices.map((p) => parseFloat(p) || 0),
2977
- volume24h: parseFloat(raw.volume24hr || raw.volume24h || "0"),
2978
- liquidity: parseFloat(raw.liquidity || "0"),
2979
- endDate: raw.endDate ? new Date(raw.endDate).getTime() / 1e3 : 0,
2980
- active: raw.active !== false && raw.closed !== true,
2981
- resolved: raw.resolved === true,
2982
- winningOutcome: raw.winningOutcome,
2983
- resolutionSource: raw.resolutionSource || void 0,
2984
- uniqueTraders: raw.uniqueTraders || void 0
2985
- };
2986
- }
2987
- parseRawFill(raw) {
2988
- const tokenId = raw.asset_id || void 0;
2989
- const marketConditionId = raw.market || raw.asset_id || "";
2990
- return {
2991
- orderId: raw.orderId || raw.order_id || "",
2992
- tradeId: raw.id || raw.tradeId || "",
2993
- marketConditionId,
2994
- outcomeIndex: raw.outcome_index ?? (raw.side === "BUY" ? 0 : 1),
2995
- side: raw.side === "BUY" || raw.side === "buy" ? "BUY" : "SELL",
2996
- price: String(raw.price || "0"),
2997
- size: String(raw.size || "0"),
2998
- fee: String(raw.fee || "0"),
2999
- timestamp: raw.timestamp || raw.created_at ? new Date(raw.created_at).getTime() : Date.now(),
3000
- isMaker: raw.maker_order || raw.is_maker || false,
3001
- tokenId
3002
- };
3003
- }
3004
- };
3005
-
3006
- // src/prediction/order-manager.ts
3007
- var PolymarketOrderManager = class {
3008
- client;
3009
- config;
3010
- seenFillIds = /* @__PURE__ */ new Set();
3011
- recentFills = [];
3012
- positions = /* @__PURE__ */ new Map();
3013
- lastPriceRefresh = 0;
3014
- PRICE_REFRESH_MS = 1e4;
3015
- constructor(client, config) {
3016
- this.client = client;
3017
- this.config = config;
3018
- }
3019
- // ── SIGNAL EXECUTION ───────────────────────────────────────
3020
- async executeSignal(signal) {
3021
- if (signal.action === "hold") {
3022
- return { success: true, status: "cancelled", error: "Hold signal \u2014 no action" };
3023
- }
3024
- const violation = this.checkRiskLimits(signal);
3025
- if (violation) {
3026
- return { success: false, status: "error", error: violation };
3027
- }
3028
- try {
3029
- const market = await this.client.getMarketByConditionId(signal.marketConditionId);
3030
- if (!market) {
3031
- return { success: false, status: "error", error: `Market not found: ${signal.marketConditionId}` };
3032
- }
3033
- if (!market.active) {
3034
- return { success: false, status: "error", error: `Market is closed: ${market.question}` };
3035
- }
3036
- const tokenId = market.outcomeTokenIds[signal.outcomeIndex];
3037
- if (!tokenId) {
3038
- return { success: false, status: "error", error: `Invalid outcome index: ${signal.outcomeIndex}` };
3039
- }
3040
- const isBuy = signal.action === "buy_yes" || signal.action === "buy_no";
3041
- const side = isBuy ? "BUY" : "SELL";
3042
- let result;
3043
- if (signal.orderType === "market") {
3044
- result = await this.client.placeMarketOrder({
3045
- tokenId,
3046
- amount: signal.amount,
3047
- side
3048
- });
3049
- } else {
3050
- result = await this.client.placeLimitOrder({
3051
- tokenId,
3052
- price: signal.limitPrice,
3053
- size: signal.amount,
3054
- side
3055
- });
3056
- }
3057
- if (result.success) {
3058
- console.log(`[prediction] Order placed: ${signal.action} ${signal.amount} on "${market.question}" @ ${signal.limitPrice}`);
3059
- return { success: true, orderId: result.orderId, status: "resting" };
3060
- }
3061
- return { success: false, status: "error", error: "Order placement failed" };
3062
- } catch (error) {
3063
- const message = error instanceof Error ? error.message : String(error);
3064
- console.error("[prediction] Order execution error:", message);
3065
- return { success: false, status: "error", error: message };
3066
- }
3067
- }
3068
- // ── FILL POLLING ───────────────────────────────────────────
3069
- async pollNewFills() {
3070
- try {
3071
- const allFills = await this.client.getTradeHistory();
3072
- const newFills = [];
3073
- for (const fill of allFills) {
3074
- if (!this.seenFillIds.has(fill.tradeId)) {
3075
- this.seenFillIds.add(fill.tradeId);
3076
- newFills.push(fill);
3077
- this.processFill(fill);
3078
- this.recentFills.push(fill);
3079
- }
3080
- }
3081
- if (this.recentFills.length > 100) {
3082
- this.recentFills = this.recentFills.slice(-100);
3083
- }
3084
- return newFills;
3085
- } catch (error) {
3086
- const message = error instanceof Error ? error.message : String(error);
3087
- console.warn("[prediction] Fill polling error:", message);
3088
- return [];
3089
- }
3090
- }
3091
- getRecentFills() {
3092
- return this.recentFills;
3093
- }
3094
- // ── POSITION QUERIES ───────────────────────────────────────
3095
- async getPositions(forceRefresh = false) {
3096
- if (forceRefresh || Date.now() - this.lastPriceRefresh > this.PRICE_REFRESH_MS) {
3097
- await this.refreshPrices();
3098
- }
3099
- return Array.from(this.positions.values()).filter((p) => p.balance > 0).map((p) => this.toExternalPosition(p));
3100
- }
3101
- async getAccountSummary() {
3102
- const positions = await this.getPositions();
3103
- const totalExposure = positions.reduce((sum, p) => sum + p.costBasis, 0);
3104
- const totalUnrealizedPnl = positions.reduce((sum, p) => sum + p.unrealizedPnl, 0);
3105
- const openMarkets = new Set(positions.map((p) => p.marketConditionId));
3106
- return {
3107
- totalExposure,
3108
- totalUnrealizedPnl,
3109
- openMarketCount: openMarkets.size,
3110
- openPositionCount: positions.length
3111
- };
3112
- }
3113
- getTotalExposure() {
3114
- let total = 0;
3115
- for (const pos of this.positions.values()) {
3116
- if (pos.balance > 0) total += pos.totalCostBasis;
3117
- }
3118
- return total;
3119
- }
3120
- // ── CANCELLATION ───────────────────────────────────────────
3121
- async cancelOrder(orderId) {
3122
- return this.client.cancelOrder(orderId);
3123
- }
3124
- async cancelAllOrders() {
3125
- return this.client.cancelAllOrders();
3126
- }
3127
- // ── PRIVATE ────────────────────────────────────────────────
3128
- checkRiskLimits(signal) {
3129
- if (signal.amount > this.config.maxNotionalUSD) {
3130
- return `Trade exceeds max notional: $${signal.amount} > $${this.config.maxNotionalUSD}`;
3131
- }
3132
- if (signal.limitPrice <= 0 || signal.limitPrice >= 1) {
3133
- return `Invalid price: ${signal.limitPrice} (must be 0.01-0.99)`;
3134
- }
3135
- if (signal.confidence < 0.3) {
3136
- return `Low confidence: ${signal.confidence} < 0.3`;
3137
- }
3138
- const isBuy = signal.action === "buy_yes" || signal.action === "buy_no";
3139
- if (isBuy) {
3140
- const currentExposure = this.getTotalExposure();
3141
- if (currentExposure + signal.amount > this.config.maxTotalExposureUSD) {
3142
- return `Total exposure exceeded: $${currentExposure + signal.amount} > $${this.config.maxTotalExposureUSD}`;
3143
- }
3144
- }
3145
- return null;
3146
- }
3147
- processFill(fill) {
3148
- const key = `${fill.marketConditionId}:${fill.outcomeIndex}`;
3149
- let pos = this.positions.get(key);
3150
- const price = parseFloat(fill.price);
3151
- const size = parseFloat(fill.size);
3152
- if (!pos) {
3153
- pos = {
3154
- marketConditionId: fill.marketConditionId,
3155
- outcomeIndex: fill.outcomeIndex,
3156
- marketQuestion: fill.marketQuestion || "",
3157
- tokenId: fill.tokenId || "",
3158
- balance: 0,
3159
- totalCostBasis: 0,
3160
- totalProceeds: 0,
3161
- averageEntryPrice: 0,
3162
- currentPrice: price,
3163
- category: void 0,
3164
- endDate: void 0
3165
- };
3166
- this.positions.set(key, pos);
3167
- } else if (!pos.tokenId && fill.tokenId) {
3168
- pos.tokenId = fill.tokenId;
3169
- }
3170
- if (fill.side === "BUY") {
3171
- const oldCost = pos.averageEntryPrice * pos.balance;
3172
- const newCost = price * size;
3173
- pos.balance += size;
3174
- pos.totalCostBasis += newCost;
3175
- pos.averageEntryPrice = pos.balance > 0 ? (oldCost + newCost) / pos.balance : 0;
3176
- } else {
3177
- pos.balance -= size;
3178
- pos.totalProceeds += price * size;
3179
- if (pos.balance < 0) pos.balance = 0;
3180
- }
3181
- }
3182
- async refreshPrices() {
3183
- const openPositions = Array.from(this.positions.values()).filter((p) => p.balance > 0);
3184
- await Promise.all(
3185
- openPositions.map(async (pos) => {
3186
- try {
3187
- if (!pos.tokenId) {
3188
- const market = await this.client.getMarketByConditionId(pos.marketConditionId);
3189
- if (market && market.outcomeTokenIds[pos.outcomeIndex]) {
3190
- pos.tokenId = market.outcomeTokenIds[pos.outcomeIndex];
3191
- }
3192
- }
3193
- if (pos.tokenId) {
3194
- const price = await this.client.getMidpointPrice(pos.tokenId);
3195
- if (price > 0) pos.currentPrice = price;
3196
- }
3197
- } catch {
3198
- }
3199
- })
3200
- );
3201
- this.lastPriceRefresh = Date.now();
3202
- }
3203
- toExternalPosition(pos) {
3204
- const unrealizedPnl = pos.balance > 0 ? (pos.currentPrice - pos.averageEntryPrice) * pos.balance : 0;
3205
- return {
3206
- marketConditionId: pos.marketConditionId,
3207
- marketQuestion: pos.marketQuestion,
3208
- outcomeIndex: pos.outcomeIndex,
3209
- outcomeLabel: pos.outcomeIndex === 0 ? "Yes" : "No",
3210
- tokenId: pos.tokenId,
3211
- balance: pos.balance,
3212
- averageEntryPrice: pos.averageEntryPrice,
3213
- currentPrice: pos.currentPrice,
3214
- unrealizedPnl,
3215
- costBasis: pos.totalCostBasis - pos.totalProceeds,
3216
- endDate: pos.endDate,
3217
- category: pos.category
3218
- };
3219
- }
3220
- };
3221
-
3222
- // src/spot/client.ts
3223
- import {
3224
- createPublicClient,
3225
- createWalletClient,
3226
- http,
3227
- maxUint256
3228
- } from "viem";
3229
- import { privateKeyToAccount } from "viem/accounts";
3230
- var SpotDEXClient = class {
3231
- account;
3232
- clients = /* @__PURE__ */ new Map();
3233
- decimalsCache = /* @__PURE__ */ new Map();
3234
- symbolCache = /* @__PURE__ */ new Map();
3235
- constructor(privateKey) {
3236
- this.account = privateKeyToAccount(privateKey);
3237
- }
3238
- get address() {
3239
- return this.account.address;
3240
- }
3241
- getClients(chainName) {
3242
- const cached = this.clients.get(chainName);
3243
- if (cached) return cached;
3244
- const chainConfig = getChainConfig(chainName);
3245
- if (!chainConfig) {
3246
- throw new Error(`Unknown chain: ${chainName}`);
3247
- }
3248
- const publicClient = createPublicClient({
3249
- chain: chainConfig.viemChain,
3250
- transport: http(chainConfig.rpcUrl)
3251
- });
3252
- const walletClient = createWalletClient({
3253
- account: this.account,
3254
- chain: chainConfig.viemChain,
3255
- transport: http(chainConfig.rpcUrl)
3256
- });
3257
- const entry = { publicClient, walletClient, chainConfig };
3258
- this.clients.set(chainName, entry);
3259
- return entry;
3260
- }
3261
- async getDecimals(token, chainName) {
3262
- const key = `${chainName}:${token}`;
3263
- const cached = this.decimalsCache.get(key);
3264
- if (cached !== void 0) return cached;
3265
- const { publicClient } = this.getClients(chainName);
3266
- const decimals = await publicClient.readContract({
3267
- address: token,
3268
- abi: ERC20_ABI,
3269
- functionName: "decimals"
3270
- });
3271
- this.decimalsCache.set(key, decimals);
3272
- return decimals;
3273
- }
3274
- async getSymbol(token, chainName) {
3275
- const key = `${chainName}:${token}`;
3276
- const cached = this.symbolCache.get(key);
3277
- if (cached) return cached;
3278
- const { publicClient } = this.getClients(chainName);
3279
- const symbol = await publicClient.readContract({
3280
- address: token,
3281
- abi: ERC20_ABI,
3282
- functionName: "symbol"
3283
- });
3284
- this.symbolCache.set(key, symbol);
3285
- return symbol;
3286
- }
3287
- async getBalance(token, chainName) {
3288
- const { publicClient } = this.getClients(chainName);
3289
- return await publicClient.readContract({
3290
- address: token,
3291
- abi: ERC20_ABI,
3292
- functionName: "balanceOf",
3293
- args: [this.account.address]
3294
- });
3295
- }
3296
- /** Get the native token balance (ETH, POL, etc.) on a chain */
3297
- async getNativeBalance(chainName) {
3298
- const { publicClient } = this.getClients(chainName);
3299
- return await publicClient.getBalance({ address: this.account.address });
3300
- }
3301
- async ensureApproval(token, spender, amount, chainName) {
3302
- const { publicClient, walletClient } = this.getClients(chainName);
3303
- const allowance = await publicClient.readContract({
3304
- address: token,
3305
- abi: ERC20_ABI,
3306
- functionName: "allowance",
3307
- args: [this.account.address, spender]
3308
- });
3309
- if (allowance >= amount) return null;
3310
- const hash = await walletClient.writeContract({
3311
- address: token,
3312
- abi: ERC20_ABI,
3313
- functionName: "approve",
3314
- args: [spender, maxUint256]
3315
- });
3316
- await publicClient.waitForTransactionReceipt({ hash });
3317
- console.log(`[spot] Approved ${token} for ${spender} on ${chainName} (tx: ${hash})`);
3318
- return hash;
3319
- }
3320
- };
3321
-
3322
- // src/spot/uniswap.ts
3323
- var FEE_TIERS = [500, 3e3, 1e4];
3324
- var UniswapAdapter = class {
3325
- client;
3326
- constructor(client) {
3327
- this.client = client;
3328
- }
3329
- async quote(params) {
3330
- const chainConfig = getChainConfig(params.chain);
3331
- if (!chainConfig?.uniswapQuoter) {
3332
- throw new Error(`No Uniswap QuoterV2 on ${params.chain}`);
3333
- }
3334
- const { publicClient } = this.client.getClients(params.chain);
3335
- let bestAmountOut = 0n;
3336
- let bestFeeTier = 0;
3337
- for (const fee of FEE_TIERS) {
3338
- try {
3339
- const result = await publicClient.simulateContract({
3340
- address: chainConfig.uniswapQuoter,
3341
- abi: UNISWAP_QUOTER_V2_ABI,
3342
- functionName: "quoteExactInputSingle",
3343
- args: [
3344
- {
3345
- tokenIn: params.tokenIn,
3346
- tokenOut: params.tokenOut,
3347
- amountIn: params.amountIn,
3348
- fee,
3349
- sqrtPriceLimitX96: 0n
3350
- }
3351
- ]
3352
- });
3353
- const amountOut = result.result[0];
3354
- if (amountOut > bestAmountOut) {
3355
- bestAmountOut = amountOut;
3356
- bestFeeTier = fee;
3357
- }
3358
- } catch {
3359
- }
3360
- }
3361
- if (bestAmountOut === 0n) {
3362
- throw new Error(`No Uniswap V3 pool found for ${params.tokenIn}/${params.tokenOut} on ${params.chain}`);
3363
- }
3364
- const tokenInSymbol = await this.client.getSymbol(params.tokenIn, params.chain);
3365
- const tokenOutSymbol = await this.client.getSymbol(params.tokenOut, params.chain);
3366
- return {
3367
- amountOut: bestAmountOut,
3368
- feeTier: bestFeeTier,
3369
- route: `${tokenInSymbol} \u2192 ${tokenOutSymbol} (${bestFeeTier / 1e4}%)`
3370
- };
3371
- }
3372
- async swap(params) {
3373
- const chainConfig = getChainConfig(params.chain);
3374
- if (!chainConfig) {
3375
- throw new Error(`Unknown chain: ${params.chain}`);
3376
- }
3377
- const routerAddress = chainConfig.dexRouters.uniswap;
3378
- if (!routerAddress) {
3379
- throw new Error(`No Uniswap router on ${params.chain}`);
3380
- }
3381
- const quoteResult = await this.quote(params);
3382
- const amountOutMinimum = quoteResult.amountOut * BigInt(1e4 - params.slippageBps) / 10000n;
3383
- await this.client.ensureApproval(params.tokenIn, routerAddress, params.amountIn, params.chain);
3384
- const { publicClient, walletClient } = this.client.getClients(params.chain);
3385
- const recipient = params.recipient ?? this.client.address;
3386
- try {
3387
- const hash = await walletClient.writeContract({
3388
- address: routerAddress,
3389
- abi: UNISWAP_SWAP_ROUTER_ABI,
3390
- functionName: "exactInputSingle",
3391
- args: [
3392
- {
3393
- tokenIn: params.tokenIn,
3394
- tokenOut: params.tokenOut,
3395
- fee: quoteResult.feeTier,
3396
- recipient,
3397
- amountIn: params.amountIn,
3398
- amountOutMinimum,
3399
- sqrtPriceLimitX96: 0n
3400
- }
3401
- ]
3402
- });
3403
- const receipt = await publicClient.waitForTransactionReceipt({ hash });
3404
- const tokenInDecimals = await this.client.getDecimals(params.tokenIn, params.chain);
3405
- const tokenOutDecimals = await this.client.getDecimals(params.tokenOut, params.chain);
3406
- const amountInFloat = Number(params.amountIn) / 10 ** tokenInDecimals;
3407
- const amountOutFloat = Number(quoteResult.amountOut) / 10 ** tokenOutDecimals;
3408
- const effectivePrice = amountOutFloat / amountInFloat;
3409
- const gasUsed = receipt.gasUsed ?? 0n;
3410
- const gasPrice = receipt.effectiveGasPrice ?? 0n;
3411
- return {
3412
- success: true,
3413
- txHash: hash,
3414
- amountIn: params.amountIn,
3415
- amountOut: quoteResult.amountOut,
3416
- tokenIn: params.tokenIn,
3417
- tokenOut: params.tokenOut,
3418
- effectivePrice,
3419
- gasCost: gasUsed * gasPrice,
3420
- chain: params.chain,
3421
- dex: "uniswap"
3422
- };
3423
- } catch (err) {
3424
- return {
3425
- success: false,
3426
- txHash: "0x0",
3427
- amountIn: params.amountIn,
3428
- amountOut: 0n,
3429
- tokenIn: params.tokenIn,
3430
- tokenOut: params.tokenOut,
3431
- effectivePrice: 0,
3432
- gasCost: 0n,
3433
- chain: params.chain,
3434
- dex: "uniswap",
3435
- error: err.message
3436
- };
3437
- }
3438
- }
3439
- };
3440
-
3441
- // src/spot/aerodrome.ts
3442
- var AerodromeAdapter = class {
3443
- client;
3444
- constructor(client) {
3445
- this.client = client;
3446
- }
3447
- async quote(params) {
3448
- if (params.chain !== "base") {
3449
- throw new Error("Aerodrome is only available on Base");
3450
- }
3451
- const chainConfig = getChainConfig("base");
3452
- const routerAddress = chainConfig.dexRouters.aerodrome;
3453
- if (!routerAddress) {
3454
- throw new Error("No Aerodrome router configured for Base");
3455
- }
3456
- const { publicClient } = this.client.getClients("base");
3457
- let bestAmountOut = 0n;
3458
- let bestStable = false;
3459
- for (const stable of [true, false]) {
3460
- try {
3461
- const route = [
3462
- {
3463
- from: params.tokenIn,
3464
- to: params.tokenOut,
3465
- stable,
3466
- factory: AERODROME_DEFAULT_FACTORY
3467
- }
3468
- ];
3469
- const amounts = await publicClient.readContract({
3470
- address: routerAddress,
3471
- abi: AERODROME_ROUTER_ABI,
3472
- functionName: "getAmountsOut",
3473
- args: [params.amountIn, route]
3474
- });
3475
- const amountOut = amounts[amounts.length - 1];
3476
- if (amountOut > bestAmountOut) {
3477
- bestAmountOut = amountOut;
3478
- bestStable = stable;
3479
- }
3480
- } catch {
3481
- }
3482
- }
3483
- if (bestAmountOut === 0n) {
3484
- throw new Error(`No Aerodrome pool found for ${params.tokenIn}/${params.tokenOut}`);
3485
- }
3486
- const tokenInSymbol = await this.client.getSymbol(params.tokenIn, "base");
3487
- const tokenOutSymbol = await this.client.getSymbol(params.tokenOut, "base");
3488
- return {
3489
- amountOut: bestAmountOut,
3490
- stable: bestStable,
3491
- route: `${tokenInSymbol} \u2192 ${tokenOutSymbol} (${bestStable ? "stable" : "volatile"})`
3492
- };
3493
- }
3494
- async swap(params) {
3495
- if (params.chain !== "base") {
3496
- throw new Error("Aerodrome is only available on Base");
3497
- }
3498
- const chainConfig = getChainConfig("base");
3499
- const routerAddress = chainConfig.dexRouters.aerodrome;
3500
- if (!routerAddress) {
3501
- throw new Error("No Aerodrome router configured for Base");
3502
- }
3503
- const quoteResult = await this.quote(params);
3504
- const amountOutMin = quoteResult.amountOut * BigInt(1e4 - params.slippageBps) / 10000n;
3505
- await this.client.ensureApproval(params.tokenIn, routerAddress, params.amountIn, "base");
3506
- const { publicClient, walletClient } = this.client.getClients("base");
3507
- const recipient = params.recipient ?? this.client.address;
3508
- const route = [
3509
- {
3510
- from: params.tokenIn,
3511
- to: params.tokenOut,
3512
- stable: quoteResult.stable,
3513
- factory: AERODROME_DEFAULT_FACTORY
3514
- }
3515
- ];
3516
- const deadline = BigInt(Math.floor(Date.now() / 1e3) + 300);
3517
- try {
3518
- const hash = await walletClient.writeContract({
3519
- address: routerAddress,
3520
- abi: AERODROME_ROUTER_ABI,
3521
- functionName: "swapExactTokensForTokens",
3522
- args: [params.amountIn, amountOutMin, route, recipient, deadline]
3523
- });
3524
- const receipt = await publicClient.waitForTransactionReceipt({ hash });
3525
- const tokenInDecimals = await this.client.getDecimals(params.tokenIn, "base");
3526
- const tokenOutDecimals = await this.client.getDecimals(params.tokenOut, "base");
3527
- const amountInFloat = Number(params.amountIn) / 10 ** tokenInDecimals;
3528
- const amountOutFloat = Number(quoteResult.amountOut) / 10 ** tokenOutDecimals;
3529
- const effectivePrice = amountOutFloat / amountInFloat;
3530
- const gasUsed = receipt.gasUsed ?? 0n;
3531
- const gasPrice = receipt.effectiveGasPrice ?? 0n;
3532
- return {
3533
- success: true,
3534
- txHash: hash,
3535
- amountIn: params.amountIn,
3536
- amountOut: quoteResult.amountOut,
3537
- tokenIn: params.tokenIn,
3538
- tokenOut: params.tokenOut,
3539
- effectivePrice,
3540
- gasCost: gasUsed * gasPrice,
3541
- chain: "base",
3542
- dex: "aerodrome"
3543
- };
3544
- } catch (err) {
3545
- return {
3546
- success: false,
3547
- txHash: "0x0",
3548
- amountIn: params.amountIn,
3549
- amountOut: 0n,
3550
- tokenIn: params.tokenIn,
3551
- tokenOut: params.tokenOut,
3552
- effectivePrice: 0,
3553
- gasCost: 0n,
3554
- chain: "base",
3555
- dex: "aerodrome",
3556
- error: err.message
3557
- };
3558
- }
3559
- }
3560
- };
3561
-
3562
- // src/spot/swap-manager.ts
3563
- var TOKEN_ALIASES = {
3564
- base: {
3565
- ETH: "0x4200000000000000000000000000000000000006",
3566
- WETH: "0x4200000000000000000000000000000000000006",
3567
- USDC: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
3568
- USDbC: "0xd9aAEc86B65D86f6A7B5B1b0c42FFA531710b6CA",
3569
- DAI: "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb"
3570
- },
3571
- ethereum: {
3572
- ETH: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
3573
- WETH: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
3574
- USDC: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
3575
- USDT: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
3576
- DAI: "0x6B175474E89094C44Da98b954EedeAC495271d0F"
3577
- },
3578
- arbitrum: {
3579
- ETH: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
3580
- WETH: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
3581
- USDC: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
3582
- "USDC.e": "0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8",
3583
- USDT: "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"
3584
- },
3585
- polygon: {
3586
- POL: "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",
3587
- WPOL: "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",
3588
- WMATIC: "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",
3589
- USDC: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
3590
- "USDC.e": "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
3591
- USDT: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F"
3592
- }
3593
- };
3594
- var SpotSwapManager = class {
3595
- dexClient;
3596
- uniswap;
3597
- aerodrome;
3598
- config;
3599
- constructor(privateKey, config) {
3600
- this.config = config;
3601
- this.dexClient = new SpotDEXClient(privateKey);
3602
- this.uniswap = new UniswapAdapter(this.dexClient);
3603
- this.aerodrome = new AerodromeAdapter(this.dexClient);
3604
- }
3605
- get client() {
3606
- return this.dexClient;
3607
- }
3608
- /** Resolve a token symbol or address to a hex address */
3609
- resolveToken(tokenOrSymbol, chain) {
3610
- if (tokenOrSymbol.startsWith("0x") && tokenOrSymbol.length === 42) {
3611
- return tokenOrSymbol;
3612
- }
3613
- const chainAliases = TOKEN_ALIASES[chain];
3614
- if (chainAliases) {
3615
- const upper = tokenOrSymbol.toUpperCase();
3616
- const address = chainAliases[upper] ?? chainAliases[tokenOrSymbol];
3617
- if (address) return address;
3618
- }
3619
- const chainConfig = getChainConfig(chain);
3620
- if (chainConfig) {
3621
- const upper = tokenOrSymbol.toUpperCase();
3622
- if (upper === "WETH" || upper === "ETH") return chainConfig.wethAddress;
3623
- if (upper === "USDC") return chainConfig.usdcAddress;
3624
- }
3625
- throw new Error(`Cannot resolve token "${tokenOrSymbol}" on ${chain}. Provide contract address.`);
3626
- }
3627
- /** Select DEX: explicit choice, or auto-detect */
3628
- selectDex(chain, dex) {
3629
- if (dex) return dex;
3630
- const chainConfig = getChainConfig(chain);
3631
- if (chain === "base" && chainConfig?.dexRouters.aerodrome) {
3632
- return "aerodrome";
3633
- }
3634
- return "uniswap";
3635
- }
3636
- async getQuote(params) {
3637
- const chain = params.chain ?? this.config.defaultChain;
3638
- const dex = this.selectDex(chain, params.dex);
3639
- const swapParams = {
3640
- tokenIn: this.resolveToken(params.tokenIn, chain),
3641
- tokenOut: this.resolveToken(params.tokenOut, chain),
3642
- amountIn: params.amountIn,
3643
- slippageBps: this.config.maxSlippageBps,
3644
- chain,
3645
- dex
3646
- };
3647
- if (dex === "aerodrome") {
3648
- return this.aerodrome.quote(swapParams);
3649
- }
3650
- return this.uniswap.quote(swapParams);
3651
- }
3652
- async executeSwap(params) {
3653
- const chain = params.chain ?? this.config.defaultChain;
3654
- const dex = this.selectDex(chain, params.dex);
3655
- const tokenInAddress = this.resolveToken(params.tokenIn, chain);
3656
- try {
3657
- const decimals = await this.dexClient.getDecimals(tokenInAddress, chain);
3658
- const amountFloat = Number(params.amountIn) / 10 ** decimals;
3659
- if (amountFloat > this.config.maxSwapValueUSD) {
3660
- return {
3661
- success: false,
3662
- txHash: "0x0",
3663
- amountIn: params.amountIn,
3664
- amountOut: 0n,
3665
- tokenIn: "0x0",
3666
- tokenOut: "0x0",
3667
- effectivePrice: 0,
3668
- gasCost: 0n,
3669
- chain,
3670
- dex,
3671
- error: `Swap value ${amountFloat.toFixed(2)} tokens exceeds max $${this.config.maxSwapValueUSD}. Reduce size or increase maxSwapValueUSD.`
3672
- };
3673
- }
3674
- } catch {
3675
- }
3676
- if (!this.config.chains.includes(chain)) {
3677
- return {
3678
- success: false,
3679
- txHash: "0x0",
3680
- amountIn: params.amountIn,
3681
- amountOut: 0n,
3682
- tokenIn: "0x0",
3683
- tokenOut: "0x0",
3684
- effectivePrice: 0,
3685
- gasCost: 0n,
3686
- chain,
3687
- dex,
3688
- error: `Chain "${chain}" not enabled in spot config (enabled: ${this.config.chains.join(", ")})`
3689
- };
3690
- }
3691
- const MIN_GAS_WEI2 = 100000000000000n;
3692
- try {
3693
- const nativeBalance = await this.dexClient.getNativeBalance(chain);
3694
- if (nativeBalance < MIN_GAS_WEI2) {
3695
- const chainConfig = getChainConfig(chain);
3696
- const nativeName = chainConfig?.nativeCurrency ?? "ETH";
3697
- return {
3698
- success: false,
3699
- txHash: "0x0",
3700
- amountIn: params.amountIn,
3701
- amountOut: 0n,
3702
- tokenIn: "0x0",
3703
- tokenOut: "0x0",
3704
- effectivePrice: 0,
3705
- gasCost: 0n,
3706
- chain,
3707
- dex,
3708
- error: `Insufficient ${nativeName} for gas on ${chain}. Balance: ${nativeBalance} wei. Need at least 0.0001 ${nativeName}. Bridge gas to ${chain} before swapping.`
3709
- };
3710
- }
3711
- } catch {
3712
- }
3713
- const swapParams = {
3714
- tokenIn: this.resolveToken(params.tokenIn, chain),
3715
- tokenOut: this.resolveToken(params.tokenOut, chain),
3716
- amountIn: params.amountIn,
3717
- slippageBps: params.slippageBps ?? this.config.maxSlippageBps,
3718
- chain,
3719
- dex
3720
- };
3721
- console.log(`[spot] Swapping on ${dex}/${chain}: ${params.tokenIn} \u2192 ${params.tokenOut} (${params.amountIn})`);
3722
- if (dex === "aerodrome") {
3723
- return this.aerodrome.swap(swapParams);
3724
- }
3725
- return this.uniswap.swap(swapParams);
3726
- }
3727
- };
3728
-
3729
- // src/bridge/types.ts
3730
- var DEFAULT_BRIDGE_CONFIG = {
3731
- enabled: false,
3732
- defaultBridge: "across",
3733
- maxBridgeValueUSD: 1e4,
3734
- fillTimeoutMs: 3e5,
3735
- // 5 minutes
3736
- pollIntervalMs: 2e3
3737
- // 2 seconds
3738
- };
3739
- var ACROSS_SPOKE_POOL_ABI = [
3740
- {
3741
- type: "function",
3742
- name: "depositV3",
3743
- inputs: [
3744
- { name: "depositor", type: "address" },
3745
- { name: "recipient", type: "address" },
3746
- { name: "inputToken", type: "address" },
3747
- { name: "outputToken", type: "address" },
3748
- { name: "inputAmount", type: "uint256" },
3749
- { name: "outputAmount", type: "uint256" },
3750
- { name: "destinationChainId", type: "uint256" },
3751
- { name: "exclusiveRelayer", type: "address" },
3752
- { name: "quoteTimestamp", type: "uint32" },
3753
- { name: "fillDeadline", type: "uint32" },
3754
- { name: "exclusivityDeadline", type: "uint32" },
3755
- { name: "message", type: "bytes" }
3756
- ],
3757
- outputs: [],
3758
- stateMutability: "payable"
3759
- }
3760
- ];
3761
-
3762
- // src/bridge/across.ts
3763
- var ACROSS_API_BASE = "https://app.across.to/api";
3764
- var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
3765
- var AcrossAdapter = class {
3766
- client;
3767
- config;
3768
- constructor(client, config) {
3769
- this.client = client;
3770
- this.config = config;
3771
- }
3772
- async estimateFee(request) {
3773
- const fromChain = getChainConfig(request.fromChain);
3774
- const toChain = getChainConfig(request.toChain);
3775
- if (!fromChain) throw new Error(`Unknown source chain: ${request.fromChain}`);
3776
- if (!toChain) throw new Error(`Unknown destination chain: ${request.toChain}`);
3777
- const outputToken = this.resolveOutputToken(request.token, request.fromChain, request.toChain);
3778
- const params = new URLSearchParams({
3779
- inputToken: request.token,
3780
- outputToken,
3781
- originChainId: fromChain.chainId.toString(),
3782
- destinationChainId: toChain.chainId.toString(),
3783
- amount: request.amount.toString(),
3784
- recipient: request.recipient ?? this.client.address
3785
- });
3786
- const url = `${ACROSS_API_BASE}/suggested-fees?${params}`;
3787
- const res = await fetch(url);
3788
- if (!res.ok) {
3789
- const body = await res.text();
3790
- throw new Error(`Across fee API error (${res.status}): ${body}`);
3791
- }
3792
- const data = await res.json();
3793
- const totalFeePct = parseFloat(data.totalRelayFee.pct) / 1e18;
3794
- const feeAmount = BigInt(Math.floor(Number(request.amount) * totalFeePct));
3795
- const outputAmount = request.amount - feeAmount;
3796
- return {
3797
- totalRelayFeePct: totalFeePct * 100,
3798
- capitalFeePct: parseFloat(data.relayerCapitalFee.pct) / 1e18 * 100,
3799
- lpFeePct: parseFloat(data.lpFee.pct) / 1e18 * 100,
3800
- relayGasFeePct: parseFloat(data.relayerGasFee.pct) / 1e18 * 100,
3801
- timestamp: parseInt(data.timestamp),
3802
- estimatedFillTimeSec: data.estimatedFillTimeSec,
3803
- isAmountTooLow: data.isAmountTooLow,
3804
- outputAmount
3805
- };
3806
- }
3807
- async deposit(request) {
3808
- const fromChain = getChainConfig(request.fromChain);
3809
- const toChain = getChainConfig(request.toChain);
3810
- if (!fromChain?.acrossSpokePool) throw new Error(`No Across SpokePool on ${request.fromChain}`);
3811
- if (!toChain) throw new Error(`Unknown destination chain: ${request.toChain}`);
3812
- const spokePool = fromChain.acrossSpokePool;
3813
- const outputToken = this.resolveOutputToken(request.token, request.fromChain, request.toChain);
3814
- const recipient = request.recipient ?? this.client.address;
3815
- await this.client.ensureApproval(request.token, spokePool, request.amount, request.fromChain);
3816
- const feeEstimate = await this.estimateFee(request);
3817
- if (feeEstimate.isAmountTooLow) {
3818
- return {
3819
- success: false,
3820
- depositTxHash: "0x0",
3821
- fromChain: request.fromChain,
3822
- toChain: request.toChain,
3823
- token: request.token,
3824
- amount: request.amount,
3825
- fee: 0n,
3826
- error: "Amount too low for Across bridge"
3827
- };
3828
- }
3829
- const { publicClient, walletClient } = this.client.getClients(request.fromChain);
3830
- const fillDeadline = Math.floor(Date.now() / 1e3) + 21600;
3831
- try {
3832
- const hash = await walletClient.writeContract({
3833
- address: spokePool,
3834
- abi: ACROSS_SPOKE_POOL_ABI,
3835
- functionName: "depositV3",
3836
- args: [
3837
- this.client.address,
3838
- // depositor
3839
- recipient,
3840
- // recipient
3841
- request.token,
3842
- // inputToken
3843
- outputToken,
3844
- // outputToken
3845
- request.amount,
3846
- // inputAmount
3847
- feeEstimate.outputAmount,
3848
- // outputAmount (inputAmount - fees)
3849
- BigInt(toChain.chainId),
3850
- // destinationChainId
3851
- ZERO_ADDRESS,
3852
- // exclusiveRelayer (none)
3853
- feeEstimate.timestamp,
3854
- // quoteTimestamp
3855
- fillDeadline,
3856
- // fillDeadline
3857
- 0,
3858
- // exclusivityDeadline (none)
3859
- "0x"
3860
- // message (empty)
3861
- ]
3862
- });
3863
- const receipt = await publicClient.waitForTransactionReceipt({ hash });
3864
- const fee = request.amount - feeEstimate.outputAmount;
3865
- console.log(`[bridge] Across deposit: ${hash} (${request.fromChain} \u2192 ${request.toChain})`);
3866
- const result = {
3867
- success: true,
3868
- depositTxHash: hash,
3869
- fromChain: request.fromChain,
3870
- toChain: request.toChain,
3871
- token: request.token,
3872
- amount: request.amount,
3873
- fee
3874
- };
3875
- const fill = await this.waitForFill(hash, request.fromChain);
3876
- if (fill.filled) {
3877
- result.fillTxHash = fill.fillTxHash;
3878
- result.fillTimestamp = Date.now();
3879
- console.log(`[bridge] Across fill confirmed: ${fill.fillTxHash}`);
3880
- } else {
3881
- console.warn(`[bridge] Across fill not confirmed within timeout \u2014 deposit was successful, fill may still arrive`);
3882
- }
3883
- return result;
3884
- } catch (err) {
3885
- return {
3886
- success: false,
3887
- depositTxHash: "0x0",
3888
- fromChain: request.fromChain,
3889
- toChain: request.toChain,
3890
- token: request.token,
3891
- amount: request.amount,
3892
- fee: 0n,
3893
- error: err.message
3894
- };
3895
- }
3896
- }
3897
- async waitForFill(depositTxHash, originChain) {
3898
- const chainConfig = getChainConfig(originChain);
3899
- if (!chainConfig) return { filled: false };
3900
- const startTime = Date.now();
3901
- const timeout = this.config.fillTimeoutMs;
3902
- const interval = this.config.pollIntervalMs;
3903
- while (Date.now() - startTime < timeout) {
3904
- try {
3905
- const params = new URLSearchParams({
3906
- depositTxHash,
3907
- originChainId: chainConfig.chainId.toString()
3908
- });
3909
- const res = await fetch(`${ACROSS_API_BASE}/deposit/status?${params}`);
3910
- if (res.ok) {
3911
- const data = await res.json();
3912
- if (data.status === "filled" && data.fillTx) {
3913
- return { filled: true, fillTxHash: data.fillTx };
3914
- }
3915
- if (data.status === "expired" || data.status === "refunded") {
3916
- return { filled: false };
3917
- }
3918
- }
3919
- } catch {
3920
- }
3921
- await new Promise((resolve2) => setTimeout(resolve2, interval));
3922
- }
3923
- return { filled: false };
3924
- }
3925
- /** Resolve the equivalent token address on the destination chain */
3926
- resolveOutputToken(inputToken, fromChain, toChain) {
3927
- const from = getChainConfig(fromChain);
3928
- const to = getChainConfig(toChain);
3929
- if (!from || !to) return inputToken;
3930
- if (inputToken.toLowerCase() === from.usdcAddress.toLowerCase()) {
3931
- return to.usdcAddress;
3932
- }
3933
- if (inputToken.toLowerCase() === from.wethAddress.toLowerCase()) {
3934
- return to.wethAddress;
3935
- }
3936
- return inputToken;
3937
- }
3938
- };
3939
-
3940
- // src/bridge/bridge-manager.ts
3941
- var MIN_GAS_WEI = 100000000000000n;
3942
- var BridgeManager = class {
3943
- across;
3944
- client;
3945
- config;
3946
- constructor(client, config) {
3947
- this.config = config;
3948
- this.client = client;
3949
- this.across = new AcrossAdapter(client, config);
3950
- }
3951
- async estimateFee(request) {
3952
- const bridge = request.bridge ?? this.config.defaultBridge;
3953
- if (bridge !== "across") {
3954
- throw new Error(`Unsupported bridge: ${bridge}. Only "across" is currently supported.`);
3955
- }
3956
- return this.across.estimateFee(request);
3957
- }
3958
- async bridge(request) {
3959
- const bridge = request.bridge ?? this.config.defaultBridge;
3960
- if (bridge !== "across") {
3961
- return {
3962
- success: false,
3963
- depositTxHash: "0x0",
3964
- fromChain: request.fromChain,
3965
- toChain: request.toChain,
3966
- token: request.token,
3967
- amount: request.amount,
3968
- fee: 0n,
3969
- error: `Unsupported bridge: ${bridge}. Only "across" is currently supported.`
3970
- };
3971
- }
3972
- try {
3973
- const decimals = await this.client.getDecimals(request.token, request.fromChain);
3974
- const amountFloat = Number(request.amount) / 10 ** decimals;
3975
- if (amountFloat > this.config.maxBridgeValueUSD) {
3976
- return {
3977
- success: false,
3978
- depositTxHash: "0x0",
3979
- fromChain: request.fromChain,
3980
- toChain: request.toChain,
3981
- token: request.token,
3982
- amount: request.amount,
3983
- fee: 0n,
3984
- error: `Bridge value ${amountFloat.toFixed(2)} exceeds max $${this.config.maxBridgeValueUSD}. Reduce amount or increase maxBridgeValueUSD.`
3985
- };
3986
- }
3987
- } catch {
3988
- }
3989
- try {
3990
- const nativeBalance = await this.client.getNativeBalance(request.fromChain);
3991
- if (nativeBalance < MIN_GAS_WEI) {
3992
- const chainConfig = getChainConfig(request.fromChain);
3993
- const nativeName = chainConfig?.nativeCurrency ?? "ETH";
3994
- return {
3995
- success: false,
3996
- depositTxHash: "0x0",
3997
- fromChain: request.fromChain,
3998
- toChain: request.toChain,
3999
- token: request.token,
4000
- amount: request.amount,
4001
- fee: 0n,
4002
- error: `Insufficient ${nativeName} for gas on ${request.fromChain}. Balance: ${nativeBalance} wei. Need at least 0.0001 ${nativeName}.`
4003
- };
4004
- }
4005
- } catch {
4006
- }
4007
- console.log(`[bridge] Bridging via Across: ${request.fromChain} \u2192 ${request.toChain} (${request.amount})`);
4008
- return this.across.deposit(request);
4009
- }
4010
- };
4011
-
4012
- // src/runtime.ts
4013
- import { createWalletClient as createWalletClient2, http as http2, formatUnits } from "viem";
4014
- import { privateKeyToAccount as privateKeyToAccount2 } from "viem/accounts";
4015
- import { arbitrum as arbitrum2 } from "viem/chains";
4016
- var SDK_VERSION = "0.1.0";
4017
- var AgentRuntime = class _AgentRuntime {
4018
- config;
4019
- relay;
4020
- signal;
4021
- store;
4022
- positions;
4023
- llm;
4024
- strategy = null;
4025
- risk;
4026
- market;
4027
- paper = null;
4028
- // Venue clients
4029
- hlClient = null;
4030
- hlSigner = null;
4031
- hlOrders = null;
4032
- hlPositions = null;
4033
- hlWs = null;
4034
- pmClient = null;
4035
- pmOrders = null;
4036
- spotManager = null;
4037
- bridgeManager = null;
4038
- walletAddress = null;
4039
- mode = "idle";
4040
- cycleCount = 0;
4041
- lastCycleAt = 0;
4042
- tradingInterval = null;
4043
- running = false;
4044
- cycleInProgress = false;
4045
- constructor(config) {
4046
- this.config = config;
4047
- this.store = new FileStore(`data/${config.agentId}-store.json`);
4048
- this.positions = new PositionTracker(this.store);
4049
- this.market = new MarketDataService(3e4, config.apiUrl);
4050
- this.risk = new RiskManager(
4051
- {
4052
- maxPositionSizeBps: config.trading.maxPositionSizeBps,
4053
- maxDailyLossBps: config.trading.maxDailyLossBps,
4054
- maxConcurrentPositions: config.trading.maxConcurrentPositions,
4055
- maxSlippageBps: config.trading.maxSlippageBps,
4056
- minTradeValueUSD: config.trading.minTradeValueUSD
4057
- },
4058
- config.trading.initialCapitalUSD
4059
- );
4060
- this.llm = createLLMAdapter(config.llm);
4061
- this.relay = new RelayClient({
4062
- url: config.relay.url,
4063
- agentId: config.agentId,
4064
- token: config.apiToken,
4065
- heartbeatIntervalMs: config.relay.heartbeatIntervalMs,
4066
- reconnectMaxAttempts: config.relay.reconnectMaxAttempts,
4067
- onCommand: (cmd) => this.handleCommand(cmd),
4068
- onConnected: () => {
4069
- console.log(`[runtime] Connected to command center`);
4070
- this.sendStatus();
4071
- },
4072
- onDisconnected: () => {
4073
- console.log(`[runtime] Disconnected from command center`);
4074
- }
4075
- });
4076
- this.signal = new SignalReporter(this.relay);
4077
- if (config.trading.mode === "paper") {
4078
- this.paper = new PaperExecutor(config.trading.initialCapitalUSD ?? 1e4);
4079
- }
4080
- }
4081
- async start() {
4082
- console.log(`[runtime] Starting agent ${this.config.agentId}`);
4083
- console.log(`[runtime] Mode: ${this.config.trading.mode}`);
4084
- console.log(`[runtime] LLM: ${this.config.llm.provider}/${this.config.llm.model}`);
4085
- try {
4086
- this.strategy = await loadStrategy(this.config.strategy);
4087
- console.log(`[runtime] Strategy loaded`);
4088
- } catch (err) {
4089
- console.error(`[runtime] Failed to load strategy:`, err.message);
4090
- this.strategy = null;
4091
- }
4092
- if (this.config.trading.mode === "live") {
4093
- await this.initializeVenues();
4094
- }
4095
- try {
4096
- await this.relay.connect();
4097
- this.signal.reportInfo("Agent Started", `Agent ${this.config.agentId} connected to command center`);
4098
- } catch (err) {
4099
- console.error(`[runtime] Failed to connect to relay:`, err.message);
4100
- console.log(`[runtime] Will retry in background...`);
4101
- }
4102
- this.running = true;
4103
- this.mode = "idle";
4104
- this.sendStatus();
4105
- if (this.config.trading.mode === "paper" || this.config.trading.mode === "live") {
4106
- this.startTrading();
4107
- }
4108
- process.on("SIGTERM", () => this.stop());
4109
- process.on("SIGINT", () => this.stop());
4110
- }
4111
- async stop() {
4112
- console.log(`[runtime] Stopping agent ${this.config.agentId}`);
4113
- this.running = false;
4114
- this.stopTrading();
4115
- if (this.hlWs) {
4116
- this.hlWs.disconnect();
4117
- }
4118
- this.signal.reportInfo("Agent Stopped", `Agent ${this.config.agentId} shutting down`);
4119
- this.relay.disconnect();
4120
- console.log(`[runtime] Agent stopped`);
4121
- process.exit(0);
4122
- }
4123
- // ── VENUE INITIALIZATION ───────────────────────────────────
4124
- async initializeVenues() {
4125
- const privateKey = this.config.wallet?.privateKey;
4126
- if (!privateKey) {
4127
- console.log("[runtime] No wallet configured \u2014 live trading disabled");
4128
- return;
4129
- }
4130
- const walletAccount = privateKeyToAccount2(privateKey);
4131
- this.walletAddress = walletAccount.address;
4132
- const hlConfig = this.config.venues?.hyperliquid_perp;
4133
- if (hlConfig?.enabled) {
4134
- try {
4135
- const account = walletAccount;
4136
- const walletClient = createWalletClient2({
4137
- account,
4138
- chain: arbitrum2,
4139
- transport: http2()
4140
- });
4141
- const perpConfig = {
4142
- enabled: true,
4143
- apiUrl: hlConfig.apiUrl,
4144
- wsUrl: hlConfig.wsUrl,
4145
- maxLeverage: hlConfig.maxLeverage,
4146
- maxNotionalUSD: hlConfig.maxNotionalUSD,
4147
- allowedInstruments: hlConfig.allowedInstruments
4148
- };
4149
- this.hlClient = new HyperliquidClient(perpConfig);
4150
- this.hlSigner = new HyperliquidSigner(walletClient);
4151
- this.hlOrders = new HyperliquidOrderManager(this.hlClient, this.hlSigner, perpConfig);
4152
- this.hlPositions = new HyperliquidPositionManager(this.hlClient, account.address);
4153
- this.hlWs = new HyperliquidWebSocket(perpConfig, account.address, this.hlClient);
4154
- await this.hlClient.getMeta();
4155
- this.hlWs.onFillReceived((fill) => {
4156
- this.handleHyperliquidFill(fill);
4157
- });
4158
- this.hlWs.onLiquidationDetected((instrument, size) => {
4159
- this.signal.reportError("Liquidation Detected", `${instrument}: ${size} liquidated`);
4160
- });
4161
- await this.hlWs.connect();
4162
- console.log(`[runtime] Hyperliquid initialized (${account.address})`);
4163
- } catch (err) {
4164
- console.error("[runtime] Failed to initialize Hyperliquid:", err.message);
4165
- }
4166
- }
4167
- const pmConfig = this.config.venues?.polymarket;
4168
- if (pmConfig?.enabled) {
4169
- try {
4170
- const predConfig = {
4171
- enabled: true,
4172
- clobApiUrl: pmConfig.clobApiUrl,
4173
- gammaApiUrl: pmConfig.gammaApiUrl,
4174
- maxNotionalUSD: pmConfig.maxNotionalUSD,
4175
- maxTotalExposureUSD: pmConfig.maxTotalExposureUSD,
4176
- allowedCategories: pmConfig.allowedCategories
4177
- };
4178
- this.pmClient = new PolymarketClient(privateKey, predConfig);
4179
- await this.pmClient.initialize();
4180
- this.pmOrders = new PolymarketOrderManager(this.pmClient, predConfig);
4181
- console.log(`[runtime] Polymarket initialized`);
4182
- } catch (err) {
4183
- console.error("[runtime] Failed to initialize Polymarket:", err.message);
4184
- }
4185
- }
4186
- const spotConfig = this.config.venues?.spot;
4187
- if (spotConfig?.enabled) {
4188
- try {
4189
- const cfg = {
4190
- enabled: true,
4191
- chains: spotConfig.chains,
4192
- defaultChain: spotConfig.defaultChain,
4193
- maxSlippageBps: spotConfig.maxSlippageBps,
4194
- maxSwapValueUSD: spotConfig.maxSwapValueUSD
4195
- };
4196
- this.spotManager = new SpotSwapManager(privateKey, cfg);
4197
- console.log(`[runtime] Spot DEX initialized (chains: ${spotConfig.chains.join(", ")})`);
4198
- } catch (err) {
4199
- console.error("[runtime] Failed to initialize Spot DEX:", err.message);
4200
- }
4201
- }
4202
- const bridgeConfig = this.config.venues?.bridge;
4203
- if (bridgeConfig?.enabled) {
4204
- try {
4205
- if (!this.spotManager) {
4206
- const minimalSpotConfig = {
4207
- enabled: true,
4208
- chains: ["base", "ethereum", "arbitrum", "polygon"],
4209
- defaultChain: "base",
4210
- maxSlippageBps: 50,
4211
- maxSwapValueUSD: 1e4
4212
- };
4213
- this.spotManager = new SpotSwapManager(privateKey, minimalSpotConfig);
4214
- }
4215
- const cfg = {
4216
- enabled: true,
4217
- defaultBridge: bridgeConfig.defaultBridge,
4218
- maxBridgeValueUSD: bridgeConfig.maxBridgeValueUSD,
4219
- fillTimeoutMs: bridgeConfig.fillTimeoutMs,
4220
- pollIntervalMs: bridgeConfig.pollIntervalMs
4221
- };
4222
- this.bridgeManager = new BridgeManager(this.spotManager.client, cfg);
4223
- console.log(`[runtime] Bridge initialized`);
4224
- } catch (err) {
4225
- console.error("[runtime] Failed to initialize Bridge:", err.message);
4226
- }
4227
- }
4228
- }
4229
- // ── TRADING LOOP ───────────────────────────────────────────
4230
- startTrading() {
4231
- if (this.tradingInterval) return;
4232
- this.mode = this.config.trading.mode === "paper" ? "paper" : "trading";
4233
- console.log(`[runtime] Trading started (${this.mode}, interval: ${this.config.trading.tradingIntervalMs}ms)`);
4234
- this.sendStatus();
4235
- this.signal.reportInfo("Trading Started", `Mode: ${this.mode}`);
4236
- this.runCycle();
4237
- this.tradingInterval = setInterval(() => {
4238
- this.runCycle();
4239
- }, this.config.trading.tradingIntervalMs);
4240
- }
4241
- stopTrading() {
4242
- if (this.tradingInterval) {
4243
- clearInterval(this.tradingInterval);
4244
- this.tradingInterval = null;
4245
- }
4246
- this.mode = "idle";
4247
- this.sendStatus();
4248
- console.log(`[runtime] Trading stopped`);
4249
- }
4250
- async runCycle() {
4251
- if (!this.running || !this.strategy) return;
4252
- if (this.cycleInProgress) {
4253
- console.log("[runtime] Skipping cycle \u2014 previous cycle still running");
4254
- return;
4255
- }
4256
- this.cycleInProgress = true;
4257
- this.cycleCount++;
4258
- this.lastCycleAt = Date.now();
4259
- try {
4260
- const positionSymbols = this.positions.getPositions().map((p) => p.token);
4261
- await this.market.refreshPrices(positionSymbols);
4262
- const prices = this.market.getPrices();
4263
- const positionSummary = this.positions.getSummary(prices);
4264
- const rawSignals = await this.strategy({
4265
- llm: this.llm,
4266
- market: this.market,
4267
- position: positionSummary,
4268
- store: this.store,
4269
- config: this.config.trading,
4270
- log: (msg) => {
4271
- console.log(`[strategy] ${msg}`);
4272
- this.signal.reportInfo("Strategy Log", msg);
4273
- }
4274
- });
4275
- if (!Array.isArray(rawSignals) || rawSignals.length === 0) {
4276
- await this.pollPredictionFills();
4277
- this.sendStatus();
4278
- return;
4279
- }
4280
- const signals = rawSignals.map((sig) => this.convertToExecutableSignal(sig, prices));
4281
- const filtered = this.risk.filterSignals(signals, this.market, positionSummary.openPositions.length);
4282
- for (const sig of filtered) {
4283
- try {
4284
- await this.executeSignal(sig);
4285
- } catch (err) {
4286
- console.error(`[runtime] Trade execution error:`, err.message);
4287
- this.signal.reportError("Trade Error", err.message);
4288
- }
4289
- }
4290
- await this.pollPredictionFills();
4291
- } catch (err) {
4292
- console.error(`[runtime] Cycle error:`, err.message);
4293
- this.signal.reportError("Cycle Error", err.message);
4294
- this.mode = "idle";
4295
- } finally {
4296
- this.cycleInProgress = false;
4297
- }
4298
- this.sendStatus();
4299
- }
4300
- // ── SIGNAL EXECUTION ───────────────────────────────────────
4301
- async executeSignal(sig) {
4302
- const venue = sig.venue;
4303
- if (this.paper) {
4304
- const trade = this.paper.execute(sig, this.market);
4305
- if (trade) {
4306
- this.risk.recordTrade(trade.pnl ?? 0, trade.fee);
4307
- if (this.risk.isDailyLossLimitHit()) {
4308
- console.warn(`[runtime] Daily loss limit hit (paper) \u2014 stopping trading`);
4309
- this.signal.reportError("Daily Loss Limit", `Daily PnL: $${this.risk.getDailyPnL().toFixed(2)} exceeds limit`);
4310
- this.stopTrading();
4311
- }
4312
- this.signal.reportTrade({
4313
- ...sig,
4314
- price: trade.entryPrice,
4315
- fee: trade.fee,
4316
- venue: trade.venue,
4317
- venueFillId: trade.id,
4318
- venueTimestamp: new Date(trade.timestamp).toISOString()
4319
- });
4320
- }
4321
- return;
4322
- }
4323
- if (venue === "hyperliquid_perp" && this.hlOrders) {
4324
- await this.executeHyperliquidSignal(sig);
4325
- } else if (venue === "polymarket" && this.pmOrders) {
4326
- await this.executePolymarketSignal(sig);
4327
- } else if ((venue === "uniswap" || venue === "aerodrome" || venue === "sushiswap") && this.spotManager) {
4328
- await this.executeSpotSignal(sig);
4329
- } else if (venue === "across" && this.bridgeManager) {
4330
- await this.executeBridgeSignal(sig);
4331
- } else if (venue === "hyperliquid_deposit" && this.hlSigner) {
4332
- await this.executeHyperliquidDeposit(sig);
4333
- } else if (venue === "hyperliquid_withdraw" && this.hlSigner) {
4334
- await this.executeHyperliquidWithdraw(sig);
4335
- } else {
4336
- console.log(`[runtime] No executor for venue "${venue}" \u2014 signal dropped`);
4337
- }
4338
- }
4339
- /**
4340
- * Convert a raw strategy output to an executable TradeSignal.
4341
- * LLM templates return { symbol, side, confidence, reasoning } but execution
4342
- * needs { price, size, fee, venue, venueFillId, venueTimestamp }.
4343
- */
4344
- convertToExecutableSignal(sig, prices) {
4345
- const result = { ...sig };
4346
- if (!result.price || result.price <= 0) {
4347
- const marketPrice = prices[result.symbol?.toUpperCase()] ?? this.market.getPrice(result.symbol);
4348
- if (marketPrice) {
4349
- result.price = marketPrice;
4350
- } else {
4351
- console.warn(`[runtime] No price for ${result.symbol} \u2014 signal may fail risk checks`);
4352
- result.price = 0;
4353
- }
4354
- }
4355
- if (!result.size || result.size <= 0) {
4356
- if (result.confidence && result.price > 0) {
4357
- const maxPositionBps = this.config.trading.maxPositionSizeBps;
4358
- const capital = this.config.trading.initialCapitalUSD ?? 1e4;
4359
- const usdSize = result.confidence * (maxPositionBps / 1e4) * capital;
4360
- result.size = usdSize / result.price;
4361
- }
4362
- }
4363
- if (result.fee === void 0 || result.fee === null) {
4364
- result.fee = 0;
4365
- }
4366
- if (!result.venueFillId) result.venueFillId = "";
4367
- if (!result.venueTimestamp) result.venueTimestamp = "";
4368
- if (!result.venue) {
4369
- if (this.hlOrders) {
4370
- result.venue = "hyperliquid_perp";
4371
- } else if (this.pmOrders) {
4372
- result.venue = "polymarket";
4373
- } else if (this.spotManager) {
4374
- result.venue = this.config.venues?.spot?.defaultChain === "base" ? "aerodrome" : "uniswap";
4375
- }
4376
- }
4377
- return result;
4378
- }
4379
- async executeHyperliquidSignal(sig) {
4380
- if (!this.hlOrders) return;
4381
- const action = sig.side === "long" ? "open_long" : sig.side === "short" ? "open_short" : sig.side === "buy" ? "open_long" : "close_long";
4382
- const result = await this.hlOrders.placeOrder({
4383
- action,
4384
- instrument: sig.symbol,
4385
- size: sig.size,
4386
- price: sig.price,
4387
- leverage: sig.leverage ?? 1,
4388
- orderType: sig.orderType ?? "market",
4389
- reduceOnly: action.startsWith("close"),
4390
- confidence: sig.confidence ?? 1,
4391
- reasoning: sig.reasoning
4392
- });
4393
- if (result.success && result.status === "filled") {
4394
- console.log(`[runtime] HL order filled: ${sig.symbol} ${result.avgPrice}`);
4395
- } else if (result.success && result.status === "resting") {
4396
- console.log(`[runtime] HL order resting: ${sig.symbol} (oid: ${result.orderId})`);
4397
- } else {
4398
- console.warn(`[runtime] HL order failed: ${result.error}`);
4399
- this.signal.reportError("Perp Order Failed", `${sig.symbol}: ${result.error}`);
4400
- }
4401
- }
4402
- async executePolymarketSignal(sig) {
4403
- if (!this.pmOrders) return;
4404
- const isNo = sig.orderType === "no";
4405
- const outcomeIndex = isNo ? 1 : 0;
4406
- const isBuy = sig.side === "buy" || sig.side === "long";
4407
- const action = isBuy ? isNo ? "buy_no" : "buy_yes" : isNo ? "sell_no" : "sell_yes";
4408
- const result = await this.pmOrders.executeSignal({
4409
- action,
4410
- marketConditionId: sig.symbol,
4411
- marketQuestion: sig.reasoning ?? sig.symbol,
4412
- outcomeIndex,
4413
- amount: sig.size,
4414
- limitPrice: sig.price,
4415
- orderType: "limit",
4416
- confidence: sig.confidence ?? 1,
4417
- reasoning: sig.reasoning
4418
- });
4419
- if (result.success) {
4420
- console.log(`[runtime] PM order placed: ${sig.symbol}`);
4421
- } else {
4422
- console.warn(`[runtime] PM order failed: ${result.error}`);
4423
- this.signal.reportError("Prediction Order Failed", `${sig.symbol}: ${result.error}`);
4424
- }
4425
- }
4426
- async executeSpotSignal(sig) {
4427
- if (!this.spotManager) return;
4428
- const chain = sig.chain ?? this.config.venues?.spot?.defaultChain ?? "base";
4429
- const dex = sig.venue === "aerodrome" ? "aerodrome" : "uniswap";
4430
- const parts = sig.symbol.split("/");
4431
- const isBuy = sig.side === "buy" || sig.side === "long";
4432
- const tokenIn = isBuy ? parts[1] ?? "USDC" : parts[0] ?? sig.symbol;
4433
- const tokenOut = isBuy ? parts[0] ?? sig.symbol : parts[1] ?? "USDC";
4434
- const tokenInAddress = this.spotManager.resolveToken(tokenIn, chain);
4435
- const decimals = await this.spotManager.client.getDecimals(tokenInAddress, chain);
4436
- const amountIn = BigInt(Math.floor(sig.size * 10 ** decimals));
4437
- const result = await this.spotManager.executeSwap({
4438
- tokenIn,
4439
- tokenOut,
4440
- amountIn,
4441
- chain,
4442
- dex
4443
- });
4444
- if (result.success) {
4445
- const tokenOutSymbol = await this.spotManager.client.getSymbol(result.tokenOut, chain);
4446
- const tokenInSymbol = await this.spotManager.client.getSymbol(result.tokenIn, chain);
4447
- const tokenOutDecimals = await this.spotManager.client.getDecimals(result.tokenOut, chain);
4448
- const amountOutFloat = Number(result.amountOut) / 10 ** tokenOutDecimals;
4449
- const amountInFloat = Number(result.amountIn) / 10 ** decimals;
4450
- const tradeSignal = {
4451
- venue: result.dex,
4452
- chain,
4453
- symbol: `${parts[0] ?? sig.symbol}`,
4454
- side: sig.side,
4455
- size: isBuy ? amountOutFloat : amountInFloat,
4456
- price: result.effectivePrice,
4457
- fee: Number(result.gasCost) / 1e18,
4458
- venueFillId: result.txHash,
4459
- venueTimestamp: (/* @__PURE__ */ new Date()).toISOString()
4460
- };
4461
- const baseToken = parts[0] ?? sig.symbol;
4462
- let realizedPnL = 0;
4463
- if (isBuy) {
4464
- realizedPnL = this.positions.recordBuy(
4465
- baseToken,
4466
- amountOutFloat,
4467
- result.effectivePrice,
4468
- tradeSignal.fee,
4469
- result.dex,
4470
- chain,
4471
- result.txHash
4472
- );
4473
- } else {
4474
- realizedPnL = this.positions.recordSell(
4475
- baseToken,
4476
- amountInFloat,
4477
- result.effectivePrice,
4478
- tradeSignal.fee,
4479
- result.dex,
4480
- chain,
4481
- result.txHash
4482
- );
4483
- }
4484
- this.risk.recordTrade(realizedPnL, tradeSignal.fee);
4485
- if (this.risk.isDailyLossLimitHit()) {
4486
- console.warn(`[runtime] Daily loss limit hit \u2014 stopping trading`);
4487
- this.signal.reportError("Daily Loss Limit", `Daily PnL: $${this.risk.getDailyPnL().toFixed(2)} exceeds limit`);
4488
- this.stopTrading();
4489
- }
4490
- this.signal.reportSpotFill(tradeSignal);
4491
- console.log(`[runtime] Spot swap filled: ${tokenInSymbol} \u2192 ${tokenOutSymbol} on ${result.dex}/${chain}`);
4492
- } else {
4493
- console.warn(`[runtime] Spot swap failed: ${result.error}`);
4494
- this.signal.reportError("Spot Swap Failed", `${sig.symbol}: ${result.error}`);
4495
- }
4496
- }
4497
- async executeBridgeSignal(sig) {
4498
- if (!this.bridgeManager || !this.spotManager) return;
4499
- const toChain = sig.chain ?? "arbitrum";
4500
- const fromChain = sig.orderType ?? "base";
4501
- const tokenAddress = this.spotManager.resolveToken(sig.symbol, fromChain);
4502
- const decimals = await this.spotManager.client.getDecimals(tokenAddress, fromChain);
4503
- const amount = BigInt(Math.floor(sig.size * 10 ** decimals));
4504
- const result = await this.bridgeManager.bridge({
4505
- token: tokenAddress,
4506
- amount,
4507
- fromChain,
4508
- toChain
4509
- });
4510
- if (result.success) {
4511
- const tradeSignal = {
4512
- venue: "across",
4513
- chain: toChain,
4514
- symbol: sig.symbol,
4515
- side: "buy",
4516
- size: sig.size,
4517
- price: sig.price || 1,
4518
- fee: Number(result.fee) / 10 ** decimals,
4519
- venueFillId: result.depositTxHash,
4520
- venueTimestamp: (/* @__PURE__ */ new Date()).toISOString()
4521
- };
4522
- this.signal.reportBridgeFill(tradeSignal);
4523
- console.log(`[runtime] Bridge completed: ${fromChain} \u2192 ${toChain} via Across`);
4524
- } else {
4525
- console.warn(`[runtime] Bridge failed: ${result.error}`);
4526
- this.signal.reportError("Bridge Failed", `${sig.symbol} ${fromChain}\u2192${toChain}: ${result.error}`);
4527
- }
4528
- }
4529
- // ── HYPERLIQUID DEPOSIT / WITHDRAW ────────────────────────
4530
- /** Hyperliquid bridge contract on Arbitrum — accepts plain USDC transfers */
4531
- static HL_BRIDGE_CONTRACT = "0x2Df1c51E09aECF9cacB7bc98cB1742757f163dF7";
4532
- /**
4533
- * Deposit USDC into Hyperliquid by transferring to the bridge contract on Arbitrum.
4534
- * Signal format: venue='hyperliquid_deposit', size=amount in USDC, chain is ignored (always Arbitrum).
4535
- * The wallet must already have USDC + ETH for gas on Arbitrum.
4536
- */
4537
- async executeHyperliquidDeposit(sig) {
4538
- if (!this.spotManager) {
4539
- this.signal.reportError("HL Deposit Failed", "Spot manager not initialized (needed for chain clients)");
4540
- return;
4541
- }
4542
- const arbConfig = getChainConfig("arbitrum");
4543
- if (!arbConfig) {
4544
- this.signal.reportError("HL Deposit Failed", "Arbitrum chain config not found");
4545
- return;
4546
- }
4547
- const usdcAddress = arbConfig.usdcAddress;
4548
- const amount = BigInt(Math.floor(sig.size * 1e6));
4549
- const MIN_GAS_WEI2 = 100000000000000n;
4550
- try {
4551
- const gasBalance = await this.spotManager.client.getNativeBalance("arbitrum");
4552
- if (gasBalance < MIN_GAS_WEI2) {
4553
- this.signal.reportError("HL Deposit Failed", `Insufficient ETH for gas on Arbitrum. Balance: ${formatUnits(gasBalance, 18)} ETH. Need at least 0.0001 ETH.`);
4554
- return;
4555
- }
4556
- } catch {
4557
- }
4558
- try {
4559
- const usdcBalance = await this.spotManager.client.getBalance(usdcAddress, "arbitrum");
4560
- if (usdcBalance < amount) {
4561
- this.signal.reportError("HL Deposit Failed", `Insufficient USDC on Arbitrum. Have ${formatUnits(usdcBalance, 6)}, need ${formatUnits(amount, 6)}. Bridge USDC to Arbitrum first.`);
4562
- return;
4563
- }
4564
- } catch (err) {
4565
- this.signal.reportError("HL Deposit Failed", `Could not check USDC balance: ${err.message}`);
4566
- return;
4567
- }
4568
- try {
4569
- const { publicClient, walletClient } = this.spotManager.client.getClients("arbitrum");
4570
- const hash = await walletClient.writeContract({
4571
- address: usdcAddress,
4572
- abi: ERC20_ABI,
4573
- functionName: "transfer",
4574
- args: [_AgentRuntime.HL_BRIDGE_CONTRACT, amount]
4575
- });
4576
- const receipt = await publicClient.waitForTransactionReceipt({ hash });
4577
- if (receipt.status === "reverted") {
4578
- this.signal.reportError("HL Deposit Failed", `Transfer reverted: ${hash}`);
4579
- return;
4580
- }
4581
- console.log(`[runtime] HL deposit: ${formatUnits(amount, 6)} USDC \u2192 Hyperliquid (tx: ${hash})`);
4582
- this.signal.reportInfo("HL Deposit", `Deposited ${formatUnits(amount, 6)} USDC to Hyperliquid`);
4583
- } catch (err) {
4584
- console.error("[runtime] HL deposit failed:", err.message);
4585
- this.signal.reportError("HL Deposit Failed", err.message);
4586
- }
4587
- }
4588
- /**
4589
- * Withdraw USDC from Hyperliquid to the wallet on Arbitrum.
4590
- * Signal format: venue='hyperliquid_withdraw', size=amount in USDC.
4591
- * Uses the withdraw3 EIP-712 signing scheme.
4592
- */
4593
- async executeHyperliquidWithdraw(sig) {
4594
- if (!this.hlSigner || !this.hlClient) {
4595
- this.signal.reportError("HL Withdraw Failed", "Hyperliquid signer/client not initialized");
4596
- return;
4597
- }
4598
- const destination = this.hlSigner.getAddress();
4599
- const amount = sig.size.toString();
4600
- try {
4601
- const { action, signature, nonce } = await this.hlSigner.signWithdraw(destination, amount);
4602
- const apiUrl = this.config.venues?.hyperliquid_perp?.apiUrl ?? "https://api.hyperliquid.xyz";
4603
- const resp = await fetch(`${apiUrl}/exchange`, {
4604
- method: "POST",
4605
- headers: { "Content-Type": "application/json" },
4606
- body: JSON.stringify({ action, nonce, signature, vaultAddress: null })
4607
- });
4608
- if (!resp.ok) {
4609
- const text = await resp.text();
4610
- throw new Error(`HL Exchange API error: ${resp.status} ${text}`);
4611
- }
4612
- const data = await resp.json();
4613
- if (data.status !== "ok") {
4614
- throw new Error(`HL withdraw3 failed: ${JSON.stringify(data)}`);
4615
- }
4616
- console.log(`[runtime] HL withdrawal: ${amount} USDC \u2192 ${destination} on Arbitrum`);
4617
- this.signal.reportInfo("HL Withdrawal", `Withdrew ${amount} USDC from Hyperliquid to ${destination}`);
4618
- } catch (err) {
4619
- console.error("[runtime] HL withdrawal failed:", err.message);
4620
- this.signal.reportError("HL Withdraw Failed", err.message);
4621
- }
4622
- }
4623
- // ── FILL HANDLING ──────────────────────────────────────────
4624
- handleHyperliquidFill(fill) {
4625
- const tradeSignal = {
4626
- venue: "hyperliquid_perp",
4627
- symbol: fill.coin,
4628
- side: fill.side === "B" ? "long" : "short",
4629
- size: parseFloat(fill.sz),
4630
- price: parseFloat(fill.px),
4631
- fee: parseFloat(fill.fee),
4632
- venueFillId: fill.hash,
4633
- venueTimestamp: new Date(fill.time).toISOString(),
4634
- orderType: fill.isMaker ? "limit" : "market"
4635
- };
4636
- const action = fill.side === "B" ? "buy" : "sell";
4637
- const fee = parseFloat(fill.fee);
4638
- let realizedPnL = 0;
4639
- if (action === "buy") {
4640
- realizedPnL = this.positions.recordBuy(
4641
- fill.coin,
4642
- parseFloat(fill.sz),
4643
- parseFloat(fill.px),
4644
- fee,
4645
- "hyperliquid_perp",
4646
- void 0,
4647
- fill.hash
4648
- );
4649
- } else {
4650
- realizedPnL = this.positions.recordSell(
4651
- fill.coin,
4652
- parseFloat(fill.sz),
4653
- parseFloat(fill.px),
4654
- fee,
4655
- "hyperliquid_perp",
4656
- void 0,
4657
- fill.hash
4658
- );
4659
- }
4660
- this.risk.recordTrade(realizedPnL, fee);
4661
- if (this.risk.isDailyLossLimitHit()) {
4662
- console.warn(`[runtime] Daily loss limit hit \u2014 stopping trading`);
4663
- this.signal.reportError("Daily Loss Limit", `Daily PnL: $${this.risk.getDailyPnL().toFixed(2)} exceeds limit of -$${this.risk.getDailyLossLimit().toFixed(2)}`);
4664
- this.stopTrading();
4665
- }
4666
- this.signal.reportPerpFill(tradeSignal);
4667
- }
4668
- async pollPredictionFills() {
4669
- if (!this.pmOrders) return;
4670
- try {
4671
- const newFills = await this.pmOrders.pollNewFills();
4672
- for (const fill of newFills) {
4673
- const tradeSignal = {
4674
- venue: "polymarket",
4675
- chain: "polygon",
4676
- symbol: encodePredictionInstrument(fill.marketConditionId, fill.outcomeIndex),
4677
- side: fill.side === "BUY" ? "buy" : "sell",
4678
- size: parseFloat(fill.size),
4679
- price: parseFloat(fill.price),
4680
- fee: parseFloat(fill.fee),
4681
- venueFillId: fill.tradeId,
4682
- venueTimestamp: new Date(fill.timestamp).toISOString()
4683
- };
4684
- const fillFee = parseFloat(fill.fee);
4685
- let realizedPnL = 0;
4686
- if (fill.side === "BUY") {
4687
- realizedPnL = this.positions.recordBuy(
4688
- tradeSignal.symbol,
4689
- parseFloat(fill.size),
4690
- parseFloat(fill.price),
4691
- fillFee,
4692
- "polymarket",
4693
- "polygon",
4694
- fill.tradeId
4695
- );
4696
- } else {
4697
- realizedPnL = this.positions.recordSell(
4698
- tradeSignal.symbol,
4699
- parseFloat(fill.size),
4700
- parseFloat(fill.price),
4701
- fillFee,
4702
- "polymarket",
4703
- "polygon",
4704
- fill.tradeId
4705
- );
4706
- }
4707
- this.risk.recordTrade(realizedPnL, fillFee);
4708
- if (this.risk.isDailyLossLimitHit()) {
4709
- console.warn(`[runtime] Daily loss limit hit \u2014 stopping trading`);
4710
- this.signal.reportError("Daily Loss Limit", `Daily PnL: $${this.risk.getDailyPnL().toFixed(2)} exceeds limit`);
4711
- this.stopTrading();
4712
- }
4713
- this.signal.reportPredictionFill(tradeSignal);
4714
- }
4715
- } catch (err) {
4716
- console.warn("[runtime] Prediction fill poll error:", err.message);
4717
- }
4718
- }
4719
- // ── COMMANDS ───────────────────────────────────────────────
4720
- handleCommand(command) {
4721
- console.log(`[runtime] Command received: ${command.type} (${command.id})`);
4722
- switch (command.type) {
4723
- case "start_trading":
4724
- this.startTrading();
4725
- this.relay.sendCommandAck(command.id, true, "Trading started");
4726
- break;
4727
- case "stop_trading":
4728
- this.stopTrading();
4729
- this.relay.sendCommandAck(command.id, true, "Trading stopped");
4730
- break;
4731
- case "pause_trading":
4732
- this.stopTrading();
4733
- this.relay.sendCommandAck(command.id, true, "Trading paused");
4734
- break;
4735
- case "update_risk_params":
4736
- if (command.params) {
4737
- this.risk.updateParams(command.params);
4738
- this.sendStatus();
4739
- this.relay.sendCommandAck(command.id, true, "Risk params updated");
4740
- } else {
4741
- this.relay.sendCommandAck(command.id, false, "No params provided");
4742
- }
4743
- break;
4744
- case "get_status":
4745
- this.sendStatus();
4746
- this.relay.sendCommandAck(command.id, true);
4747
- break;
4748
- case "reload_config":
4749
- this.reloadConfig(command);
4750
- break;
4751
- default:
4752
- console.warn(`[runtime] Unknown command: ${command.type}`);
4753
- this.relay.sendCommandAck(command.id, false, `Unknown command: ${command.type}`);
4754
- }
4755
- }
4756
- async reloadConfig(command) {
4757
- try {
4758
- const apiBase = this.config.apiUrl || this.config.relay.url.replace(/\/ws\/.*/, "");
4759
- const res = await fetch(`${apiBase}/v1/agents/${this.config.agentId}`, {
4760
- headers: { "Authorization": `Bearer ${this.config.apiToken}` }
4761
- });
4762
- if (!res.ok) {
4763
- throw new Error(`API returned ${res.status}`);
4764
- }
4765
- const agent = await res.json();
4766
- if (agent.config) {
4767
- const cfg = agent.config;
4768
- const risk = cfg.risk;
4769
- if (risk) {
4770
- const updates = {};
4771
- if (typeof risk.maxPositionSize === "number") updates.maxPositionSizeBps = risk.maxPositionSize * 100;
4772
- if (typeof risk.maxDailyLoss === "number") updates.maxDailyLossBps = risk.maxDailyLoss * 100;
4773
- if (typeof risk.maxConcurrentPositions === "number") updates.maxConcurrentPositions = risk.maxConcurrentPositions;
4774
- if (typeof risk.slippageTolerance === "number") updates.maxSlippageBps = risk.slippageTolerance * 100;
4775
- if (typeof risk.tradingInterval === "number") {
4776
- this.config.trading.tradingIntervalMs = risk.tradingInterval * 1e3;
4777
- }
4778
- if (Object.keys(updates).length > 0) {
4779
- this.risk.updateParams(updates);
4780
- }
4781
- }
4782
- console.log("[runtime] Config reloaded from API");
4783
- this.sendStatus();
4784
- }
4785
- this.relay.sendCommandAck(command.id, true, "Config reloaded");
4786
- } catch (err) {
4787
- console.error("[runtime] Config reload failed:", err.message);
4788
- this.relay.sendCommandAck(command.id, false, err.message);
4789
- }
4790
- }
4791
- // ── STATUS ─────────────────────────────────────────────────
4792
- sendStatus() {
4793
- const prices = this.market.getPrices();
4794
- const positionSummary = this.positions.getSummary(prices);
4795
- if (this.paper) {
4796
- this.paper.recordEquityWithPrices(prices);
4797
- }
4798
- const status = {
4799
- mode: this.mode,
4800
- agentId: this.config.agentId,
4801
- walletAddress: this.walletAddress || void 0,
4802
- sdkVersion: SDK_VERSION,
4803
- cycleCount: this.cycleCount,
4804
- lastCycleAt: this.lastCycleAt,
4805
- tradingIntervalMs: this.config.trading.tradingIntervalMs,
4806
- llm: {
4807
- provider: this.config.llm.provider,
4808
- model: this.config.llm.model || "default"
4809
- },
4810
- risk: {
4811
- dailyPnL: this.risk.getDailyPnL(),
4812
- dailyLossLimit: this.risk.getDailyLossLimit(),
4813
- isLimitHit: this.risk.isDailyLossLimitHit()
4814
- },
4815
- positions: {
4816
- openPositions: positionSummary.openPositions.length,
4817
- totalUnrealizedPnL: positionSummary.totalUnrealizedPnL,
4818
- totalRealizedPnL: positionSummary.totalRealizedPnL
4819
- },
4820
- venues: {
4821
- hyperliquid: {
4822
- enabled: !!this.hlClient,
4823
- trading: !!this.hlOrders && this.mode === "trading"
4824
- },
4825
- polymarket: {
4826
- enabled: !!this.pmClient,
4827
- trading: !!this.pmOrders && this.mode === "trading"
4828
- },
4829
- spot: {
4830
- enabled: !!this.spotManager,
4831
- trading: !!this.spotManager && this.mode === "trading"
4832
- },
4833
- bridge: {
4834
- enabled: !!this.bridgeManager
4835
- }
4836
- }
4837
- };
4838
- if (this.paper) {
4839
- const metrics = this.paper.getMetrics();
4840
- status.paper = {
4841
- active: true,
4842
- simulatedValue: this.paper.getEquity(),
4843
- simulatedPnLPct: metrics.totalReturn * 100
4844
- };
4845
- status.portfolioValue = this.paper.getEquity();
4846
- }
4847
- this.relay.sendHeartbeat(status);
4848
- }
4849
- };
4850
-
4851
- export {
4852
- loadConfig,
4853
- generateSampleConfig,
4854
- writeSampleConfig,
4855
- CHAIN_CONFIGS,
4856
- getChainConfig,
4857
- DEFAULT_SPOT_CONFIG,
4858
- RelayClient,
4859
- SignalReporter,
4860
- FileStore,
4861
- PositionTracker,
4862
- createLLMAdapter,
4863
- getTemplate,
4864
- listTemplates,
4865
- loadStrategy,
4866
- RiskManager,
4867
- MarketDataService,
4868
- PaperExecutor,
4869
- HyperliquidClient,
4870
- HYPERLIQUID_DOMAIN,
4871
- HYPERLIQUID_USER_DOMAIN,
4872
- USER_ACTION_TYPES,
4873
- getNextNonce,
4874
- HyperliquidSigner,
4875
- HyperliquidOrderManager,
4876
- HyperliquidPositionManager,
4877
- HyperliquidWebSocket,
4878
- encodePredictionInstrument,
4879
- decodePredictionInstrument,
4880
- PolymarketClient,
4881
- PolymarketOrderManager,
4882
- SpotDEXClient,
4883
- UniswapAdapter,
4884
- AerodromeAdapter,
4885
- SpotSwapManager,
4886
- DEFAULT_BRIDGE_CONFIG,
4887
- AcrossAdapter,
4888
- BridgeManager,
4889
- AgentRuntime
4890
- };