@exagent/agent 0.3.3 → 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 (148) hide show
  1. package/dist/{chunk-F4TCYYTD.js → chunk-WTECTX2Z.js} +13 -1
  2. package/dist/cli.js +155 -78
  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 +18 -1
  7. package/src/setup.ts +46 -64
  8. package/dist/chunk-25J5ZDKX.js +0 -5622
  9. package/dist/chunk-2ML4XS5X.js +0 -5626
  10. package/dist/chunk-2OKYNZ3J.js +0 -5622
  11. package/dist/chunk-2PAASZJN.js +0 -5132
  12. package/dist/chunk-2WAYVOLU.js +0 -5624
  13. package/dist/chunk-2XBVVY3I.js +0 -5621
  14. package/dist/chunk-37HCPVBZ.js +0 -2941
  15. package/dist/chunk-3DZAZBLF.js +0 -5652
  16. package/dist/chunk-3IXCKNSV.js +0 -5008
  17. package/dist/chunk-3MXFTRXB.js +0 -3326
  18. package/dist/chunk-4MURFLNJ.js +0 -5136
  19. package/dist/chunk-4UVMO6ZM.js +0 -6318
  20. package/dist/chunk-56YQROFU.js +0 -5639
  21. package/dist/chunk-5B3ZEGMD.js +0 -4330
  22. package/dist/chunk-5NU6FDDE.js +0 -6020
  23. package/dist/chunk-5WADKPJU.js +0 -1552
  24. package/dist/chunk-6LOIFEEV.js +0 -4895
  25. package/dist/chunk-6YIXPNL4.js +0 -5626
  26. package/dist/chunk-72HK2V74.js +0 -5224
  27. package/dist/chunk-7Q72QQIV.js +0 -4697
  28. package/dist/chunk-7V3XTBIF.js +0 -4896
  29. package/dist/chunk-A4CM4F7Q.js +0 -5633
  30. package/dist/chunk-ADXXR2MA.js +0 -4816
  31. package/dist/chunk-AG6CJPIC.js +0 -4895
  32. package/dist/chunk-AJPXHBTF.js +0 -4459
  33. package/dist/chunk-AQ6R37XV.js +0 -4809
  34. package/dist/chunk-AS4UEZMU.js +0 -5001
  35. package/dist/chunk-ASYMD22Y.js +0 -5624
  36. package/dist/chunk-AU4MCQCE.js +0 -5624
  37. package/dist/chunk-B4VHIITU.js +0 -5748
  38. package/dist/chunk-B6GVDNKQ.js +0 -5624
  39. package/dist/chunk-BCIAW6ZL.js +0 -5132
  40. package/dist/chunk-BJZ5PCG3.js +0 -5358
  41. package/dist/chunk-BS4J5QSM.js +0 -5622
  42. package/dist/chunk-BV2AUUX6.js +0 -2940
  43. package/dist/chunk-BWNSH2LK.js +0 -1574
  44. package/dist/chunk-C3GMBW3R.js +0 -5640
  45. package/dist/chunk-C6CVQGJ4.js +0 -5624
  46. package/dist/chunk-CGXKXNUJ.js +0 -5626
  47. package/dist/chunk-CIEZAYOU.js +0 -4701
  48. package/dist/chunk-CORZCEAQ.js +0 -5621
  49. package/dist/chunk-CS5LGZWP.js +0 -5357
  50. package/dist/chunk-CVT3KC24.js +0 -5624
  51. package/dist/chunk-D5MJ45R7.js +0 -3258
  52. package/dist/chunk-DSBRZ5DZ.js +0 -5624
  53. package/dist/chunk-E2X7JARQ.js +0 -4437
  54. package/dist/chunk-E3GY36ZP.js +0 -3258
  55. package/dist/chunk-E6NCIFKB.js +0 -4733
  56. package/dist/chunk-EOXLKW4D.js +0 -4895
  57. package/dist/chunk-FCI7LX4Q.js +0 -5624
  58. package/dist/chunk-FFJSKTOL.js +0 -4539
  59. package/dist/chunk-FOQYP3IB.js +0 -2950
  60. package/dist/chunk-GNEYTZDH.js +0 -4686
  61. package/dist/chunk-GPMXUMYH.js +0 -5991
  62. package/dist/chunk-GZWPAQPU.js +0 -4593
  63. package/dist/chunk-H5DXDKMX.js +0 -5619
  64. package/dist/chunk-HFQRTMS6.js +0 -3377
  65. package/dist/chunk-HQKRHX6Y.js +0 -5626
  66. package/dist/chunk-HTF3TNBY.js +0 -4834
  67. package/dist/chunk-IADSQBBY.js +0 -5523
  68. package/dist/chunk-IE2SXMZK.js +0 -4890
  69. package/dist/chunk-IGUQVJCB.js +0 -5622
  70. package/dist/chunk-IIREL7SL.js +0 -5615
  71. package/dist/chunk-IJK4EFTJ.js +0 -6043
  72. package/dist/chunk-J2MQ3Y5O.js +0 -5223
  73. package/dist/chunk-J3NG7AGT.js +0 -6047
  74. package/dist/chunk-JIBBZ3NV.js +0 -5132
  75. package/dist/chunk-JIPSBE6S.js +0 -5622
  76. package/dist/chunk-JPG755XK.js +0 -4589
  77. package/dist/chunk-JQBNL5GX.js +0 -5230
  78. package/dist/chunk-KS3F5WSX.js +0 -4831
  79. package/dist/chunk-KUYTQ4FR.js +0 -4808
  80. package/dist/chunk-KVP4CMJ5.js +0 -4711
  81. package/dist/chunk-LAR2I44B.js +0 -5626
  82. package/dist/chunk-LBTHSED2.js +0 -1531
  83. package/dist/chunk-M6OAMYVM.js +0 -5621
  84. package/dist/chunk-MFN5WWOY.js +0 -5132
  85. package/dist/chunk-MMTSKXLK.js +0 -5624
  86. package/dist/chunk-MPUSQLTH.js +0 -5626
  87. package/dist/chunk-MREXDTWL.js +0 -1555
  88. package/dist/chunk-MUEDKRFC.js +0 -5624
  89. package/dist/chunk-NOVPL2JH.js +0 -3327
  90. package/dist/chunk-NQIP4MHV.js +0 -4334
  91. package/dist/chunk-NXXKMYLS.js +0 -5624
  92. package/dist/chunk-OBYNZXNM.js +0 -4756
  93. package/dist/chunk-OFY4HBOJ.js +0 -5624
  94. package/dist/chunk-OJNUEZEK.js +0 -5602
  95. package/dist/chunk-OQCJOMUQ.js +0 -5624
  96. package/dist/chunk-OZH75GY6.js +0 -5132
  97. package/dist/chunk-P3IJVDMZ.js +0 -4700
  98. package/dist/chunk-PMYMYMBH.js +0 -4877
  99. package/dist/chunk-PRELNRVN.js +0 -5623
  100. package/dist/chunk-PSQUSNSI.js +0 -4703
  101. package/dist/chunk-QAIQ5IB6.js +0 -5624
  102. package/dist/chunk-QG22GADV.js +0 -6316
  103. package/dist/chunk-QNE2KGGK.js +0 -3315
  104. package/dist/chunk-RH7ZBSG4.js +0 -5132
  105. package/dist/chunk-RLD5MUCR.js +0 -5626
  106. package/dist/chunk-S42VEBNR.js +0 -3268
  107. package/dist/chunk-SEM6UXU4.js +0 -3324
  108. package/dist/chunk-SI5WP77M.js +0 -4430
  109. package/dist/chunk-SID4SQSY.js +0 -4837
  110. package/dist/chunk-SIELPKWF.js +0 -1558
  111. package/dist/chunk-SVBLY6QT.js +0 -5742
  112. package/dist/chunk-SVFTC5V2.js +0 -6021
  113. package/dist/chunk-SXHTX62B.js +0 -4823
  114. package/dist/chunk-T2YCEA5U.js +0 -4730
  115. package/dist/chunk-TARCHIOU.js +0 -4718
  116. package/dist/chunk-TDACLKD7.js +0 -5867
  117. package/dist/chunk-TGCBM3NP.js +0 -4890
  118. package/dist/chunk-TIWG6KAK.js +0 -4769
  119. package/dist/chunk-TKLKATVM.js +0 -1534
  120. package/dist/chunk-TSLZ4A5P.js +0 -5222
  121. package/dist/chunk-TWSDKORW.js +0 -4698
  122. package/dist/chunk-U5QHYVMJ.js +0 -3341
  123. package/dist/chunk-UAP5CTHB.js +0 -5985
  124. package/dist/chunk-UK6SEUWU.js +0 -3210
  125. package/dist/chunk-UKU5YO65.js +0 -5132
  126. package/dist/chunk-UOZQXP4Q.js +0 -5144
  127. package/dist/chunk-UPTN2TSS.js +0 -4727
  128. package/dist/chunk-UQT2APOE.js +0 -2944
  129. package/dist/chunk-V32QDZKW.js +0 -5132
  130. package/dist/chunk-VDK4XPAC.js +0 -6318
  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-XHYHRJMK.js +0 -6319
  138. package/dist/chunk-XRHJLL74.js +0 -4893
  139. package/dist/chunk-XXWXEBJQ.js +0 -4885
  140. package/dist/chunk-YC6TH2H3.js +0 -5624
  141. package/dist/chunk-YDH6HCUJ.js +0 -5624
  142. package/dist/chunk-YJD35VKQ.js +0 -4890
  143. package/dist/chunk-YTZ5MZLP.js +0 -6318
  144. package/dist/chunk-ZBIQJBY7.js +0 -5620
  145. package/dist/chunk-ZKTSA2AE.js +0 -5629
  146. package/dist/chunk-ZKZZL3PE.js +0 -3379
  147. package/dist/chunk-ZM5KCPRK.js +0 -4541
  148. package/dist/chunk-ZTYPDSE3.js +0 -3258
@@ -1,4834 +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;
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;
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
- recordEquity() {
1660
- const equity = this.getEquity();
1661
- this.equityCurve.push({ timestamp: Date.now(), equity });
1662
- if (equity > this.peakEquity) this.peakEquity = equity;
1663
- const drawdown = (this.peakEquity - equity) / this.peakEquity;
1664
- if (drawdown > this.maxDrawdown) this.maxDrawdown = drawdown;
1665
- }
1666
- getEquity() {
1667
- let positionValue = 0;
1668
- for (const [, pos] of this.positions) {
1669
- positionValue += pos.quantity * pos.avgPrice;
1670
- }
1671
- return this.cash + positionValue;
1672
- }
1673
- getCash() {
1674
- return this.cash;
1675
- }
1676
- getPositions() {
1677
- return new Map(this.positions);
1678
- }
1679
- getTrades() {
1680
- return [...this.trades];
1681
- }
1682
- getEquityCurve() {
1683
- return [...this.equityCurve];
1684
- }
1685
- getMetrics() {
1686
- const initialEquity = this.equityCurve[0]?.equity || 0;
1687
- const currentEquity = this.getEquity();
1688
- const totalReturn = initialEquity > 0 ? (currentEquity - initialEquity) / initialEquity : 0;
1689
- const dailyReturns = this.calculateDailyReturns();
1690
- const sharpeRatio = this.calculateSharpe(dailyReturns);
1691
- let wins = 0;
1692
- let losses = 0;
1693
- let grossProfit = 0;
1694
- let grossLoss = 0;
1695
- const sellTrades = this.trades.filter((t) => t.side === "sell");
1696
- for (const sell of sellTrades) {
1697
- const buyTrades = this.trades.filter((t) => t.side === "buy" && t.symbol === sell.symbol);
1698
- const avgEntry = buyTrades.reduce((sum, t) => sum + t.entryPrice, 0) / (buyTrades.length || 1);
1699
- const pnl = (sell.entryPrice - avgEntry) * sell.size - sell.fee;
1700
- if (pnl > 0) {
1701
- wins++;
1702
- grossProfit += pnl;
1703
- } else {
1704
- losses++;
1705
- grossLoss += Math.abs(pnl);
1706
- }
1707
- }
1708
- return {
1709
- totalReturn,
1710
- sharpeRatio,
1711
- maxDrawdown: this.maxDrawdown,
1712
- winRate: wins + losses > 0 ? wins / (wins + losses) : 0,
1713
- profitFactor: grossLoss > 0 ? grossProfit / grossLoss : grossProfit > 0 ? Infinity : 0,
1714
- totalTrades: this.trades.length
1715
- };
1716
- }
1717
- calculateDailyReturns() {
1718
- if (this.equityCurve.length < 2) return [];
1719
- const dailyEquity = /* @__PURE__ */ new Map();
1720
- for (const point of this.equityCurve) {
1721
- const date = new Date(point.timestamp).toISOString().slice(0, 10);
1722
- dailyEquity.set(date, point.equity);
1723
- }
1724
- const dates = Array.from(dailyEquity.keys()).sort();
1725
- const returns = [];
1726
- for (let i = 1; i < dates.length; i++) {
1727
- const prev = dailyEquity.get(dates[i - 1]);
1728
- const curr = dailyEquity.get(dates[i]);
1729
- if (prev > 0) returns.push((curr - prev) / prev);
1730
- }
1731
- return returns;
1732
- }
1733
- calculateSharpe(returns) {
1734
- if (returns.length < 2) return 0;
1735
- const mean = returns.reduce((a, b) => a + b, 0) / returns.length;
1736
- const variance = returns.reduce((sum, r) => sum + (r - mean) ** 2, 0) / (returns.length - 1);
1737
- const std = Math.sqrt(variance);
1738
- if (std === 0) return 0;
1739
- return mean / std * Math.sqrt(365);
1740
- }
1741
- };
1742
-
1743
- // src/perp/client.ts
1744
- var HyperliquidClient = class {
1745
- apiUrl;
1746
- meta = null;
1747
- assetIndexCache = /* @__PURE__ */ new Map();
1748
- constructor(config) {
1749
- this.apiUrl = config.apiUrl;
1750
- }
1751
- // ── INFO API (read-only) ───────────────────────────────────
1752
- async getMeta() {
1753
- if (this.meta) return this.meta;
1754
- const resp = await this.infoRequest({ type: "meta" });
1755
- this.meta = resp.universe;
1756
- this.meta.forEach((asset, idx) => {
1757
- this.assetIndexCache.set(asset.name, idx);
1758
- });
1759
- return this.meta;
1760
- }
1761
- async getAssetIndex(coin) {
1762
- if (this.assetIndexCache.has(coin)) return this.assetIndexCache.get(coin);
1763
- await this.getMeta();
1764
- const idx = this.assetIndexCache.get(coin);
1765
- if (idx === void 0) throw new Error(`Unknown instrument: ${coin}`);
1766
- return idx;
1767
- }
1768
- /** Get the size decimal precision for an instrument (for order size rounding) */
1769
- async getSzDecimals(coin) {
1770
- const meta = await this.getMeta();
1771
- const asset = meta.find((a) => a.name === coin);
1772
- if (!asset) throw new Error(`Unknown instrument: ${coin}`);
1773
- return asset.szDecimals;
1774
- }
1775
- async getAllMids() {
1776
- return this.infoRequest({ type: "allMids" });
1777
- }
1778
- async getClearinghouseState(user) {
1779
- return this.infoRequest({ type: "clearinghouseState", user });
1780
- }
1781
- async getUserFills(user, startTime) {
1782
- return this.infoRequest({
1783
- type: "userFills",
1784
- user,
1785
- ...startTime !== void 0 && { startTime }
1786
- });
1787
- }
1788
- async getUserFillsByTime(user, startTime, endTime) {
1789
- return this.infoRequest({
1790
- type: "userFillsByTime",
1791
- user,
1792
- startTime,
1793
- ...endTime !== void 0 && { endTime }
1794
- });
1795
- }
1796
- async getOpenOrders(user) {
1797
- return this.infoRequest({ type: "openOrders", user });
1798
- }
1799
- async getL2Book(coin, depth) {
1800
- return this.infoRequest({
1801
- type: "l2Book",
1802
- coin,
1803
- ...depth !== void 0 && { nSigFigs: depth }
1804
- });
1805
- }
1806
- // ── HIGH-LEVEL HELPERS ─────────────────────────────────────
1807
- async getPositions(user) {
1808
- const state = await this.getClearinghouseState(user);
1809
- return state.assetPositions.filter((p) => parseFloat(p.position.szi) !== 0).map((p) => this.parsePosition(p));
1810
- }
1811
- async getAccountSummary(user) {
1812
- const state = await this.getClearinghouseState(user);
1813
- const cms = state.crossMarginSummary;
1814
- const totalEquity = parseFloat(cms.accountValue);
1815
- const totalNotional = parseFloat(cms.totalNtlPos);
1816
- const totalMarginUsed = parseFloat(cms.totalMarginUsed);
1817
- return {
1818
- totalEquity,
1819
- availableMargin: totalEquity - totalMarginUsed,
1820
- totalMarginUsed,
1821
- totalUnrealizedPnl: parseFloat(cms.totalRawUsd) - totalEquity,
1822
- totalNotional,
1823
- maintenanceMargin: totalMarginUsed * 0.5,
1824
- effectiveLeverage: totalEquity > 0 ? totalNotional / totalEquity : 0,
1825
- cashBalance: parseFloat(cms.accountValue) - state.assetPositions.reduce(
1826
- (sum, p) => sum + parseFloat(p.position.unrealizedPnl),
1827
- 0
1828
- )
1829
- };
1830
- }
1831
- async getMarketData(instruments) {
1832
- const mids = await this.getAllMids();
1833
- return instruments.filter((inst) => mids[inst] !== void 0).map((inst) => ({
1834
- instrument: inst,
1835
- midPrice: parseFloat(mids[inst]),
1836
- bestBid: parseFloat(mids[inst]),
1837
- bestAsk: parseFloat(mids[inst]),
1838
- funding8h: 0,
1839
- openInterest: 0,
1840
- volume24h: 0,
1841
- priceChange24h: 0
1842
- }));
1843
- }
1844
- parseFill(fill) {
1845
- return {
1846
- oid: fill.oid,
1847
- coin: fill.coin,
1848
- side: fill.side,
1849
- px: fill.px,
1850
- sz: fill.sz,
1851
- fee: fill.fee,
1852
- time: fill.time,
1853
- hash: fill.hash,
1854
- isMaker: fill.startPosition !== fill.px,
1855
- builderFee: fill.builderFee,
1856
- liquidation: fill.liquidation
1857
- };
1858
- }
1859
- // ── PRIVATE ────────────────────────────────────────────────
1860
- parsePosition(ap) {
1861
- const pos = ap.position;
1862
- const size = parseFloat(pos.szi);
1863
- const entryPrice = parseFloat(pos.entryPx || "0");
1864
- const markPrice = parseFloat(pos.positionValue || "0") / Math.abs(size || 1);
1865
- return {
1866
- instrument: pos.coin,
1867
- assetIndex: this.assetIndexCache.get(pos.coin) ?? -1,
1868
- size,
1869
- entryPrice,
1870
- markPrice,
1871
- unrealizedPnl: parseFloat(pos.unrealizedPnl),
1872
- leverage: parseFloat(pos.leverage?.value || "1"),
1873
- marginType: pos.leverage?.type === "isolated" ? "isolated" : "cross",
1874
- liquidationPrice: parseFloat(pos.liquidationPx || "0"),
1875
- notionalUSD: Math.abs(size) * markPrice,
1876
- marginUsed: parseFloat(pos.marginUsed)
1877
- };
1878
- }
1879
- async infoRequest(body) {
1880
- const resp = await fetch(`${this.apiUrl}/info`, {
1881
- method: "POST",
1882
- headers: { "Content-Type": "application/json" },
1883
- body: JSON.stringify(body)
1884
- });
1885
- if (!resp.ok) {
1886
- throw new Error(`Hyperliquid Info API error: ${resp.status} ${await resp.text()}`);
1887
- }
1888
- return resp.json();
1889
- }
1890
- };
1891
-
1892
- // src/perp/signer.ts
1893
- import { keccak256 } from "viem";
1894
-
1895
- // src/perp/msgpack.ts
1896
- var FOUR_BITS = 16;
1897
- var FIVE_BITS = 32;
1898
- var SEVEN_BITS = 128;
1899
- var EIGHT_BITS = 256;
1900
- var FIFTEEN_BITS = 32768;
1901
- var SIXTEEN_BITS = 65536;
1902
- var THIRTY_ONE_BITS = 2147483648;
1903
- var THIRTY_TWO_BITS = 4294967296;
1904
- var SIXTY_THREE_BITS = 9223372036854775808n;
1905
- var SIXTY_FOUR_BITS = 18446744073709551616n;
1906
- var textEncoder = new TextEncoder();
1907
- function encodeMsgpack(object) {
1908
- const byteParts = [];
1909
- encodeSlice(object, byteParts);
1910
- return concatBytes(...byteParts);
1911
- }
1912
- function concatBytes(...arrays) {
1913
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
1914
- const result = new Uint8Array(totalLength);
1915
- let offset = 0;
1916
- for (const arr of arrays) {
1917
- result.set(arr, offset);
1918
- offset += arr.length;
1919
- }
1920
- return result;
1921
- }
1922
- function encodeFloat64(num) {
1923
- const dataView = new DataView(new ArrayBuffer(9));
1924
- dataView.setFloat64(1, num);
1925
- dataView.setUint8(0, 203);
1926
- return new Uint8Array(dataView.buffer);
1927
- }
1928
- function encodeNumber(num) {
1929
- if (!Number.isInteger(num)) return encodeFloat64(num);
1930
- if (num < 0) {
1931
- if (num >= -FIVE_BITS) return new Uint8Array([num & 255]);
1932
- if (num >= -SEVEN_BITS) return new Uint8Array([208, num & 255]);
1933
- if (num >= -FIFTEEN_BITS) {
1934
- const dv = new DataView(new ArrayBuffer(3));
1935
- dv.setInt16(1, num);
1936
- dv.setUint8(0, 209);
1937
- return new Uint8Array(dv.buffer);
1938
- }
1939
- if (num >= -THIRTY_ONE_BITS) {
1940
- const dv = new DataView(new ArrayBuffer(5));
1941
- dv.setInt32(1, num);
1942
- dv.setUint8(0, 210);
1943
- return new Uint8Array(dv.buffer);
1944
- }
1945
- return encodeFloat64(num);
1946
- }
1947
- if (num <= 127) return new Uint8Array([num]);
1948
- if (num < EIGHT_BITS) return new Uint8Array([204, num]);
1949
- if (num < SIXTEEN_BITS) {
1950
- const dv = new DataView(new ArrayBuffer(3));
1951
- dv.setUint16(1, num);
1952
- dv.setUint8(0, 205);
1953
- return new Uint8Array(dv.buffer);
1954
- }
1955
- if (num < THIRTY_TWO_BITS) {
1956
- const dv = new DataView(new ArrayBuffer(5));
1957
- dv.setUint32(1, num);
1958
- dv.setUint8(0, 206);
1959
- return new Uint8Array(dv.buffer);
1960
- }
1961
- return encodeFloat64(num);
1962
- }
1963
- function encodeSlice(object, byteParts) {
1964
- if (object === null) {
1965
- byteParts.push(new Uint8Array([192]));
1966
- return;
1967
- }
1968
- if (object === false) {
1969
- byteParts.push(new Uint8Array([194]));
1970
- return;
1971
- }
1972
- if (object === true) {
1973
- byteParts.push(new Uint8Array([195]));
1974
- return;
1975
- }
1976
- if (typeof object === "number") {
1977
- byteParts.push(encodeNumber(object));
1978
- return;
1979
- }
1980
- if (typeof object === "bigint") {
1981
- if (object < 0) {
1982
- if (object < -SIXTY_THREE_BITS)
1983
- throw new Error("Cannot safely encode bigint larger than 64 bits");
1984
- const dv2 = new DataView(new ArrayBuffer(9));
1985
- dv2.setBigInt64(1, object);
1986
- dv2.setUint8(0, 211);
1987
- byteParts.push(new Uint8Array(dv2.buffer));
1988
- return;
1989
- }
1990
- if (object >= SIXTY_FOUR_BITS)
1991
- throw new Error("Cannot safely encode bigint larger than 64 bits");
1992
- const dv = new DataView(new ArrayBuffer(9));
1993
- dv.setBigUint64(1, object);
1994
- dv.setUint8(0, 207);
1995
- byteParts.push(new Uint8Array(dv.buffer));
1996
- return;
1997
- }
1998
- if (typeof object === "string") {
1999
- const encoded = textEncoder.encode(object);
2000
- const len = encoded.length;
2001
- if (len < FIVE_BITS) byteParts.push(new Uint8Array([160 | len]));
2002
- else if (len < EIGHT_BITS) byteParts.push(new Uint8Array([217, len]));
2003
- else if (len < SIXTEEN_BITS) {
2004
- const dv = new DataView(new ArrayBuffer(3));
2005
- dv.setUint16(1, len);
2006
- dv.setUint8(0, 218);
2007
- byteParts.push(new Uint8Array(dv.buffer));
2008
- } else if (len < THIRTY_TWO_BITS) {
2009
- const dv = new DataView(new ArrayBuffer(5));
2010
- dv.setUint32(1, len);
2011
- dv.setUint8(0, 219);
2012
- byteParts.push(new Uint8Array(dv.buffer));
2013
- } else {
2014
- throw new Error("Cannot safely encode string with size larger than 32 bits");
2015
- }
2016
- byteParts.push(encoded);
2017
- return;
2018
- }
2019
- if (object instanceof Uint8Array) {
2020
- if (object.length < EIGHT_BITS) {
2021
- byteParts.push(new Uint8Array([196, object.length]));
2022
- } else if (object.length < SIXTEEN_BITS) {
2023
- const dv = new DataView(new ArrayBuffer(3));
2024
- dv.setUint16(1, object.length);
2025
- dv.setUint8(0, 197);
2026
- byteParts.push(new Uint8Array(dv.buffer));
2027
- } else if (object.length < THIRTY_TWO_BITS) {
2028
- const dv = new DataView(new ArrayBuffer(5));
2029
- dv.setUint32(1, object.length);
2030
- dv.setUint8(0, 198);
2031
- byteParts.push(new Uint8Array(dv.buffer));
2032
- } else {
2033
- throw new Error("Cannot safely encode Uint8Array with size larger than 32 bits");
2034
- }
2035
- byteParts.push(object);
2036
- return;
2037
- }
2038
- if (Array.isArray(object)) {
2039
- if (object.length < FOUR_BITS) byteParts.push(new Uint8Array([144 | object.length]));
2040
- else if (object.length < SIXTEEN_BITS) {
2041
- const dv = new DataView(new ArrayBuffer(3));
2042
- dv.setUint16(1, object.length);
2043
- dv.setUint8(0, 220);
2044
- byteParts.push(new Uint8Array(dv.buffer));
2045
- } else if (object.length < THIRTY_TWO_BITS) {
2046
- const dv = new DataView(new ArrayBuffer(5));
2047
- dv.setUint32(1, object.length);
2048
- dv.setUint8(0, 221);
2049
- byteParts.push(new Uint8Array(dv.buffer));
2050
- } else {
2051
- throw new Error("Cannot safely encode array with size larger than 32 bits");
2052
- }
2053
- for (const obj of object) encodeSlice(obj, byteParts);
2054
- return;
2055
- }
2056
- if (typeof object === "object") {
2057
- const entries = Object.entries(object);
2058
- const numKeys = entries.length;
2059
- if (numKeys < FOUR_BITS) byteParts.push(new Uint8Array([128 | numKeys]));
2060
- else if (numKeys < SIXTEEN_BITS) {
2061
- const dv = new DataView(new ArrayBuffer(3));
2062
- dv.setUint16(1, numKeys);
2063
- dv.setUint8(0, 222);
2064
- byteParts.push(new Uint8Array(dv.buffer));
2065
- } else if (numKeys < THIRTY_TWO_BITS) {
2066
- const dv = new DataView(new ArrayBuffer(5));
2067
- dv.setUint32(1, numKeys);
2068
- dv.setUint8(0, 223);
2069
- byteParts.push(new Uint8Array(dv.buffer));
2070
- } else {
2071
- throw new Error("Cannot safely encode map with size larger than 32 bits");
2072
- }
2073
- for (const [key, value] of entries) {
2074
- encodeSlice(key, byteParts);
2075
- encodeSlice(value, byteParts);
2076
- }
2077
- return;
2078
- }
2079
- throw new Error("Cannot safely encode value into messagepack");
2080
- }
2081
- function largeIntToBigInt(obj) {
2082
- if (typeof obj === "number" && Number.isInteger(obj) && (obj >= 4294967296 || obj < -2147483648)) {
2083
- return BigInt(obj);
2084
- }
2085
- if (Array.isArray(obj)) return obj.map(largeIntToBigInt);
2086
- if (typeof obj === "object" && obj !== null && !(obj instanceof Uint8Array)) {
2087
- const result = {};
2088
- for (const key in obj) {
2089
- result[key] = largeIntToBigInt(obj[key]);
2090
- }
2091
- return result;
2092
- }
2093
- return obj;
2094
- }
2095
- function removeUndefinedKeys(obj) {
2096
- if (Array.isArray(obj)) return obj.map(removeUndefinedKeys);
2097
- if (typeof obj === "object" && obj !== null && !(obj instanceof Uint8Array)) {
2098
- const result = {};
2099
- for (const key in obj) {
2100
- const val = obj[key];
2101
- if (val !== void 0) {
2102
- result[key] = removeUndefinedKeys(val);
2103
- }
2104
- }
2105
- return result;
2106
- }
2107
- return obj;
2108
- }
2109
- function toUint64Bytes(n) {
2110
- const bytes = new Uint8Array(8);
2111
- new DataView(bytes.buffer).setBigUint64(0, BigInt(n));
2112
- return bytes;
2113
- }
2114
-
2115
- // src/perp/signer.ts
2116
- var HYPERLIQUID_DOMAIN = {
2117
- name: "Exchange",
2118
- version: "1",
2119
- chainId: 1337,
2120
- verifyingContract: "0x0000000000000000000000000000000000000000"
2121
- };
2122
- var HYPERLIQUID_USER_DOMAIN = {
2123
- name: "HyperliquidSignTransaction",
2124
- version: "1",
2125
- chainId: 42161,
2126
- verifyingContract: "0x0000000000000000000000000000000000000000"
2127
- };
2128
- var USER_ACTION_TYPES = {
2129
- withdraw: {
2130
- "HyperliquidTransaction:Withdraw": [
2131
- { name: "hyperliquidChain", type: "string" },
2132
- { name: "destination", type: "string" },
2133
- { name: "amount", type: "string" },
2134
- { name: "time", type: "uint64" }
2135
- ]
2136
- },
2137
- usdSend: {
2138
- "HyperliquidTransaction:UsdSend": [
2139
- { name: "hyperliquidChain", type: "string" },
2140
- { name: "destination", type: "string" },
2141
- { name: "amount", type: "string" },
2142
- { name: "time", type: "uint64" }
2143
- ]
2144
- }
2145
- };
2146
- var PHANTOM_AGENT_TYPES = {
2147
- Agent: [
2148
- { name: "source", type: "string" },
2149
- { name: "connectionId", type: "bytes32" }
2150
- ]
2151
- };
2152
- var lastNonce = 0n;
2153
- function getNextNonce() {
2154
- const now = BigInt(Date.now());
2155
- if (now <= lastNonce) {
2156
- lastNonce = lastNonce + 1n;
2157
- } else {
2158
- lastNonce = now;
2159
- }
2160
- return lastNonce;
2161
- }
2162
- function createL1ActionHash(args) {
2163
- const { action, nonce, vaultAddress } = args;
2164
- const cleaned = removeUndefinedKeys(action);
2165
- const withBigInts = largeIntToBigInt(cleaned);
2166
- const actionBytes = encodeMsgpack(withBigInts);
2167
- const nonceBytes = toUint64Bytes(nonce);
2168
- const vaultMarker = vaultAddress ? new Uint8Array([1]) : new Uint8Array([0]);
2169
- const vaultBytes = vaultAddress ? hexToBytes(vaultAddress.slice(2)) : new Uint8Array();
2170
- const bytes = concatBytes2(actionBytes, nonceBytes, vaultMarker, vaultBytes);
2171
- return keccak256(bytes);
2172
- }
2173
- var HyperliquidSigner = class {
2174
- constructor(walletClient, isTestnet = false) {
2175
- this.walletClient = walletClient;
2176
- this.isTestnet = isTestnet;
2177
- }
2178
- isTestnet;
2179
- /**
2180
- * Sign an L1 action (order, cancel, updateLeverage, etc.)
2181
- * using the phantom agent pattern.
2182
- */
2183
- async signAction(action, nonce, vaultAddress) {
2184
- const actionNonce = nonce ?? getNextNonce();
2185
- const nonceNumber = Number(actionNonce);
2186
- const account = this.walletClient.account;
2187
- if (!account) throw new Error("Wallet client has no account");
2188
- const connectionId = createL1ActionHash({
2189
- action,
2190
- nonce: nonceNumber,
2191
- vaultAddress
2192
- });
2193
- const signature = await this.walletClient.signTypedData({
2194
- account,
2195
- domain: HYPERLIQUID_DOMAIN,
2196
- types: PHANTOM_AGENT_TYPES,
2197
- primaryType: "Agent",
2198
- message: {
2199
- source: this.isTestnet ? "b" : "a",
2200
- connectionId
2201
- }
2202
- });
2203
- return { signature, nonce: actionNonce };
2204
- }
2205
- /**
2206
- * Sign a user-signed action (withdraw3, usdSend, approveAgent, etc.)
2207
- * using the HyperliquidSignTransaction domain (chainId 42161).
2208
- *
2209
- * Unlike trading actions, these use direct EIP-712 typed data signing
2210
- * with action-specific types — NOT the phantom agent pattern.
2211
- */
2212
- async signUserAction(actionType, message) {
2213
- const account = this.walletClient.account;
2214
- if (!account) throw new Error("Wallet client has no account");
2215
- const types = USER_ACTION_TYPES[actionType];
2216
- const primaryType = Object.keys(types)[0];
2217
- const signature = await this.walletClient.signTypedData({
2218
- account,
2219
- domain: HYPERLIQUID_USER_DOMAIN,
2220
- types,
2221
- primaryType,
2222
- message
2223
- });
2224
- return { signature };
2225
- }
2226
- /**
2227
- * Build and sign a withdraw3 action for withdrawing USDC from Hyperliquid to Arbitrum.
2228
- * Returns the complete payload ready to POST to /exchange.
2229
- *
2230
- * @param destination — The Arbitrum address to receive USDC
2231
- * @param amount — Amount as string (e.g., "10.0" for $10)
2232
- */
2233
- async signWithdraw(destination, amount) {
2234
- const timestamp = Date.now();
2235
- const message = {
2236
- hyperliquidChain: this.isTestnet ? "Testnet" : "Mainnet",
2237
- destination,
2238
- amount,
2239
- time: BigInt(timestamp)
2240
- };
2241
- const { signature } = await this.signUserAction("withdraw", message);
2242
- const action = {
2243
- type: "withdraw3",
2244
- hyperliquidChain: this.isTestnet ? "Testnet" : "Mainnet",
2245
- signatureChainId: "0xa4b1",
2246
- // Arbitrum chainId in hex
2247
- destination,
2248
- amount,
2249
- time: timestamp
2250
- };
2251
- return {
2252
- action,
2253
- signature: {
2254
- r: signature.slice(0, 66),
2255
- s: `0x${signature.slice(66, 130)}`,
2256
- v: parseInt(signature.slice(130, 132), 16)
2257
- },
2258
- nonce: timestamp
2259
- };
2260
- }
2261
- getAddress() {
2262
- const account = this.walletClient.account;
2263
- if (!account) throw new Error("Wallet client has no account");
2264
- return account.address;
2265
- }
2266
- };
2267
- function hexToBytes(hex) {
2268
- const bytes = new Uint8Array(hex.length / 2);
2269
- for (let i = 0; i < bytes.length; i++) {
2270
- bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
2271
- }
2272
- return bytes;
2273
- }
2274
- function concatBytes2(...arrays) {
2275
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
2276
- const result = new Uint8Array(totalLength);
2277
- let offset = 0;
2278
- for (const arr of arrays) {
2279
- result.set(arr, offset);
2280
- offset += arr.length;
2281
- }
2282
- return result;
2283
- }
2284
-
2285
- // src/perp/orders.ts
2286
- var HyperliquidOrderManager = class {
2287
- client;
2288
- signer;
2289
- config;
2290
- constructor(client, signer, config) {
2291
- this.client = client;
2292
- this.signer = signer;
2293
- this.config = config;
2294
- }
2295
- async placeOrder(signal) {
2296
- try {
2297
- if (!signal.reduceOnly) {
2298
- const notionalUSD = signal.size * signal.price;
2299
- if (notionalUSD > this.config.maxNotionalUSD) {
2300
- const msg = `Notional $${notionalUSD.toFixed(0)} exceeds max $${this.config.maxNotionalUSD} for ${signal.instrument}`;
2301
- console.warn(`[perp] Order rejected: ${msg}`);
2302
- return { success: false, status: "error", error: msg };
2303
- }
2304
- if (signal.leverage > this.config.maxLeverage) {
2305
- const msg = `Leverage ${signal.leverage}x exceeds max ${this.config.maxLeverage}x for ${signal.instrument}`;
2306
- console.warn(`[perp] Order rejected: ${msg}`);
2307
- return { success: false, status: "error", error: msg };
2308
- }
2309
- }
2310
- const assetIndex = await this.client.getAssetIndex(signal.instrument);
2311
- const isBuy = signal.action === "open_long" || signal.action === "close_short";
2312
- const szDecimals = await this.client.getSzDecimals(signal.instrument);
2313
- const factor = 10 ** szDecimals;
2314
- const roundedSize = Math.floor(signal.size * factor) / factor;
2315
- if (roundedSize <= 0) {
2316
- const msg = `Size ${signal.size} rounds to 0 at ${szDecimals} decimal places for ${signal.instrument}`;
2317
- console.warn(`[perp] Order rejected: ${msg}`);
2318
- return { success: false, status: "error", error: msg };
2319
- }
2320
- const orderWire = {
2321
- a: assetIndex,
2322
- b: isBuy,
2323
- p: signal.orderType === "market" ? this.getMarketPrice(signal) : signal.price.toString(),
2324
- s: roundedSize.toString(),
2325
- r: signal.reduceOnly,
2326
- t: signal.orderType === "market" ? { limit: { tif: "Ioc" } } : { limit: { tif: "Gtc" } }
2327
- };
2328
- const action = {
2329
- type: "order",
2330
- orders: [orderWire],
2331
- grouping: "na"
2332
- };
2333
- const nonce = getNextNonce();
2334
- const { signature } = await this.signer.signAction(action, nonce);
2335
- const resp = await this.exchangeRequest({
2336
- action,
2337
- nonce: Number(nonce),
2338
- signature: {
2339
- r: signature.slice(0, 66),
2340
- s: `0x${signature.slice(66, 130)}`,
2341
- v: parseInt(signature.slice(130, 132), 16)
2342
- },
2343
- vaultAddress: null
2344
- });
2345
- return this.parseOrderResponse(resp);
2346
- } catch (error) {
2347
- const message = error instanceof Error ? error.message : String(error);
2348
- console.error(`[perp] Order failed for ${signal.instrument}:`, message);
2349
- return { success: false, status: "error", error: message };
2350
- }
2351
- }
2352
- async cancelOrder(instrument, orderId) {
2353
- try {
2354
- const assetIndex = await this.client.getAssetIndex(instrument);
2355
- const action = {
2356
- type: "cancel",
2357
- cancels: [{ a: assetIndex, o: orderId }]
2358
- };
2359
- const nonce = getNextNonce();
2360
- const { signature } = await this.signer.signAction(action, nonce);
2361
- await this.exchangeRequest({
2362
- action,
2363
- nonce: Number(nonce),
2364
- signature: {
2365
- r: signature.slice(0, 66),
2366
- s: `0x${signature.slice(66, 130)}`,
2367
- v: parseInt(signature.slice(130, 132), 16)
2368
- },
2369
- vaultAddress: null
2370
- });
2371
- console.log(`[perp] Cancelled order ${orderId} for ${instrument}`);
2372
- return true;
2373
- } catch (error) {
2374
- const message = error instanceof Error ? error.message : String(error);
2375
- console.error(`[perp] Cancel failed for order ${orderId}:`, message);
2376
- return false;
2377
- }
2378
- }
2379
- async closePosition(instrument, positionSize) {
2380
- const isLong = positionSize > 0;
2381
- return this.placeOrder({
2382
- action: isLong ? "close_long" : "close_short",
2383
- instrument,
2384
- size: Math.abs(positionSize),
2385
- price: 0,
2386
- leverage: 1,
2387
- orderType: "market",
2388
- reduceOnly: true,
2389
- confidence: 1,
2390
- reasoning: "Position close"
2391
- });
2392
- }
2393
- async updateLeverage(instrument, leverage, isCross = true) {
2394
- try {
2395
- const assetIndex = await this.client.getAssetIndex(instrument);
2396
- const action = {
2397
- type: "updateLeverage",
2398
- asset: assetIndex,
2399
- isCross,
2400
- leverage
2401
- };
2402
- const nonce = getNextNonce();
2403
- const { signature } = await this.signer.signAction(action, nonce);
2404
- await this.exchangeRequest({
2405
- action,
2406
- nonce: Number(nonce),
2407
- signature: {
2408
- r: signature.slice(0, 66),
2409
- s: `0x${signature.slice(66, 130)}`,
2410
- v: parseInt(signature.slice(130, 132), 16)
2411
- },
2412
- vaultAddress: null
2413
- });
2414
- console.log(`[perp] Leverage set for ${instrument}: ${leverage}x (${isCross ? "cross" : "isolated"})`);
2415
- return true;
2416
- } catch (error) {
2417
- const message = error instanceof Error ? error.message : String(error);
2418
- console.error(`[perp] Leverage update failed for ${instrument}:`, message);
2419
- return false;
2420
- }
2421
- }
2422
- // ── PRIVATE ────────────────────────────────────────────────
2423
- getMarketPrice(signal) {
2424
- const isBuy = signal.action === "open_long" || signal.action === "close_short";
2425
- if (signal.price > 0) {
2426
- const slippage = isBuy ? 1.005 : 0.995;
2427
- return (signal.price * slippage).toString();
2428
- }
2429
- return "0";
2430
- }
2431
- parseOrderResponse(resp) {
2432
- if (resp?.status === "ok" && resp?.response?.type === "order") {
2433
- const statuses = resp.response.data?.statuses || [];
2434
- if (statuses.length > 0) {
2435
- const status = statuses[0];
2436
- if (status.filled) {
2437
- return {
2438
- success: true,
2439
- orderId: status.filled.oid,
2440
- status: "filled",
2441
- avgPrice: status.filled.avgPx,
2442
- filledSize: status.filled.totalSz
2443
- };
2444
- }
2445
- if (status.resting) {
2446
- return {
2447
- success: true,
2448
- orderId: status.resting.oid,
2449
- status: "resting"
2450
- };
2451
- }
2452
- if (status.error) {
2453
- return { success: false, status: "error", error: status.error };
2454
- }
2455
- }
2456
- }
2457
- return {
2458
- success: false,
2459
- status: "error",
2460
- error: `Unexpected response: ${JSON.stringify(resp)}`
2461
- };
2462
- }
2463
- async exchangeRequest(body) {
2464
- const resp = await fetch(`${this.config.apiUrl}/exchange`, {
2465
- method: "POST",
2466
- headers: { "Content-Type": "application/json" },
2467
- body: JSON.stringify(body)
2468
- });
2469
- if (!resp.ok) {
2470
- throw new Error(`Hyperliquid Exchange API error: ${resp.status} ${await resp.text()}`);
2471
- }
2472
- return resp.json();
2473
- }
2474
- };
2475
-
2476
- // src/perp/positions.ts
2477
- var HyperliquidPositionManager = class {
2478
- client;
2479
- userAddress;
2480
- cachedPositions = [];
2481
- cachedAccount = null;
2482
- lastRefreshAt = 0;
2483
- cacheTtlMs = 5e3;
2484
- constructor(client, userAddress) {
2485
- this.client = client;
2486
- this.userAddress = userAddress;
2487
- }
2488
- // ── POSITION QUERIES ───────────────────────────────────────
2489
- async getPositions(forceRefresh = false) {
2490
- if (!forceRefresh && this.isCacheFresh()) return this.cachedPositions;
2491
- await this.refresh();
2492
- return this.cachedPositions;
2493
- }
2494
- async getPosition(instrument) {
2495
- const positions = await this.getPositions();
2496
- return positions.find((p) => p.instrument === instrument) ?? null;
2497
- }
2498
- async getAccountSummary(forceRefresh = false) {
2499
- if (!forceRefresh && this.isCacheFresh() && this.cachedAccount) {
2500
- return this.cachedAccount;
2501
- }
2502
- await this.refresh();
2503
- return this.cachedAccount;
2504
- }
2505
- // ── LIQUIDATION MONITORING ─────────────────────────────────
2506
- async getLiquidationProximity() {
2507
- const positions = await this.getPositions();
2508
- const proximities = /* @__PURE__ */ new Map();
2509
- for (const pos of positions) {
2510
- if (pos.liquidationPrice <= 0 || pos.markPrice <= 0) {
2511
- proximities.set(pos.instrument, 0);
2512
- continue;
2513
- }
2514
- let proximity;
2515
- if (pos.size > 0) {
2516
- if (pos.markPrice <= pos.liquidationPrice) {
2517
- proximity = 1;
2518
- } else {
2519
- const distanceToLiq = pos.markPrice - pos.liquidationPrice;
2520
- const entryToLiq = pos.entryPrice - pos.liquidationPrice;
2521
- proximity = entryToLiq > 0 ? 1 - distanceToLiq / entryToLiq : 0;
2522
- }
2523
- } else {
2524
- if (pos.markPrice >= pos.liquidationPrice) {
2525
- proximity = 1;
2526
- } else {
2527
- const distanceToLiq = pos.liquidationPrice - pos.markPrice;
2528
- const entryToLiq = pos.liquidationPrice - pos.entryPrice;
2529
- proximity = entryToLiq > 0 ? 1 - distanceToLiq / entryToLiq : 0;
2530
- }
2531
- }
2532
- proximities.set(pos.instrument, Math.max(0, Math.min(1, proximity)));
2533
- }
2534
- return proximities;
2535
- }
2536
- async getDangerousPositions(threshold = 0.7) {
2537
- const positions = await this.getPositions();
2538
- const proximities = await this.getLiquidationProximity();
2539
- return positions.filter((p) => (proximities.get(p.instrument) ?? 0) > threshold);
2540
- }
2541
- // ── SUMMARY HELPERS ────────────────────────────────────────
2542
- async getTotalUnrealizedPnl() {
2543
- const positions = await this.getPositions();
2544
- return positions.reduce((sum, p) => sum + p.unrealizedPnl, 0);
2545
- }
2546
- async getTotalNotional() {
2547
- const positions = await this.getPositions();
2548
- return positions.reduce((sum, p) => sum + p.notionalUSD, 0);
2549
- }
2550
- async getPositionCount() {
2551
- return (await this.getPositions()).length;
2552
- }
2553
- // ── CACHE ──────────────────────────────────────────────────
2554
- async refresh() {
2555
- try {
2556
- const [positions, account] = await Promise.all([
2557
- this.client.getPositions(this.userAddress),
2558
- this.client.getAccountSummary(this.userAddress)
2559
- ]);
2560
- this.cachedPositions = positions;
2561
- this.cachedAccount = account;
2562
- this.lastRefreshAt = Date.now();
2563
- } catch (error) {
2564
- const message = error instanceof Error ? error.message : String(error);
2565
- console.error("[perp] Failed to refresh positions:", message);
2566
- }
2567
- }
2568
- isCacheFresh() {
2569
- return Date.now() - this.lastRefreshAt < this.cacheTtlMs;
2570
- }
2571
- };
2572
-
2573
- // src/perp/websocket.ts
2574
- import WebSocket2 from "ws";
2575
- var HyperliquidWebSocket = class {
2576
- wsUrl;
2577
- userAddress;
2578
- client;
2579
- ws = null;
2580
- reconnectAttempts = 0;
2581
- maxReconnectAttempts = 20;
2582
- baseReconnectMs = 1e3;
2583
- maxReconnectMs = 6e4;
2584
- reconnectTimer = null;
2585
- pingTimer = null;
2586
- isConnecting = false;
2587
- shouldReconnect = true;
2588
- lastProcessedFillTime = 0;
2589
- onFill = null;
2590
- onFunding = null;
2591
- onLiquidation = null;
2592
- constructor(config, userAddress, client) {
2593
- this.wsUrl = config.wsUrl;
2594
- this.userAddress = userAddress;
2595
- this.client = client;
2596
- }
2597
- // ── CONNECTION ─────────────────────────────────────────────
2598
- async connect() {
2599
- if (this.ws?.readyState === WebSocket2.OPEN || this.isConnecting) return;
2600
- this.isConnecting = true;
2601
- this.shouldReconnect = true;
2602
- return new Promise((resolve2, reject) => {
2603
- try {
2604
- this.ws = new WebSocket2(this.wsUrl);
2605
- this.ws.on("open", () => {
2606
- this.isConnecting = false;
2607
- this.reconnectAttempts = 0;
2608
- console.log("[perp-ws] Connected");
2609
- this.subscribe({
2610
- type: "subscribe",
2611
- subscription: { type: "userFills", user: this.userAddress }
2612
- });
2613
- this.subscribe({
2614
- type: "subscribe",
2615
- subscription: { type: "userFundings", user: this.userAddress }
2616
- });
2617
- this.startPing();
2618
- this.backfillMissedFills().catch((err) => {
2619
- console.warn("[perp-ws] Backfill failed:", err instanceof Error ? err.message : err);
2620
- });
2621
- resolve2();
2622
- });
2623
- this.ws.on("message", (data) => {
2624
- this.handleMessage(data);
2625
- });
2626
- this.ws.on("close", (code, reason) => {
2627
- this.isConnecting = false;
2628
- console.log(`[perp-ws] Closed: ${code} ${reason.toString()}`);
2629
- this.stopPing();
2630
- this.scheduleReconnect();
2631
- });
2632
- this.ws.on("error", (error) => {
2633
- this.isConnecting = false;
2634
- console.error("[perp-ws] Error:", error.message);
2635
- if (this.reconnectAttempts === 0) reject(error);
2636
- });
2637
- } catch (error) {
2638
- this.isConnecting = false;
2639
- reject(error);
2640
- }
2641
- });
2642
- }
2643
- disconnect() {
2644
- this.shouldReconnect = false;
2645
- if (this.reconnectTimer) {
2646
- clearTimeout(this.reconnectTimer);
2647
- this.reconnectTimer = null;
2648
- }
2649
- this.stopPing();
2650
- if (this.ws) {
2651
- this.ws.removeAllListeners();
2652
- if (this.ws.readyState === WebSocket2.OPEN) {
2653
- this.ws.close(1e3, "Client disconnect");
2654
- }
2655
- this.ws = null;
2656
- }
2657
- console.log("[perp-ws] Disconnected");
2658
- }
2659
- get isConnected() {
2660
- return this.ws?.readyState === WebSocket2.OPEN;
2661
- }
2662
- // ── EVENT HANDLERS ─────────────────────────────────────────
2663
- onFillReceived(callback) {
2664
- this.onFill = callback;
2665
- }
2666
- onFundingReceived(callback) {
2667
- this.onFunding = callback;
2668
- }
2669
- onLiquidationDetected(callback) {
2670
- this.onLiquidation = callback;
2671
- }
2672
- getLastProcessedFillTime() {
2673
- return this.lastProcessedFillTime;
2674
- }
2675
- // ── MESSAGE HANDLING ───────────────────────────────────────
2676
- handleMessage(data) {
2677
- try {
2678
- const msg = JSON.parse(data.toString());
2679
- if (msg.channel === "userFills") {
2680
- this.handleFillMessage(msg.data);
2681
- } else if (msg.channel === "userFundings") {
2682
- this.handleFundingMessage(msg.data);
2683
- }
2684
- } catch {
2685
- }
2686
- }
2687
- handleFillMessage(fills) {
2688
- if (!Array.isArray(fills) || !this.onFill) return;
2689
- for (const rawFill of fills) {
2690
- const fill = this.client.parseFill(rawFill);
2691
- if (fill.time > this.lastProcessedFillTime) {
2692
- this.lastProcessedFillTime = fill.time;
2693
- }
2694
- if (fill.liquidation && this.onLiquidation) {
2695
- this.onLiquidation(fill.coin, parseFloat(fill.sz));
2696
- }
2697
- this.onFill(fill);
2698
- }
2699
- }
2700
- handleFundingMessage(fundings) {
2701
- if (!Array.isArray(fundings) || !this.onFunding) return;
2702
- for (const funding of fundings) {
2703
- this.onFunding({
2704
- time: funding.time,
2705
- coin: funding.coin,
2706
- usdc: funding.usdc,
2707
- szi: funding.szi,
2708
- fundingRate: funding.fundingRate
2709
- });
2710
- }
2711
- }
2712
- // ── BACKFILL ───────────────────────────────────────────────
2713
- async backfillMissedFills() {
2714
- if (this.lastProcessedFillTime === 0 || !this.onFill) return;
2715
- console.log(`[perp-ws] Backfilling fills since ${new Date(this.lastProcessedFillTime).toISOString()}`);
2716
- const fills = await this.client.getUserFillsByTime(
2717
- this.userAddress,
2718
- this.lastProcessedFillTime + 1
2719
- );
2720
- if (fills.length > 0) {
2721
- console.log(`[perp-ws] Backfilled ${fills.length} missed fills`);
2722
- for (const rawFill of fills) {
2723
- const fill = this.client.parseFill(rawFill);
2724
- if (fill.time > this.lastProcessedFillTime) {
2725
- this.lastProcessedFillTime = fill.time;
2726
- }
2727
- if (fill.liquidation && this.onLiquidation) {
2728
- this.onLiquidation(fill.coin, parseFloat(fill.sz));
2729
- }
2730
- this.onFill(fill);
2731
- }
2732
- }
2733
- }
2734
- // ── RECONNECTION ───────────────────────────────────────────
2735
- scheduleReconnect() {
2736
- if (!this.shouldReconnect || this.reconnectAttempts >= this.maxReconnectAttempts) {
2737
- if (this.reconnectAttempts >= this.maxReconnectAttempts) {
2738
- console.error(`[perp-ws] Max reconnect attempts (${this.maxReconnectAttempts}) reached`);
2739
- }
2740
- return;
2741
- }
2742
- const delay = Math.min(
2743
- this.baseReconnectMs * Math.pow(2, this.reconnectAttempts),
2744
- this.maxReconnectMs
2745
- );
2746
- this.reconnectAttempts++;
2747
- console.log(`[perp-ws] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);
2748
- this.reconnectTimer = setTimeout(() => {
2749
- this.connect().catch((err) => {
2750
- console.error("[perp-ws] Reconnect failed:", err instanceof Error ? err.message : err);
2751
- });
2752
- }, delay);
2753
- }
2754
- // ── KEEPALIVE ──────────────────────────────────────────────
2755
- startPing() {
2756
- this.stopPing();
2757
- this.pingTimer = setInterval(() => {
2758
- if (this.ws?.readyState === WebSocket2.OPEN) {
2759
- this.ws.send(JSON.stringify({ method: "ping" }));
2760
- }
2761
- }, 25e3);
2762
- }
2763
- stopPing() {
2764
- if (this.pingTimer) {
2765
- clearInterval(this.pingTimer);
2766
- this.pingTimer = null;
2767
- }
2768
- }
2769
- // ── HELPERS ────────────────────────────────────────────────
2770
- subscribe(msg) {
2771
- if (this.ws?.readyState === WebSocket2.OPEN) {
2772
- this.ws.send(JSON.stringify(msg));
2773
- }
2774
- }
2775
- };
2776
-
2777
- // src/prediction/types.ts
2778
- var DEFAULT_PREDICTION_CONFIG = {
2779
- enabled: false,
2780
- clobApiUrl: "https://clob.polymarket.com",
2781
- gammaApiUrl: "https://gamma-api.polymarket.com",
2782
- maxNotionalUSD: 1e3,
2783
- maxTotalExposureUSD: 5e3
2784
- };
2785
- var POLYGON_CHAIN_ID = 137;
2786
- var PREDICTION_INSTRUMENT_PREFIX = "POLY:";
2787
- function encodePredictionInstrument(conditionId, outcomeIndex) {
2788
- return `${PREDICTION_INSTRUMENT_PREFIX}${conditionId}:${outcomeIndex}`;
2789
- }
2790
- function decodePredictionInstrument(instrument) {
2791
- if (!instrument.startsWith(PREDICTION_INSTRUMENT_PREFIX)) return null;
2792
- const parts = instrument.slice(PREDICTION_INSTRUMENT_PREFIX.length).split(":");
2793
- if (parts.length !== 2) return null;
2794
- return { conditionId: parts[0], outcomeIndex: parseInt(parts[1], 10) };
2795
- }
2796
-
2797
- // src/prediction/client.ts
2798
- import { ClobClient } from "@polymarket/clob-client";
2799
- import { Wallet } from "ethers";
2800
- var PolymarketClient = class {
2801
- config;
2802
- clobClient = null;
2803
- apiCreds = null;
2804
- signer;
2805
- walletAddress;
2806
- marketCache = /* @__PURE__ */ new Map();
2807
- CACHE_TTL_MS = 6e4;
2808
- constructor(privateKey, config) {
2809
- this.config = { ...DEFAULT_PREDICTION_CONFIG, ...config };
2810
- this.signer = new Wallet(privateKey);
2811
- this.walletAddress = this.signer.address;
2812
- }
2813
- // ── INITIALIZATION ─────────────────────────────────────────
2814
- async initialize() {
2815
- const initClient = new ClobClient(
2816
- this.config.clobApiUrl,
2817
- POLYGON_CHAIN_ID,
2818
- this.signer
2819
- );
2820
- this.apiCreds = await initClient.createOrDeriveApiKey();
2821
- this.clobClient = new ClobClient(
2822
- this.config.clobApiUrl,
2823
- POLYGON_CHAIN_ID,
2824
- this.signer,
2825
- this.apiCreds,
2826
- 0
2827
- );
2828
- console.log(`[prediction] CLOB initialized for ${this.walletAddress}`);
2829
- }
2830
- get isInitialized() {
2831
- return this.clobClient !== null && this.apiCreds !== null;
2832
- }
2833
- // ── CLOB API — ORDER BOOK & PRICES ─────────────────────────
2834
- async getOrderBook(tokenId) {
2835
- this.ensureInitialized();
2836
- const book = await this.clobClient.getOrderBook(tokenId);
2837
- return {
2838
- bids: (book.bids || []).map((b) => ({ price: parseFloat(b.price), size: parseFloat(b.size) })),
2839
- asks: (book.asks || []).map((a) => ({ price: parseFloat(a.price), size: parseFloat(a.size) }))
2840
- };
2841
- }
2842
- async getMidpointPrice(tokenId) {
2843
- const book = await this.getOrderBook(tokenId);
2844
- if (book.bids.length === 0 || book.asks.length === 0) return 0;
2845
- return (book.bids[0].price + book.asks[0].price) / 2;
2846
- }
2847
- async getLastTradePrice(tokenId) {
2848
- this.ensureInitialized();
2849
- const resp = await this.clobClient.getLastTradePrice(tokenId);
2850
- return parseFloat(resp?.price || "0");
2851
- }
2852
- // ── CLOB API — ORDERS ──────────────────────────────────────
2853
- async placeLimitOrder(params) {
2854
- this.ensureInitialized();
2855
- const order = await this.clobClient.createAndPostOrder({
2856
- tokenID: params.tokenId,
2857
- price: params.price,
2858
- side: params.side,
2859
- size: params.size
2860
- });
2861
- return {
2862
- orderId: order?.orderID || "",
2863
- success: !!order?.orderID
2864
- };
2865
- }
2866
- async placeMarketOrder(params) {
2867
- this.ensureInitialized();
2868
- const order = await this.clobClient.createMarketOrder({
2869
- tokenID: params.tokenId,
2870
- amount: params.amount,
2871
- side: params.side
2872
- });
2873
- const result = await this.clobClient.postOrder(order);
2874
- return {
2875
- orderId: result?.orderID || "",
2876
- success: !!result?.orderID
2877
- };
2878
- }
2879
- async cancelOrder(orderId) {
2880
- this.ensureInitialized();
2881
- try {
2882
- await this.clobClient.cancelOrder({ orderID: orderId });
2883
- return true;
2884
- } catch {
2885
- return false;
2886
- }
2887
- }
2888
- async cancelAllOrders() {
2889
- this.ensureInitialized();
2890
- try {
2891
- await this.clobClient.cancelAll();
2892
- return true;
2893
- } catch {
2894
- return false;
2895
- }
2896
- }
2897
- async getOpenOrders() {
2898
- this.ensureInitialized();
2899
- return this.clobClient.getOpenOrders();
2900
- }
2901
- async getTradeHistory() {
2902
- this.ensureInitialized();
2903
- const trades = await this.clobClient.getTrades();
2904
- return (trades || []).map((t) => this.parseRawFill(t));
2905
- }
2906
- // ── GAMMA API — MARKET DISCOVERY (public) ──────────────────
2907
- async getMarkets(params) {
2908
- const query = new URLSearchParams();
2909
- if (params?.limit) query.set("limit", String(params.limit));
2910
- if (params?.offset) query.set("offset", String(params.offset));
2911
- if (params?.active !== void 0) query.set("active", String(params.active));
2912
- if (params?.category) query.set("tag", params.category);
2913
- const url = `${this.config.gammaApiUrl}/markets?${query.toString()}`;
2914
- const resp = await fetch(url);
2915
- if (!resp.ok) throw new Error(`Gamma API error: ${resp.status} ${await resp.text()}`);
2916
- const raw = await resp.json();
2917
- return (raw || []).map((m) => this.parseGammaMarket(m));
2918
- }
2919
- async getMarketByConditionId(conditionId) {
2920
- const cached = this.marketCache.get(conditionId);
2921
- if (cached && Date.now() - cached.cachedAt < this.CACHE_TTL_MS) {
2922
- return cached.market;
2923
- }
2924
- const url = `${this.config.gammaApiUrl}/markets?condition_id=${conditionId}`;
2925
- const resp = await fetch(url);
2926
- if (!resp.ok) return null;
2927
- const raw = await resp.json();
2928
- if (!raw || raw.length === 0) return null;
2929
- const market = this.parseGammaMarket(raw[0]);
2930
- this.marketCache.set(conditionId, { market, cachedAt: Date.now() });
2931
- return market;
2932
- }
2933
- async searchMarkets(query, limit = 20) {
2934
- const url = `${this.config.gammaApiUrl}/markets?_q=${encodeURIComponent(query)}&limit=${limit}&active=true`;
2935
- const resp = await fetch(url);
2936
- if (!resp.ok) return [];
2937
- const raw = await resp.json();
2938
- return (raw || []).map((m) => this.parseGammaMarket(m));
2939
- }
2940
- async getTrendingMarkets(limit = 10) {
2941
- const url = `${this.config.gammaApiUrl}/markets?active=true&limit=${limit}&order=volume24hr&ascending=false`;
2942
- const resp = await fetch(url);
2943
- if (!resp.ok) return [];
2944
- const raw = await resp.json();
2945
- return (raw || []).map((m) => this.parseGammaMarket(m));
2946
- }
2947
- // ── WALLET ─────────────────────────────────────────────────
2948
- getWalletAddress() {
2949
- return this.walletAddress;
2950
- }
2951
- // ── PRIVATE ────────────────────────────────────────────────
2952
- ensureInitialized() {
2953
- if (!this.clobClient) {
2954
- throw new Error("PolymarketClient not initialized. Call initialize() first.");
2955
- }
2956
- }
2957
- parseGammaMarket(raw) {
2958
- const outcomes = raw.outcomes ? JSON.parse(raw.outcomes) : ["Yes", "No"];
2959
- const outcomePrices = raw.outcomePrices ? JSON.parse(raw.outcomePrices) : [0, 0];
2960
- const outcomeTokenIds = raw.clobTokenIds ? JSON.parse(raw.clobTokenIds) : [];
2961
- return {
2962
- conditionId: raw.conditionId || raw.condition_id || "",
2963
- question: raw.question || "",
2964
- description: raw.description || "",
2965
- category: raw.groupItemTitle || raw.category || "Other",
2966
- outcomes,
2967
- outcomeTokenIds,
2968
- outcomePrices: outcomePrices.map((p) => parseFloat(p) || 0),
2969
- volume24h: parseFloat(raw.volume24hr || raw.volume24h || "0"),
2970
- liquidity: parseFloat(raw.liquidity || "0"),
2971
- endDate: raw.endDate ? new Date(raw.endDate).getTime() / 1e3 : 0,
2972
- active: raw.active !== false && raw.closed !== true,
2973
- resolved: raw.resolved === true,
2974
- winningOutcome: raw.winningOutcome,
2975
- resolutionSource: raw.resolutionSource || void 0,
2976
- uniqueTraders: raw.uniqueTraders || void 0
2977
- };
2978
- }
2979
- parseRawFill(raw) {
2980
- const tokenId = raw.asset_id || void 0;
2981
- const marketConditionId = raw.market || raw.asset_id || "";
2982
- return {
2983
- orderId: raw.orderId || raw.order_id || "",
2984
- tradeId: raw.id || raw.tradeId || "",
2985
- marketConditionId,
2986
- outcomeIndex: raw.outcome_index ?? (raw.side === "BUY" ? 0 : 1),
2987
- side: raw.side === "BUY" || raw.side === "buy" ? "BUY" : "SELL",
2988
- price: String(raw.price || "0"),
2989
- size: String(raw.size || "0"),
2990
- fee: String(raw.fee || "0"),
2991
- timestamp: raw.timestamp || raw.created_at ? new Date(raw.created_at).getTime() : Date.now(),
2992
- isMaker: raw.maker_order || raw.is_maker || false,
2993
- tokenId
2994
- };
2995
- }
2996
- };
2997
-
2998
- // src/prediction/order-manager.ts
2999
- var PolymarketOrderManager = class {
3000
- client;
3001
- config;
3002
- seenFillIds = /* @__PURE__ */ new Set();
3003
- recentFills = [];
3004
- positions = /* @__PURE__ */ new Map();
3005
- lastPriceRefresh = 0;
3006
- PRICE_REFRESH_MS = 1e4;
3007
- constructor(client, config) {
3008
- this.client = client;
3009
- this.config = config;
3010
- }
3011
- // ── SIGNAL EXECUTION ───────────────────────────────────────
3012
- async executeSignal(signal) {
3013
- if (signal.action === "hold") {
3014
- return { success: true, status: "cancelled", error: "Hold signal \u2014 no action" };
3015
- }
3016
- const violation = this.checkRiskLimits(signal);
3017
- if (violation) {
3018
- return { success: false, status: "error", error: violation };
3019
- }
3020
- try {
3021
- const market = await this.client.getMarketByConditionId(signal.marketConditionId);
3022
- if (!market) {
3023
- return { success: false, status: "error", error: `Market not found: ${signal.marketConditionId}` };
3024
- }
3025
- if (!market.active) {
3026
- return { success: false, status: "error", error: `Market is closed: ${market.question}` };
3027
- }
3028
- const tokenId = market.outcomeTokenIds[signal.outcomeIndex];
3029
- if (!tokenId) {
3030
- return { success: false, status: "error", error: `Invalid outcome index: ${signal.outcomeIndex}` };
3031
- }
3032
- const isBuy = signal.action === "buy_yes" || signal.action === "buy_no";
3033
- const side = isBuy ? "BUY" : "SELL";
3034
- let result;
3035
- if (signal.orderType === "market") {
3036
- result = await this.client.placeMarketOrder({
3037
- tokenId,
3038
- amount: signal.amount,
3039
- side
3040
- });
3041
- } else {
3042
- result = await this.client.placeLimitOrder({
3043
- tokenId,
3044
- price: signal.limitPrice,
3045
- size: signal.amount,
3046
- side
3047
- });
3048
- }
3049
- if (result.success) {
3050
- console.log(`[prediction] Order placed: ${signal.action} ${signal.amount} on "${market.question}" @ ${signal.limitPrice}`);
3051
- return { success: true, orderId: result.orderId, status: "resting" };
3052
- }
3053
- return { success: false, status: "error", error: "Order placement failed" };
3054
- } catch (error) {
3055
- const message = error instanceof Error ? error.message : String(error);
3056
- console.error("[prediction] Order execution error:", message);
3057
- return { success: false, status: "error", error: message };
3058
- }
3059
- }
3060
- // ── FILL POLLING ───────────────────────────────────────────
3061
- async pollNewFills() {
3062
- try {
3063
- const allFills = await this.client.getTradeHistory();
3064
- const newFills = [];
3065
- for (const fill of allFills) {
3066
- if (!this.seenFillIds.has(fill.tradeId)) {
3067
- this.seenFillIds.add(fill.tradeId);
3068
- newFills.push(fill);
3069
- this.processFill(fill);
3070
- this.recentFills.push(fill);
3071
- }
3072
- }
3073
- if (this.recentFills.length > 100) {
3074
- this.recentFills = this.recentFills.slice(-100);
3075
- }
3076
- return newFills;
3077
- } catch (error) {
3078
- const message = error instanceof Error ? error.message : String(error);
3079
- console.warn("[prediction] Fill polling error:", message);
3080
- return [];
3081
- }
3082
- }
3083
- getRecentFills() {
3084
- return this.recentFills;
3085
- }
3086
- // ── POSITION QUERIES ───────────────────────────────────────
3087
- async getPositions(forceRefresh = false) {
3088
- if (forceRefresh || Date.now() - this.lastPriceRefresh > this.PRICE_REFRESH_MS) {
3089
- await this.refreshPrices();
3090
- }
3091
- return Array.from(this.positions.values()).filter((p) => p.balance > 0).map((p) => this.toExternalPosition(p));
3092
- }
3093
- async getAccountSummary() {
3094
- const positions = await this.getPositions();
3095
- const totalExposure = positions.reduce((sum, p) => sum + p.costBasis, 0);
3096
- const totalUnrealizedPnl = positions.reduce((sum, p) => sum + p.unrealizedPnl, 0);
3097
- const openMarkets = new Set(positions.map((p) => p.marketConditionId));
3098
- return {
3099
- totalExposure,
3100
- totalUnrealizedPnl,
3101
- openMarketCount: openMarkets.size,
3102
- openPositionCount: positions.length
3103
- };
3104
- }
3105
- getTotalExposure() {
3106
- let total = 0;
3107
- for (const pos of this.positions.values()) {
3108
- if (pos.balance > 0) total += pos.totalCostBasis;
3109
- }
3110
- return total;
3111
- }
3112
- // ── CANCELLATION ───────────────────────────────────────────
3113
- async cancelOrder(orderId) {
3114
- return this.client.cancelOrder(orderId);
3115
- }
3116
- async cancelAllOrders() {
3117
- return this.client.cancelAllOrders();
3118
- }
3119
- // ── PRIVATE ────────────────────────────────────────────────
3120
- checkRiskLimits(signal) {
3121
- if (signal.amount > this.config.maxNotionalUSD) {
3122
- return `Trade exceeds max notional: $${signal.amount} > $${this.config.maxNotionalUSD}`;
3123
- }
3124
- if (signal.limitPrice <= 0 || signal.limitPrice >= 1) {
3125
- return `Invalid price: ${signal.limitPrice} (must be 0.01-0.99)`;
3126
- }
3127
- if (signal.confidence < 0.3) {
3128
- return `Low confidence: ${signal.confidence} < 0.3`;
3129
- }
3130
- const isBuy = signal.action === "buy_yes" || signal.action === "buy_no";
3131
- if (isBuy) {
3132
- const currentExposure = this.getTotalExposure();
3133
- if (currentExposure + signal.amount > this.config.maxTotalExposureUSD) {
3134
- return `Total exposure exceeded: $${currentExposure + signal.amount} > $${this.config.maxTotalExposureUSD}`;
3135
- }
3136
- }
3137
- return null;
3138
- }
3139
- processFill(fill) {
3140
- const key = `${fill.marketConditionId}:${fill.outcomeIndex}`;
3141
- let pos = this.positions.get(key);
3142
- const price = parseFloat(fill.price);
3143
- const size = parseFloat(fill.size);
3144
- if (!pos) {
3145
- pos = {
3146
- marketConditionId: fill.marketConditionId,
3147
- outcomeIndex: fill.outcomeIndex,
3148
- marketQuestion: fill.marketQuestion || "",
3149
- tokenId: fill.tokenId || "",
3150
- balance: 0,
3151
- totalCostBasis: 0,
3152
- totalProceeds: 0,
3153
- averageEntryPrice: 0,
3154
- currentPrice: price,
3155
- category: void 0,
3156
- endDate: void 0
3157
- };
3158
- this.positions.set(key, pos);
3159
- } else if (!pos.tokenId && fill.tokenId) {
3160
- pos.tokenId = fill.tokenId;
3161
- }
3162
- if (fill.side === "BUY") {
3163
- const oldCost = pos.averageEntryPrice * pos.balance;
3164
- const newCost = price * size;
3165
- pos.balance += size;
3166
- pos.totalCostBasis += newCost;
3167
- pos.averageEntryPrice = pos.balance > 0 ? (oldCost + newCost) / pos.balance : 0;
3168
- } else {
3169
- pos.balance -= size;
3170
- pos.totalProceeds += price * size;
3171
- if (pos.balance < 0) pos.balance = 0;
3172
- }
3173
- }
3174
- async refreshPrices() {
3175
- const openPositions = Array.from(this.positions.values()).filter((p) => p.balance > 0);
3176
- await Promise.all(
3177
- openPositions.map(async (pos) => {
3178
- try {
3179
- if (!pos.tokenId) {
3180
- const market = await this.client.getMarketByConditionId(pos.marketConditionId);
3181
- if (market && market.outcomeTokenIds[pos.outcomeIndex]) {
3182
- pos.tokenId = market.outcomeTokenIds[pos.outcomeIndex];
3183
- }
3184
- }
3185
- if (pos.tokenId) {
3186
- const price = await this.client.getMidpointPrice(pos.tokenId);
3187
- if (price > 0) pos.currentPrice = price;
3188
- }
3189
- } catch {
3190
- }
3191
- })
3192
- );
3193
- this.lastPriceRefresh = Date.now();
3194
- }
3195
- toExternalPosition(pos) {
3196
- const unrealizedPnl = pos.balance > 0 ? (pos.currentPrice - pos.averageEntryPrice) * pos.balance : 0;
3197
- return {
3198
- marketConditionId: pos.marketConditionId,
3199
- marketQuestion: pos.marketQuestion,
3200
- outcomeIndex: pos.outcomeIndex,
3201
- outcomeLabel: pos.outcomeIndex === 0 ? "Yes" : "No",
3202
- tokenId: pos.tokenId,
3203
- balance: pos.balance,
3204
- averageEntryPrice: pos.averageEntryPrice,
3205
- currentPrice: pos.currentPrice,
3206
- unrealizedPnl,
3207
- costBasis: pos.totalCostBasis - pos.totalProceeds,
3208
- endDate: pos.endDate,
3209
- category: pos.category
3210
- };
3211
- }
3212
- };
3213
-
3214
- // src/spot/client.ts
3215
- import {
3216
- createPublicClient,
3217
- createWalletClient,
3218
- http,
3219
- maxUint256
3220
- } from "viem";
3221
- import { privateKeyToAccount } from "viem/accounts";
3222
- var SpotDEXClient = class {
3223
- account;
3224
- clients = /* @__PURE__ */ new Map();
3225
- decimalsCache = /* @__PURE__ */ new Map();
3226
- symbolCache = /* @__PURE__ */ new Map();
3227
- constructor(privateKey) {
3228
- this.account = privateKeyToAccount(privateKey);
3229
- }
3230
- get address() {
3231
- return this.account.address;
3232
- }
3233
- getClients(chainName) {
3234
- const cached = this.clients.get(chainName);
3235
- if (cached) return cached;
3236
- const chainConfig = getChainConfig(chainName);
3237
- if (!chainConfig) {
3238
- throw new Error(`Unknown chain: ${chainName}`);
3239
- }
3240
- const publicClient = createPublicClient({
3241
- chain: chainConfig.viemChain,
3242
- transport: http(chainConfig.rpcUrl)
3243
- });
3244
- const walletClient = createWalletClient({
3245
- account: this.account,
3246
- chain: chainConfig.viemChain,
3247
- transport: http(chainConfig.rpcUrl)
3248
- });
3249
- const entry = { publicClient, walletClient, chainConfig };
3250
- this.clients.set(chainName, entry);
3251
- return entry;
3252
- }
3253
- async getDecimals(token, chainName) {
3254
- const key = `${chainName}:${token}`;
3255
- const cached = this.decimalsCache.get(key);
3256
- if (cached !== void 0) return cached;
3257
- const { publicClient } = this.getClients(chainName);
3258
- const decimals = await publicClient.readContract({
3259
- address: token,
3260
- abi: ERC20_ABI,
3261
- functionName: "decimals"
3262
- });
3263
- this.decimalsCache.set(key, decimals);
3264
- return decimals;
3265
- }
3266
- async getSymbol(token, chainName) {
3267
- const key = `${chainName}:${token}`;
3268
- const cached = this.symbolCache.get(key);
3269
- if (cached) return cached;
3270
- const { publicClient } = this.getClients(chainName);
3271
- const symbol = await publicClient.readContract({
3272
- address: token,
3273
- abi: ERC20_ABI,
3274
- functionName: "symbol"
3275
- });
3276
- this.symbolCache.set(key, symbol);
3277
- return symbol;
3278
- }
3279
- async getBalance(token, chainName) {
3280
- const { publicClient } = this.getClients(chainName);
3281
- return await publicClient.readContract({
3282
- address: token,
3283
- abi: ERC20_ABI,
3284
- functionName: "balanceOf",
3285
- args: [this.account.address]
3286
- });
3287
- }
3288
- /** Get the native token balance (ETH, POL, etc.) on a chain */
3289
- async getNativeBalance(chainName) {
3290
- const { publicClient } = this.getClients(chainName);
3291
- return await publicClient.getBalance({ address: this.account.address });
3292
- }
3293
- async ensureApproval(token, spender, amount, chainName) {
3294
- const { publicClient, walletClient } = this.getClients(chainName);
3295
- const allowance = await publicClient.readContract({
3296
- address: token,
3297
- abi: ERC20_ABI,
3298
- functionName: "allowance",
3299
- args: [this.account.address, spender]
3300
- });
3301
- if (allowance >= amount) return null;
3302
- const hash = await walletClient.writeContract({
3303
- address: token,
3304
- abi: ERC20_ABI,
3305
- functionName: "approve",
3306
- args: [spender, maxUint256]
3307
- });
3308
- await publicClient.waitForTransactionReceipt({ hash });
3309
- console.log(`[spot] Approved ${token} for ${spender} on ${chainName} (tx: ${hash})`);
3310
- return hash;
3311
- }
3312
- };
3313
-
3314
- // src/spot/uniswap.ts
3315
- var FEE_TIERS = [500, 3e3, 1e4];
3316
- var UniswapAdapter = class {
3317
- client;
3318
- constructor(client) {
3319
- this.client = client;
3320
- }
3321
- async quote(params) {
3322
- const chainConfig = getChainConfig(params.chain);
3323
- if (!chainConfig?.uniswapQuoter) {
3324
- throw new Error(`No Uniswap QuoterV2 on ${params.chain}`);
3325
- }
3326
- const { publicClient } = this.client.getClients(params.chain);
3327
- let bestAmountOut = 0n;
3328
- let bestFeeTier = 0;
3329
- for (const fee of FEE_TIERS) {
3330
- try {
3331
- const result = await publicClient.simulateContract({
3332
- address: chainConfig.uniswapQuoter,
3333
- abi: UNISWAP_QUOTER_V2_ABI,
3334
- functionName: "quoteExactInputSingle",
3335
- args: [
3336
- {
3337
- tokenIn: params.tokenIn,
3338
- tokenOut: params.tokenOut,
3339
- amountIn: params.amountIn,
3340
- fee,
3341
- sqrtPriceLimitX96: 0n
3342
- }
3343
- ]
3344
- });
3345
- const amountOut = result.result[0];
3346
- if (amountOut > bestAmountOut) {
3347
- bestAmountOut = amountOut;
3348
- bestFeeTier = fee;
3349
- }
3350
- } catch {
3351
- }
3352
- }
3353
- if (bestAmountOut === 0n) {
3354
- throw new Error(`No Uniswap V3 pool found for ${params.tokenIn}/${params.tokenOut} on ${params.chain}`);
3355
- }
3356
- const tokenInSymbol = await this.client.getSymbol(params.tokenIn, params.chain);
3357
- const tokenOutSymbol = await this.client.getSymbol(params.tokenOut, params.chain);
3358
- return {
3359
- amountOut: bestAmountOut,
3360
- feeTier: bestFeeTier,
3361
- route: `${tokenInSymbol} \u2192 ${tokenOutSymbol} (${bestFeeTier / 1e4}%)`
3362
- };
3363
- }
3364
- async swap(params) {
3365
- const chainConfig = getChainConfig(params.chain);
3366
- if (!chainConfig) {
3367
- throw new Error(`Unknown chain: ${params.chain}`);
3368
- }
3369
- const routerAddress = chainConfig.dexRouters.uniswap;
3370
- if (!routerAddress) {
3371
- throw new Error(`No Uniswap router on ${params.chain}`);
3372
- }
3373
- const quoteResult = await this.quote(params);
3374
- const amountOutMinimum = quoteResult.amountOut * BigInt(1e4 - params.slippageBps) / 10000n;
3375
- await this.client.ensureApproval(params.tokenIn, routerAddress, params.amountIn, params.chain);
3376
- const { publicClient, walletClient } = this.client.getClients(params.chain);
3377
- const recipient = params.recipient ?? this.client.address;
3378
- try {
3379
- const hash = await walletClient.writeContract({
3380
- address: routerAddress,
3381
- abi: UNISWAP_SWAP_ROUTER_ABI,
3382
- functionName: "exactInputSingle",
3383
- args: [
3384
- {
3385
- tokenIn: params.tokenIn,
3386
- tokenOut: params.tokenOut,
3387
- fee: quoteResult.feeTier,
3388
- recipient,
3389
- amountIn: params.amountIn,
3390
- amountOutMinimum,
3391
- sqrtPriceLimitX96: 0n
3392
- }
3393
- ]
3394
- });
3395
- const receipt = await publicClient.waitForTransactionReceipt({ hash });
3396
- const tokenInDecimals = await this.client.getDecimals(params.tokenIn, params.chain);
3397
- const tokenOutDecimals = await this.client.getDecimals(params.tokenOut, params.chain);
3398
- const amountInFloat = Number(params.amountIn) / 10 ** tokenInDecimals;
3399
- const amountOutFloat = Number(quoteResult.amountOut) / 10 ** tokenOutDecimals;
3400
- const effectivePrice = amountOutFloat / amountInFloat;
3401
- const gasUsed = receipt.gasUsed ?? 0n;
3402
- const gasPrice = receipt.effectiveGasPrice ?? 0n;
3403
- return {
3404
- success: true,
3405
- txHash: hash,
3406
- amountIn: params.amountIn,
3407
- amountOut: quoteResult.amountOut,
3408
- tokenIn: params.tokenIn,
3409
- tokenOut: params.tokenOut,
3410
- effectivePrice,
3411
- gasCost: gasUsed * gasPrice,
3412
- chain: params.chain,
3413
- dex: "uniswap"
3414
- };
3415
- } catch (err) {
3416
- return {
3417
- success: false,
3418
- txHash: "0x0",
3419
- amountIn: params.amountIn,
3420
- amountOut: 0n,
3421
- tokenIn: params.tokenIn,
3422
- tokenOut: params.tokenOut,
3423
- effectivePrice: 0,
3424
- gasCost: 0n,
3425
- chain: params.chain,
3426
- dex: "uniswap",
3427
- error: err.message
3428
- };
3429
- }
3430
- }
3431
- };
3432
-
3433
- // src/spot/aerodrome.ts
3434
- var AerodromeAdapter = class {
3435
- client;
3436
- constructor(client) {
3437
- this.client = client;
3438
- }
3439
- async quote(params) {
3440
- if (params.chain !== "base") {
3441
- throw new Error("Aerodrome is only available on Base");
3442
- }
3443
- const chainConfig = getChainConfig("base");
3444
- const routerAddress = chainConfig.dexRouters.aerodrome;
3445
- if (!routerAddress) {
3446
- throw new Error("No Aerodrome router configured for Base");
3447
- }
3448
- const { publicClient } = this.client.getClients("base");
3449
- let bestAmountOut = 0n;
3450
- let bestStable = false;
3451
- for (const stable of [true, false]) {
3452
- try {
3453
- const route = [
3454
- {
3455
- from: params.tokenIn,
3456
- to: params.tokenOut,
3457
- stable,
3458
- factory: AERODROME_DEFAULT_FACTORY
3459
- }
3460
- ];
3461
- const amounts = await publicClient.readContract({
3462
- address: routerAddress,
3463
- abi: AERODROME_ROUTER_ABI,
3464
- functionName: "getAmountsOut",
3465
- args: [params.amountIn, route]
3466
- });
3467
- const amountOut = amounts[amounts.length - 1];
3468
- if (amountOut > bestAmountOut) {
3469
- bestAmountOut = amountOut;
3470
- bestStable = stable;
3471
- }
3472
- } catch {
3473
- }
3474
- }
3475
- if (bestAmountOut === 0n) {
3476
- throw new Error(`No Aerodrome pool found for ${params.tokenIn}/${params.tokenOut}`);
3477
- }
3478
- const tokenInSymbol = await this.client.getSymbol(params.tokenIn, "base");
3479
- const tokenOutSymbol = await this.client.getSymbol(params.tokenOut, "base");
3480
- return {
3481
- amountOut: bestAmountOut,
3482
- stable: bestStable,
3483
- route: `${tokenInSymbol} \u2192 ${tokenOutSymbol} (${bestStable ? "stable" : "volatile"})`
3484
- };
3485
- }
3486
- async swap(params) {
3487
- if (params.chain !== "base") {
3488
- throw new Error("Aerodrome is only available on Base");
3489
- }
3490
- const chainConfig = getChainConfig("base");
3491
- const routerAddress = chainConfig.dexRouters.aerodrome;
3492
- if (!routerAddress) {
3493
- throw new Error("No Aerodrome router configured for Base");
3494
- }
3495
- const quoteResult = await this.quote(params);
3496
- const amountOutMin = quoteResult.amountOut * BigInt(1e4 - params.slippageBps) / 10000n;
3497
- await this.client.ensureApproval(params.tokenIn, routerAddress, params.amountIn, "base");
3498
- const { publicClient, walletClient } = this.client.getClients("base");
3499
- const recipient = params.recipient ?? this.client.address;
3500
- const route = [
3501
- {
3502
- from: params.tokenIn,
3503
- to: params.tokenOut,
3504
- stable: quoteResult.stable,
3505
- factory: AERODROME_DEFAULT_FACTORY
3506
- }
3507
- ];
3508
- const deadline = BigInt(Math.floor(Date.now() / 1e3) + 300);
3509
- try {
3510
- const hash = await walletClient.writeContract({
3511
- address: routerAddress,
3512
- abi: AERODROME_ROUTER_ABI,
3513
- functionName: "swapExactTokensForTokens",
3514
- args: [params.amountIn, amountOutMin, route, recipient, deadline]
3515
- });
3516
- const receipt = await publicClient.waitForTransactionReceipt({ hash });
3517
- const tokenInDecimals = await this.client.getDecimals(params.tokenIn, "base");
3518
- const tokenOutDecimals = await this.client.getDecimals(params.tokenOut, "base");
3519
- const amountInFloat = Number(params.amountIn) / 10 ** tokenInDecimals;
3520
- const amountOutFloat = Number(quoteResult.amountOut) / 10 ** tokenOutDecimals;
3521
- const effectivePrice = amountOutFloat / amountInFloat;
3522
- const gasUsed = receipt.gasUsed ?? 0n;
3523
- const gasPrice = receipt.effectiveGasPrice ?? 0n;
3524
- return {
3525
- success: true,
3526
- txHash: hash,
3527
- amountIn: params.amountIn,
3528
- amountOut: quoteResult.amountOut,
3529
- tokenIn: params.tokenIn,
3530
- tokenOut: params.tokenOut,
3531
- effectivePrice,
3532
- gasCost: gasUsed * gasPrice,
3533
- chain: "base",
3534
- dex: "aerodrome"
3535
- };
3536
- } catch (err) {
3537
- return {
3538
- success: false,
3539
- txHash: "0x0",
3540
- amountIn: params.amountIn,
3541
- amountOut: 0n,
3542
- tokenIn: params.tokenIn,
3543
- tokenOut: params.tokenOut,
3544
- effectivePrice: 0,
3545
- gasCost: 0n,
3546
- chain: "base",
3547
- dex: "aerodrome",
3548
- error: err.message
3549
- };
3550
- }
3551
- }
3552
- };
3553
-
3554
- // src/spot/swap-manager.ts
3555
- var TOKEN_ALIASES = {
3556
- base: {
3557
- ETH: "0x4200000000000000000000000000000000000006",
3558
- WETH: "0x4200000000000000000000000000000000000006",
3559
- USDC: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
3560
- USDbC: "0xd9aAEc86B65D86f6A7B5B1b0c42FFA531710b6CA",
3561
- DAI: "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb"
3562
- },
3563
- ethereum: {
3564
- ETH: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
3565
- WETH: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
3566
- USDC: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
3567
- USDT: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
3568
- DAI: "0x6B175474E89094C44Da98b954EedeAC495271d0F"
3569
- },
3570
- arbitrum: {
3571
- ETH: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
3572
- WETH: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
3573
- USDC: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
3574
- "USDC.e": "0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8",
3575
- USDT: "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"
3576
- },
3577
- polygon: {
3578
- POL: "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",
3579
- WPOL: "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",
3580
- WMATIC: "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",
3581
- USDC: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
3582
- "USDC.e": "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
3583
- USDT: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F"
3584
- }
3585
- };
3586
- var SpotSwapManager = class {
3587
- dexClient;
3588
- uniswap;
3589
- aerodrome;
3590
- config;
3591
- constructor(privateKey, config) {
3592
- this.config = config;
3593
- this.dexClient = new SpotDEXClient(privateKey);
3594
- this.uniswap = new UniswapAdapter(this.dexClient);
3595
- this.aerodrome = new AerodromeAdapter(this.dexClient);
3596
- }
3597
- get client() {
3598
- return this.dexClient;
3599
- }
3600
- /** Resolve a token symbol or address to a hex address */
3601
- resolveToken(tokenOrSymbol, chain) {
3602
- if (tokenOrSymbol.startsWith("0x") && tokenOrSymbol.length === 42) {
3603
- return tokenOrSymbol;
3604
- }
3605
- const chainAliases = TOKEN_ALIASES[chain];
3606
- if (chainAliases) {
3607
- const upper = tokenOrSymbol.toUpperCase();
3608
- const address = chainAliases[upper] ?? chainAliases[tokenOrSymbol];
3609
- if (address) return address;
3610
- }
3611
- const chainConfig = getChainConfig(chain);
3612
- if (chainConfig) {
3613
- const upper = tokenOrSymbol.toUpperCase();
3614
- if (upper === "WETH" || upper === "ETH") return chainConfig.wethAddress;
3615
- if (upper === "USDC") return chainConfig.usdcAddress;
3616
- }
3617
- throw new Error(`Cannot resolve token "${tokenOrSymbol}" on ${chain}. Provide contract address.`);
3618
- }
3619
- /** Select DEX: explicit choice, or auto-detect */
3620
- selectDex(chain, dex) {
3621
- if (dex) return dex;
3622
- const chainConfig = getChainConfig(chain);
3623
- if (chain === "base" && chainConfig?.dexRouters.aerodrome) {
3624
- return "aerodrome";
3625
- }
3626
- return "uniswap";
3627
- }
3628
- async getQuote(params) {
3629
- const chain = params.chain ?? this.config.defaultChain;
3630
- const dex = this.selectDex(chain, params.dex);
3631
- const swapParams = {
3632
- tokenIn: this.resolveToken(params.tokenIn, chain),
3633
- tokenOut: this.resolveToken(params.tokenOut, chain),
3634
- amountIn: params.amountIn,
3635
- slippageBps: this.config.maxSlippageBps,
3636
- chain,
3637
- dex
3638
- };
3639
- if (dex === "aerodrome") {
3640
- return this.aerodrome.quote(swapParams);
3641
- }
3642
- return this.uniswap.quote(swapParams);
3643
- }
3644
- async executeSwap(params) {
3645
- const chain = params.chain ?? this.config.defaultChain;
3646
- const dex = this.selectDex(chain, params.dex);
3647
- const tokenInAddress = this.resolveToken(params.tokenIn, chain);
3648
- try {
3649
- const decimals = await this.dexClient.getDecimals(tokenInAddress, chain);
3650
- const amountFloat = Number(params.amountIn) / 10 ** decimals;
3651
- if (amountFloat > this.config.maxSwapValueUSD) {
3652
- return {
3653
- success: false,
3654
- txHash: "0x0",
3655
- amountIn: params.amountIn,
3656
- amountOut: 0n,
3657
- tokenIn: "0x0",
3658
- tokenOut: "0x0",
3659
- effectivePrice: 0,
3660
- gasCost: 0n,
3661
- chain,
3662
- dex,
3663
- error: `Swap value ${amountFloat.toFixed(2)} tokens exceeds max $${this.config.maxSwapValueUSD}. Reduce size or increase maxSwapValueUSD.`
3664
- };
3665
- }
3666
- } catch {
3667
- }
3668
- if (!this.config.chains.includes(chain)) {
3669
- return {
3670
- success: false,
3671
- txHash: "0x0",
3672
- amountIn: params.amountIn,
3673
- amountOut: 0n,
3674
- tokenIn: "0x0",
3675
- tokenOut: "0x0",
3676
- effectivePrice: 0,
3677
- gasCost: 0n,
3678
- chain,
3679
- dex,
3680
- error: `Chain "${chain}" not enabled in spot config (enabled: ${this.config.chains.join(", ")})`
3681
- };
3682
- }
3683
- const MIN_GAS_WEI2 = 100000000000000n;
3684
- try {
3685
- const nativeBalance = await this.dexClient.getNativeBalance(chain);
3686
- if (nativeBalance < MIN_GAS_WEI2) {
3687
- const chainConfig = getChainConfig(chain);
3688
- const nativeName = chainConfig?.nativeCurrency ?? "ETH";
3689
- return {
3690
- success: false,
3691
- txHash: "0x0",
3692
- amountIn: params.amountIn,
3693
- amountOut: 0n,
3694
- tokenIn: "0x0",
3695
- tokenOut: "0x0",
3696
- effectivePrice: 0,
3697
- gasCost: 0n,
3698
- chain,
3699
- dex,
3700
- error: `Insufficient ${nativeName} for gas on ${chain}. Balance: ${nativeBalance} wei. Need at least 0.0001 ${nativeName}. Bridge gas to ${chain} before swapping.`
3701
- };
3702
- }
3703
- } catch {
3704
- }
3705
- const swapParams = {
3706
- tokenIn: this.resolveToken(params.tokenIn, chain),
3707
- tokenOut: this.resolveToken(params.tokenOut, chain),
3708
- amountIn: params.amountIn,
3709
- slippageBps: params.slippageBps ?? this.config.maxSlippageBps,
3710
- chain,
3711
- dex
3712
- };
3713
- console.log(`[spot] Swapping on ${dex}/${chain}: ${params.tokenIn} \u2192 ${params.tokenOut} (${params.amountIn})`);
3714
- if (dex === "aerodrome") {
3715
- return this.aerodrome.swap(swapParams);
3716
- }
3717
- return this.uniswap.swap(swapParams);
3718
- }
3719
- };
3720
-
3721
- // src/bridge/types.ts
3722
- var DEFAULT_BRIDGE_CONFIG = {
3723
- enabled: false,
3724
- defaultBridge: "across",
3725
- maxBridgeValueUSD: 1e4,
3726
- fillTimeoutMs: 3e5,
3727
- // 5 minutes
3728
- pollIntervalMs: 2e3
3729
- // 2 seconds
3730
- };
3731
- var ACROSS_SPOKE_POOL_ABI = [
3732
- {
3733
- type: "function",
3734
- name: "depositV3",
3735
- inputs: [
3736
- { name: "depositor", type: "address" },
3737
- { name: "recipient", type: "address" },
3738
- { name: "inputToken", type: "address" },
3739
- { name: "outputToken", type: "address" },
3740
- { name: "inputAmount", type: "uint256" },
3741
- { name: "outputAmount", type: "uint256" },
3742
- { name: "destinationChainId", type: "uint256" },
3743
- { name: "exclusiveRelayer", type: "address" },
3744
- { name: "quoteTimestamp", type: "uint32" },
3745
- { name: "fillDeadline", type: "uint32" },
3746
- { name: "exclusivityDeadline", type: "uint32" },
3747
- { name: "message", type: "bytes" }
3748
- ],
3749
- outputs: [],
3750
- stateMutability: "payable"
3751
- }
3752
- ];
3753
-
3754
- // src/bridge/across.ts
3755
- var ACROSS_API_BASE = "https://app.across.to/api";
3756
- var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
3757
- var AcrossAdapter = class {
3758
- client;
3759
- config;
3760
- constructor(client, config) {
3761
- this.client = client;
3762
- this.config = config;
3763
- }
3764
- async estimateFee(request) {
3765
- const fromChain = getChainConfig(request.fromChain);
3766
- const toChain = getChainConfig(request.toChain);
3767
- if (!fromChain) throw new Error(`Unknown source chain: ${request.fromChain}`);
3768
- if (!toChain) throw new Error(`Unknown destination chain: ${request.toChain}`);
3769
- const outputToken = this.resolveOutputToken(request.token, request.fromChain, request.toChain);
3770
- const params = new URLSearchParams({
3771
- inputToken: request.token,
3772
- outputToken,
3773
- originChainId: fromChain.chainId.toString(),
3774
- destinationChainId: toChain.chainId.toString(),
3775
- amount: request.amount.toString(),
3776
- recipient: request.recipient ?? this.client.address
3777
- });
3778
- const url = `${ACROSS_API_BASE}/suggested-fees?${params}`;
3779
- const res = await fetch(url);
3780
- if (!res.ok) {
3781
- const body = await res.text();
3782
- throw new Error(`Across fee API error (${res.status}): ${body}`);
3783
- }
3784
- const data = await res.json();
3785
- const totalFeePct = parseFloat(data.totalRelayFee.pct) / 1e18;
3786
- const feeAmount = BigInt(Math.floor(Number(request.amount) * totalFeePct));
3787
- const outputAmount = request.amount - feeAmount;
3788
- return {
3789
- totalRelayFeePct: totalFeePct * 100,
3790
- capitalFeePct: parseFloat(data.relayerCapitalFee.pct) / 1e18 * 100,
3791
- lpFeePct: parseFloat(data.lpFee.pct) / 1e18 * 100,
3792
- relayGasFeePct: parseFloat(data.relayerGasFee.pct) / 1e18 * 100,
3793
- timestamp: parseInt(data.timestamp),
3794
- estimatedFillTimeSec: data.estimatedFillTimeSec,
3795
- isAmountTooLow: data.isAmountTooLow,
3796
- outputAmount
3797
- };
3798
- }
3799
- async deposit(request) {
3800
- const fromChain = getChainConfig(request.fromChain);
3801
- const toChain = getChainConfig(request.toChain);
3802
- if (!fromChain?.acrossSpokePool) throw new Error(`No Across SpokePool on ${request.fromChain}`);
3803
- if (!toChain) throw new Error(`Unknown destination chain: ${request.toChain}`);
3804
- const spokePool = fromChain.acrossSpokePool;
3805
- const outputToken = this.resolveOutputToken(request.token, request.fromChain, request.toChain);
3806
- const recipient = request.recipient ?? this.client.address;
3807
- await this.client.ensureApproval(request.token, spokePool, request.amount, request.fromChain);
3808
- const feeEstimate = await this.estimateFee(request);
3809
- if (feeEstimate.isAmountTooLow) {
3810
- return {
3811
- success: false,
3812
- depositTxHash: "0x0",
3813
- fromChain: request.fromChain,
3814
- toChain: request.toChain,
3815
- token: request.token,
3816
- amount: request.amount,
3817
- fee: 0n,
3818
- error: "Amount too low for Across bridge"
3819
- };
3820
- }
3821
- const { publicClient, walletClient } = this.client.getClients(request.fromChain);
3822
- const fillDeadline = Math.floor(Date.now() / 1e3) + 21600;
3823
- try {
3824
- const hash = await walletClient.writeContract({
3825
- address: spokePool,
3826
- abi: ACROSS_SPOKE_POOL_ABI,
3827
- functionName: "depositV3",
3828
- args: [
3829
- this.client.address,
3830
- // depositor
3831
- recipient,
3832
- // recipient
3833
- request.token,
3834
- // inputToken
3835
- outputToken,
3836
- // outputToken
3837
- request.amount,
3838
- // inputAmount
3839
- feeEstimate.outputAmount,
3840
- // outputAmount (inputAmount - fees)
3841
- BigInt(toChain.chainId),
3842
- // destinationChainId
3843
- ZERO_ADDRESS,
3844
- // exclusiveRelayer (none)
3845
- feeEstimate.timestamp,
3846
- // quoteTimestamp
3847
- fillDeadline,
3848
- // fillDeadline
3849
- 0,
3850
- // exclusivityDeadline (none)
3851
- "0x"
3852
- // message (empty)
3853
- ]
3854
- });
3855
- const receipt = await publicClient.waitForTransactionReceipt({ hash });
3856
- const fee = request.amount - feeEstimate.outputAmount;
3857
- console.log(`[bridge] Across deposit: ${hash} (${request.fromChain} \u2192 ${request.toChain})`);
3858
- const result = {
3859
- success: true,
3860
- depositTxHash: hash,
3861
- fromChain: request.fromChain,
3862
- toChain: request.toChain,
3863
- token: request.token,
3864
- amount: request.amount,
3865
- fee
3866
- };
3867
- const fill = await this.waitForFill(hash, request.fromChain);
3868
- if (fill.filled) {
3869
- result.fillTxHash = fill.fillTxHash;
3870
- result.fillTimestamp = Date.now();
3871
- console.log(`[bridge] Across fill confirmed: ${fill.fillTxHash}`);
3872
- } else {
3873
- console.warn(`[bridge] Across fill not confirmed within timeout \u2014 deposit was successful, fill may still arrive`);
3874
- }
3875
- return result;
3876
- } catch (err) {
3877
- return {
3878
- success: false,
3879
- depositTxHash: "0x0",
3880
- fromChain: request.fromChain,
3881
- toChain: request.toChain,
3882
- token: request.token,
3883
- amount: request.amount,
3884
- fee: 0n,
3885
- error: err.message
3886
- };
3887
- }
3888
- }
3889
- async waitForFill(depositTxHash, originChain) {
3890
- const chainConfig = getChainConfig(originChain);
3891
- if (!chainConfig) return { filled: false };
3892
- const startTime = Date.now();
3893
- const timeout = this.config.fillTimeoutMs;
3894
- const interval = this.config.pollIntervalMs;
3895
- while (Date.now() - startTime < timeout) {
3896
- try {
3897
- const params = new URLSearchParams({
3898
- depositTxHash,
3899
- originChainId: chainConfig.chainId.toString()
3900
- });
3901
- const res = await fetch(`${ACROSS_API_BASE}/deposit/status?${params}`);
3902
- if (res.ok) {
3903
- const data = await res.json();
3904
- if (data.status === "filled" && data.fillTx) {
3905
- return { filled: true, fillTxHash: data.fillTx };
3906
- }
3907
- if (data.status === "expired" || data.status === "refunded") {
3908
- return { filled: false };
3909
- }
3910
- }
3911
- } catch {
3912
- }
3913
- await new Promise((resolve2) => setTimeout(resolve2, interval));
3914
- }
3915
- return { filled: false };
3916
- }
3917
- /** Resolve the equivalent token address on the destination chain */
3918
- resolveOutputToken(inputToken, fromChain, toChain) {
3919
- const from = getChainConfig(fromChain);
3920
- const to = getChainConfig(toChain);
3921
- if (!from || !to) return inputToken;
3922
- if (inputToken.toLowerCase() === from.usdcAddress.toLowerCase()) {
3923
- return to.usdcAddress;
3924
- }
3925
- if (inputToken.toLowerCase() === from.wethAddress.toLowerCase()) {
3926
- return to.wethAddress;
3927
- }
3928
- return inputToken;
3929
- }
3930
- };
3931
-
3932
- // src/bridge/bridge-manager.ts
3933
- var MIN_GAS_WEI = 100000000000000n;
3934
- var BridgeManager = class {
3935
- across;
3936
- client;
3937
- config;
3938
- constructor(client, config) {
3939
- this.config = config;
3940
- this.client = client;
3941
- this.across = new AcrossAdapter(client, config);
3942
- }
3943
- async estimateFee(request) {
3944
- const bridge = request.bridge ?? this.config.defaultBridge;
3945
- if (bridge !== "across") {
3946
- throw new Error(`Unsupported bridge: ${bridge}. Only "across" is currently supported.`);
3947
- }
3948
- return this.across.estimateFee(request);
3949
- }
3950
- async bridge(request) {
3951
- const bridge = request.bridge ?? this.config.defaultBridge;
3952
- if (bridge !== "across") {
3953
- return {
3954
- success: false,
3955
- depositTxHash: "0x0",
3956
- fromChain: request.fromChain,
3957
- toChain: request.toChain,
3958
- token: request.token,
3959
- amount: request.amount,
3960
- fee: 0n,
3961
- error: `Unsupported bridge: ${bridge}. Only "across" is currently supported.`
3962
- };
3963
- }
3964
- try {
3965
- const decimals = await this.client.getDecimals(request.token, request.fromChain);
3966
- const amountFloat = Number(request.amount) / 10 ** decimals;
3967
- if (amountFloat > this.config.maxBridgeValueUSD) {
3968
- return {
3969
- success: false,
3970
- depositTxHash: "0x0",
3971
- fromChain: request.fromChain,
3972
- toChain: request.toChain,
3973
- token: request.token,
3974
- amount: request.amount,
3975
- fee: 0n,
3976
- error: `Bridge value ${amountFloat.toFixed(2)} exceeds max $${this.config.maxBridgeValueUSD}. Reduce amount or increase maxBridgeValueUSD.`
3977
- };
3978
- }
3979
- } catch {
3980
- }
3981
- try {
3982
- const nativeBalance = await this.client.getNativeBalance(request.fromChain);
3983
- if (nativeBalance < MIN_GAS_WEI) {
3984
- const chainConfig = getChainConfig(request.fromChain);
3985
- const nativeName = chainConfig?.nativeCurrency ?? "ETH";
3986
- return {
3987
- success: false,
3988
- depositTxHash: "0x0",
3989
- fromChain: request.fromChain,
3990
- toChain: request.toChain,
3991
- token: request.token,
3992
- amount: request.amount,
3993
- fee: 0n,
3994
- error: `Insufficient ${nativeName} for gas on ${request.fromChain}. Balance: ${nativeBalance} wei. Need at least 0.0001 ${nativeName}.`
3995
- };
3996
- }
3997
- } catch {
3998
- }
3999
- console.log(`[bridge] Bridging via Across: ${request.fromChain} \u2192 ${request.toChain} (${request.amount})`);
4000
- return this.across.deposit(request);
4001
- }
4002
- };
4003
-
4004
- // src/runtime.ts
4005
- import { createWalletClient as createWalletClient2, http as http2, formatUnits } from "viem";
4006
- import { privateKeyToAccount as privateKeyToAccount2 } from "viem/accounts";
4007
- import { arbitrum as arbitrum2 } from "viem/chains";
4008
- var SDK_VERSION = "0.1.0";
4009
- var AgentRuntime = class _AgentRuntime {
4010
- config;
4011
- relay;
4012
- signal;
4013
- store;
4014
- positions;
4015
- llm;
4016
- strategy = null;
4017
- risk;
4018
- market;
4019
- paper = null;
4020
- // Venue clients
4021
- hlClient = null;
4022
- hlSigner = null;
4023
- hlOrders = null;
4024
- hlPositions = null;
4025
- hlWs = null;
4026
- pmClient = null;
4027
- pmOrders = null;
4028
- spotManager = null;
4029
- bridgeManager = null;
4030
- walletAddress = null;
4031
- mode = "idle";
4032
- cycleCount = 0;
4033
- lastCycleAt = 0;
4034
- tradingInterval = null;
4035
- running = false;
4036
- cycleInProgress = false;
4037
- constructor(config) {
4038
- this.config = config;
4039
- this.store = new FileStore(`data/${config.agentId}-store.json`);
4040
- this.positions = new PositionTracker(this.store);
4041
- this.market = new MarketDataService(3e4, config.apiUrl);
4042
- this.risk = new RiskManager(
4043
- {
4044
- maxPositionSizeBps: config.trading.maxPositionSizeBps,
4045
- maxDailyLossBps: config.trading.maxDailyLossBps,
4046
- maxConcurrentPositions: config.trading.maxConcurrentPositions,
4047
- maxSlippageBps: config.trading.maxSlippageBps,
4048
- minTradeValueUSD: config.trading.minTradeValueUSD
4049
- },
4050
- config.trading.initialCapitalUSD
4051
- );
4052
- this.llm = createLLMAdapter(config.llm);
4053
- this.relay = new RelayClient({
4054
- url: config.relay.url,
4055
- agentId: config.agentId,
4056
- token: config.apiToken,
4057
- heartbeatIntervalMs: config.relay.heartbeatIntervalMs,
4058
- reconnectMaxAttempts: config.relay.reconnectMaxAttempts,
4059
- onCommand: (cmd) => this.handleCommand(cmd),
4060
- onConnected: () => {
4061
- console.log(`[runtime] Connected to command center`);
4062
- this.sendStatus();
4063
- },
4064
- onDisconnected: () => {
4065
- console.log(`[runtime] Disconnected from command center`);
4066
- }
4067
- });
4068
- this.signal = new SignalReporter(this.relay);
4069
- if (config.trading.mode === "paper") {
4070
- this.paper = new PaperExecutor(config.trading.initialCapitalUSD ?? 1e4);
4071
- }
4072
- }
4073
- async start() {
4074
- console.log(`[runtime] Starting agent ${this.config.agentId}`);
4075
- console.log(`[runtime] Mode: ${this.config.trading.mode}`);
4076
- console.log(`[runtime] LLM: ${this.config.llm.provider}/${this.config.llm.model}`);
4077
- try {
4078
- this.strategy = await loadStrategy(this.config.strategy);
4079
- console.log(`[runtime] Strategy loaded`);
4080
- } catch (err) {
4081
- console.error(`[runtime] Failed to load strategy:`, err.message);
4082
- this.strategy = null;
4083
- }
4084
- if (this.config.trading.mode === "live") {
4085
- await this.initializeVenues();
4086
- }
4087
- try {
4088
- await this.relay.connect();
4089
- this.signal.reportInfo("Agent Started", `Agent ${this.config.agentId} connected to command center`);
4090
- } catch (err) {
4091
- console.error(`[runtime] Failed to connect to relay:`, err.message);
4092
- console.log(`[runtime] Will retry in background...`);
4093
- }
4094
- this.running = true;
4095
- this.mode = "idle";
4096
- this.sendStatus();
4097
- if (this.config.trading.mode === "paper" || this.config.trading.mode === "live") {
4098
- this.startTrading();
4099
- }
4100
- process.on("SIGTERM", () => this.stop());
4101
- process.on("SIGINT", () => this.stop());
4102
- }
4103
- async stop() {
4104
- console.log(`[runtime] Stopping agent ${this.config.agentId}`);
4105
- this.running = false;
4106
- this.stopTrading();
4107
- if (this.hlWs) {
4108
- this.hlWs.disconnect();
4109
- }
4110
- this.signal.reportInfo("Agent Stopped", `Agent ${this.config.agentId} shutting down`);
4111
- this.relay.disconnect();
4112
- console.log(`[runtime] Agent stopped`);
4113
- process.exit(0);
4114
- }
4115
- // ── VENUE INITIALIZATION ───────────────────────────────────
4116
- async initializeVenues() {
4117
- const privateKey = this.config.wallet?.privateKey;
4118
- if (!privateKey) {
4119
- console.log("[runtime] No wallet configured \u2014 live trading disabled");
4120
- return;
4121
- }
4122
- const walletAccount = privateKeyToAccount2(privateKey);
4123
- this.walletAddress = walletAccount.address;
4124
- const hlConfig = this.config.venues?.hyperliquid_perp;
4125
- if (hlConfig?.enabled) {
4126
- try {
4127
- const account = walletAccount;
4128
- const walletClient = createWalletClient2({
4129
- account,
4130
- chain: arbitrum2,
4131
- transport: http2()
4132
- });
4133
- const perpConfig = {
4134
- enabled: true,
4135
- apiUrl: hlConfig.apiUrl,
4136
- wsUrl: hlConfig.wsUrl,
4137
- maxLeverage: hlConfig.maxLeverage,
4138
- maxNotionalUSD: hlConfig.maxNotionalUSD,
4139
- allowedInstruments: hlConfig.allowedInstruments
4140
- };
4141
- this.hlClient = new HyperliquidClient(perpConfig);
4142
- this.hlSigner = new HyperliquidSigner(walletClient);
4143
- this.hlOrders = new HyperliquidOrderManager(this.hlClient, this.hlSigner, perpConfig);
4144
- this.hlPositions = new HyperliquidPositionManager(this.hlClient, account.address);
4145
- this.hlWs = new HyperliquidWebSocket(perpConfig, account.address, this.hlClient);
4146
- await this.hlClient.getMeta();
4147
- this.hlWs.onFillReceived((fill) => {
4148
- this.handleHyperliquidFill(fill);
4149
- });
4150
- this.hlWs.onLiquidationDetected((instrument, size) => {
4151
- this.signal.reportError("Liquidation Detected", `${instrument}: ${size} liquidated`);
4152
- });
4153
- await this.hlWs.connect();
4154
- console.log(`[runtime] Hyperliquid initialized (${account.address})`);
4155
- } catch (err) {
4156
- console.error("[runtime] Failed to initialize Hyperliquid:", err.message);
4157
- }
4158
- }
4159
- const pmConfig = this.config.venues?.polymarket;
4160
- if (pmConfig?.enabled) {
4161
- try {
4162
- const predConfig = {
4163
- enabled: true,
4164
- clobApiUrl: pmConfig.clobApiUrl,
4165
- gammaApiUrl: pmConfig.gammaApiUrl,
4166
- maxNotionalUSD: pmConfig.maxNotionalUSD,
4167
- maxTotalExposureUSD: pmConfig.maxTotalExposureUSD,
4168
- allowedCategories: pmConfig.allowedCategories
4169
- };
4170
- this.pmClient = new PolymarketClient(privateKey, predConfig);
4171
- await this.pmClient.initialize();
4172
- this.pmOrders = new PolymarketOrderManager(this.pmClient, predConfig);
4173
- console.log(`[runtime] Polymarket initialized`);
4174
- } catch (err) {
4175
- console.error("[runtime] Failed to initialize Polymarket:", err.message);
4176
- }
4177
- }
4178
- const spotConfig = this.config.venues?.spot;
4179
- if (spotConfig?.enabled) {
4180
- try {
4181
- const cfg = {
4182
- enabled: true,
4183
- chains: spotConfig.chains,
4184
- defaultChain: spotConfig.defaultChain,
4185
- maxSlippageBps: spotConfig.maxSlippageBps,
4186
- maxSwapValueUSD: spotConfig.maxSwapValueUSD
4187
- };
4188
- this.spotManager = new SpotSwapManager(privateKey, cfg);
4189
- console.log(`[runtime] Spot DEX initialized (chains: ${spotConfig.chains.join(", ")})`);
4190
- } catch (err) {
4191
- console.error("[runtime] Failed to initialize Spot DEX:", err.message);
4192
- }
4193
- }
4194
- const bridgeConfig = this.config.venues?.bridge;
4195
- if (bridgeConfig?.enabled) {
4196
- try {
4197
- if (!this.spotManager) {
4198
- const minimalSpotConfig = {
4199
- enabled: true,
4200
- chains: ["base", "ethereum", "arbitrum", "polygon"],
4201
- defaultChain: "base",
4202
- maxSlippageBps: 50,
4203
- maxSwapValueUSD: 1e4
4204
- };
4205
- this.spotManager = new SpotSwapManager(privateKey, minimalSpotConfig);
4206
- }
4207
- const cfg = {
4208
- enabled: true,
4209
- defaultBridge: bridgeConfig.defaultBridge,
4210
- maxBridgeValueUSD: bridgeConfig.maxBridgeValueUSD,
4211
- fillTimeoutMs: bridgeConfig.fillTimeoutMs,
4212
- pollIntervalMs: bridgeConfig.pollIntervalMs
4213
- };
4214
- this.bridgeManager = new BridgeManager(this.spotManager.client, cfg);
4215
- console.log(`[runtime] Bridge initialized`);
4216
- } catch (err) {
4217
- console.error("[runtime] Failed to initialize Bridge:", err.message);
4218
- }
4219
- }
4220
- }
4221
- // ── TRADING LOOP ───────────────────────────────────────────
4222
- startTrading() {
4223
- if (this.tradingInterval) return;
4224
- this.mode = this.config.trading.mode === "paper" ? "paper" : "trading";
4225
- console.log(`[runtime] Trading started (${this.mode}, interval: ${this.config.trading.tradingIntervalMs}ms)`);
4226
- this.sendStatus();
4227
- this.signal.reportInfo("Trading Started", `Mode: ${this.mode}`);
4228
- this.runCycle();
4229
- this.tradingInterval = setInterval(() => {
4230
- this.runCycle();
4231
- }, this.config.trading.tradingIntervalMs);
4232
- }
4233
- stopTrading() {
4234
- if (this.tradingInterval) {
4235
- clearInterval(this.tradingInterval);
4236
- this.tradingInterval = null;
4237
- }
4238
- this.mode = "idle";
4239
- this.sendStatus();
4240
- console.log(`[runtime] Trading stopped`);
4241
- }
4242
- async runCycle() {
4243
- if (!this.running || !this.strategy) return;
4244
- if (this.cycleInProgress) {
4245
- console.log("[runtime] Skipping cycle \u2014 previous cycle still running");
4246
- return;
4247
- }
4248
- this.cycleInProgress = true;
4249
- this.cycleCount++;
4250
- this.lastCycleAt = Date.now();
4251
- try {
4252
- const prices = this.market.getPrices();
4253
- const positionSummary = this.positions.getSummary(prices);
4254
- const signals = await this.strategy({
4255
- llm: this.llm,
4256
- market: this.market,
4257
- position: positionSummary,
4258
- store: this.store,
4259
- config: this.config.trading,
4260
- log: (msg) => {
4261
- console.log(`[strategy] ${msg}`);
4262
- this.signal.reportInfo("Strategy Log", msg);
4263
- }
4264
- });
4265
- if (!Array.isArray(signals) || signals.length === 0) {
4266
- await this.pollPredictionFills();
4267
- this.sendStatus();
4268
- return;
4269
- }
4270
- const filtered = this.risk.filterSignals(signals, this.market, positionSummary.openPositions.length);
4271
- for (const sig of filtered) {
4272
- try {
4273
- await this.executeSignal(sig);
4274
- } catch (err) {
4275
- console.error(`[runtime] Trade execution error:`, err.message);
4276
- this.signal.reportError("Trade Error", err.message);
4277
- }
4278
- }
4279
- await this.pollPredictionFills();
4280
- } catch (err) {
4281
- console.error(`[runtime] Cycle error:`, err.message);
4282
- this.signal.reportError("Cycle Error", err.message);
4283
- this.mode = "idle";
4284
- } finally {
4285
- this.cycleInProgress = false;
4286
- }
4287
- this.sendStatus();
4288
- }
4289
- // ── SIGNAL EXECUTION ───────────────────────────────────────
4290
- async executeSignal(sig) {
4291
- const venue = sig.venue;
4292
- if (this.paper) {
4293
- const trade = this.paper.execute(sig, this.market);
4294
- if (trade) {
4295
- this.risk.recordTrade(trade.pnl ?? 0, trade.fee);
4296
- if (this.risk.isDailyLossLimitHit()) {
4297
- console.warn(`[runtime] Daily loss limit hit (paper) \u2014 stopping trading`);
4298
- this.signal.reportError("Daily Loss Limit", `Daily PnL: $${this.risk.getDailyPnL().toFixed(2)} exceeds limit`);
4299
- this.stopTrading();
4300
- }
4301
- this.signal.reportTrade({
4302
- ...sig,
4303
- price: trade.entryPrice,
4304
- fee: trade.fee,
4305
- venue: trade.venue,
4306
- venueFillId: trade.id,
4307
- venueTimestamp: new Date(trade.timestamp).toISOString()
4308
- });
4309
- }
4310
- return;
4311
- }
4312
- if (venue === "hyperliquid_perp" && this.hlOrders) {
4313
- await this.executeHyperliquidSignal(sig);
4314
- } else if (venue === "polymarket" && this.pmOrders) {
4315
- await this.executePolymarketSignal(sig);
4316
- } else if ((venue === "uniswap" || venue === "aerodrome" || venue === "sushiswap") && this.spotManager) {
4317
- await this.executeSpotSignal(sig);
4318
- } else if (venue === "across" && this.bridgeManager) {
4319
- await this.executeBridgeSignal(sig);
4320
- } else if (venue === "hyperliquid_deposit" && this.hlSigner) {
4321
- await this.executeHyperliquidDeposit(sig);
4322
- } else if (venue === "hyperliquid_withdraw" && this.hlSigner) {
4323
- await this.executeHyperliquidWithdraw(sig);
4324
- } else {
4325
- console.log(`[runtime] No executor for venue "${venue}" \u2014 signal dropped`);
4326
- }
4327
- }
4328
- async executeHyperliquidSignal(sig) {
4329
- if (!this.hlOrders) return;
4330
- const action = sig.side === "long" ? "open_long" : sig.side === "short" ? "open_short" : sig.side === "buy" ? "open_long" : "close_long";
4331
- const result = await this.hlOrders.placeOrder({
4332
- action,
4333
- instrument: sig.symbol,
4334
- size: sig.size,
4335
- price: sig.price,
4336
- leverage: sig.leverage ?? 1,
4337
- orderType: sig.orderType ?? "market",
4338
- reduceOnly: action.startsWith("close"),
4339
- confidence: sig.confidence ?? 1,
4340
- reasoning: sig.reasoning
4341
- });
4342
- if (result.success && result.status === "filled") {
4343
- console.log(`[runtime] HL order filled: ${sig.symbol} ${result.avgPrice}`);
4344
- } else if (result.success && result.status === "resting") {
4345
- console.log(`[runtime] HL order resting: ${sig.symbol} (oid: ${result.orderId})`);
4346
- } else {
4347
- console.warn(`[runtime] HL order failed: ${result.error}`);
4348
- this.signal.reportError("Perp Order Failed", `${sig.symbol}: ${result.error}`);
4349
- }
4350
- }
4351
- async executePolymarketSignal(sig) {
4352
- if (!this.pmOrders) return;
4353
- const isNo = sig.orderType === "no";
4354
- const outcomeIndex = isNo ? 1 : 0;
4355
- const isBuy = sig.side === "buy" || sig.side === "long";
4356
- const action = isBuy ? isNo ? "buy_no" : "buy_yes" : isNo ? "sell_no" : "sell_yes";
4357
- const result = await this.pmOrders.executeSignal({
4358
- action,
4359
- marketConditionId: sig.symbol,
4360
- marketQuestion: sig.reasoning ?? sig.symbol,
4361
- outcomeIndex,
4362
- amount: sig.size,
4363
- limitPrice: sig.price,
4364
- orderType: "limit",
4365
- confidence: sig.confidence ?? 1,
4366
- reasoning: sig.reasoning
4367
- });
4368
- if (result.success) {
4369
- console.log(`[runtime] PM order placed: ${sig.symbol}`);
4370
- } else {
4371
- console.warn(`[runtime] PM order failed: ${result.error}`);
4372
- this.signal.reportError("Prediction Order Failed", `${sig.symbol}: ${result.error}`);
4373
- }
4374
- }
4375
- async executeSpotSignal(sig) {
4376
- if (!this.spotManager) return;
4377
- const chain = sig.chain ?? this.config.venues?.spot?.defaultChain ?? "base";
4378
- const dex = sig.venue === "aerodrome" ? "aerodrome" : "uniswap";
4379
- const parts = sig.symbol.split("/");
4380
- const isBuy = sig.side === "buy" || sig.side === "long";
4381
- const tokenIn = isBuy ? parts[1] ?? "USDC" : parts[0] ?? sig.symbol;
4382
- const tokenOut = isBuy ? parts[0] ?? sig.symbol : parts[1] ?? "USDC";
4383
- const tokenInAddress = this.spotManager.resolveToken(tokenIn, chain);
4384
- const decimals = await this.spotManager.client.getDecimals(tokenInAddress, chain);
4385
- const amountIn = BigInt(Math.floor(sig.size * 10 ** decimals));
4386
- const result = await this.spotManager.executeSwap({
4387
- tokenIn,
4388
- tokenOut,
4389
- amountIn,
4390
- chain,
4391
- dex
4392
- });
4393
- if (result.success) {
4394
- const tokenOutSymbol = await this.spotManager.client.getSymbol(result.tokenOut, chain);
4395
- const tokenInSymbol = await this.spotManager.client.getSymbol(result.tokenIn, chain);
4396
- const tokenOutDecimals = await this.spotManager.client.getDecimals(result.tokenOut, chain);
4397
- const amountOutFloat = Number(result.amountOut) / 10 ** tokenOutDecimals;
4398
- const amountInFloat = Number(result.amountIn) / 10 ** decimals;
4399
- const tradeSignal = {
4400
- venue: result.dex,
4401
- chain,
4402
- symbol: `${parts[0] ?? sig.symbol}`,
4403
- side: sig.side,
4404
- size: isBuy ? amountOutFloat : amountInFloat,
4405
- price: result.effectivePrice,
4406
- fee: Number(result.gasCost) / 1e18,
4407
- venueFillId: result.txHash,
4408
- venueTimestamp: (/* @__PURE__ */ new Date()).toISOString()
4409
- };
4410
- const baseToken = parts[0] ?? sig.symbol;
4411
- let realizedPnL = 0;
4412
- if (isBuy) {
4413
- realizedPnL = this.positions.recordBuy(
4414
- baseToken,
4415
- amountOutFloat,
4416
- result.effectivePrice,
4417
- tradeSignal.fee,
4418
- result.dex,
4419
- chain,
4420
- result.txHash
4421
- );
4422
- } else {
4423
- realizedPnL = this.positions.recordSell(
4424
- baseToken,
4425
- amountInFloat,
4426
- result.effectivePrice,
4427
- tradeSignal.fee,
4428
- result.dex,
4429
- chain,
4430
- result.txHash
4431
- );
4432
- }
4433
- this.risk.recordTrade(realizedPnL, tradeSignal.fee);
4434
- if (this.risk.isDailyLossLimitHit()) {
4435
- console.warn(`[runtime] Daily loss limit hit \u2014 stopping trading`);
4436
- this.signal.reportError("Daily Loss Limit", `Daily PnL: $${this.risk.getDailyPnL().toFixed(2)} exceeds limit`);
4437
- this.stopTrading();
4438
- }
4439
- this.signal.reportSpotFill(tradeSignal);
4440
- console.log(`[runtime] Spot swap filled: ${tokenInSymbol} \u2192 ${tokenOutSymbol} on ${result.dex}/${chain}`);
4441
- } else {
4442
- console.warn(`[runtime] Spot swap failed: ${result.error}`);
4443
- this.signal.reportError("Spot Swap Failed", `${sig.symbol}: ${result.error}`);
4444
- }
4445
- }
4446
- async executeBridgeSignal(sig) {
4447
- if (!this.bridgeManager || !this.spotManager) return;
4448
- const toChain = sig.chain ?? "arbitrum";
4449
- const fromChain = sig.orderType ?? "base";
4450
- const tokenAddress = this.spotManager.resolveToken(sig.symbol, fromChain);
4451
- const decimals = await this.spotManager.client.getDecimals(tokenAddress, fromChain);
4452
- const amount = BigInt(Math.floor(sig.size * 10 ** decimals));
4453
- const result = await this.bridgeManager.bridge({
4454
- token: tokenAddress,
4455
- amount,
4456
- fromChain,
4457
- toChain
4458
- });
4459
- if (result.success) {
4460
- const tradeSignal = {
4461
- venue: "across",
4462
- chain: toChain,
4463
- symbol: sig.symbol,
4464
- side: "buy",
4465
- size: sig.size,
4466
- price: sig.price || 1,
4467
- fee: Number(result.fee) / 10 ** decimals,
4468
- venueFillId: result.depositTxHash,
4469
- venueTimestamp: (/* @__PURE__ */ new Date()).toISOString()
4470
- };
4471
- this.signal.reportBridgeFill(tradeSignal);
4472
- console.log(`[runtime] Bridge completed: ${fromChain} \u2192 ${toChain} via Across`);
4473
- } else {
4474
- console.warn(`[runtime] Bridge failed: ${result.error}`);
4475
- this.signal.reportError("Bridge Failed", `${sig.symbol} ${fromChain}\u2192${toChain}: ${result.error}`);
4476
- }
4477
- }
4478
- // ── HYPERLIQUID DEPOSIT / WITHDRAW ────────────────────────
4479
- /** Hyperliquid bridge contract on Arbitrum — accepts plain USDC transfers */
4480
- static HL_BRIDGE_CONTRACT = "0x2Df1c51E09aECF9cacB7bc98cB1742757f163dF7";
4481
- /**
4482
- * Deposit USDC into Hyperliquid by transferring to the bridge contract on Arbitrum.
4483
- * Signal format: venue='hyperliquid_deposit', size=amount in USDC, chain is ignored (always Arbitrum).
4484
- * The wallet must already have USDC + ETH for gas on Arbitrum.
4485
- */
4486
- async executeHyperliquidDeposit(sig) {
4487
- if (!this.spotManager) {
4488
- this.signal.reportError("HL Deposit Failed", "Spot manager not initialized (needed for chain clients)");
4489
- return;
4490
- }
4491
- const arbConfig = getChainConfig("arbitrum");
4492
- if (!arbConfig) {
4493
- this.signal.reportError("HL Deposit Failed", "Arbitrum chain config not found");
4494
- return;
4495
- }
4496
- const usdcAddress = arbConfig.usdcAddress;
4497
- const amount = BigInt(Math.floor(sig.size * 1e6));
4498
- const MIN_GAS_WEI2 = 100000000000000n;
4499
- try {
4500
- const gasBalance = await this.spotManager.client.getNativeBalance("arbitrum");
4501
- if (gasBalance < MIN_GAS_WEI2) {
4502
- this.signal.reportError("HL Deposit Failed", `Insufficient ETH for gas on Arbitrum. Balance: ${formatUnits(gasBalance, 18)} ETH. Need at least 0.0001 ETH.`);
4503
- return;
4504
- }
4505
- } catch {
4506
- }
4507
- try {
4508
- const usdcBalance = await this.spotManager.client.getBalance(usdcAddress, "arbitrum");
4509
- if (usdcBalance < amount) {
4510
- this.signal.reportError("HL Deposit Failed", `Insufficient USDC on Arbitrum. Have ${formatUnits(usdcBalance, 6)}, need ${formatUnits(amount, 6)}. Bridge USDC to Arbitrum first.`);
4511
- return;
4512
- }
4513
- } catch (err) {
4514
- this.signal.reportError("HL Deposit Failed", `Could not check USDC balance: ${err.message}`);
4515
- return;
4516
- }
4517
- try {
4518
- const { publicClient, walletClient } = this.spotManager.client.getClients("arbitrum");
4519
- const hash = await walletClient.writeContract({
4520
- address: usdcAddress,
4521
- abi: ERC20_ABI,
4522
- functionName: "transfer",
4523
- args: [_AgentRuntime.HL_BRIDGE_CONTRACT, amount]
4524
- });
4525
- const receipt = await publicClient.waitForTransactionReceipt({ hash });
4526
- if (receipt.status === "reverted") {
4527
- this.signal.reportError("HL Deposit Failed", `Transfer reverted: ${hash}`);
4528
- return;
4529
- }
4530
- console.log(`[runtime] HL deposit: ${formatUnits(amount, 6)} USDC \u2192 Hyperliquid (tx: ${hash})`);
4531
- this.signal.reportInfo("HL Deposit", `Deposited ${formatUnits(amount, 6)} USDC to Hyperliquid`);
4532
- } catch (err) {
4533
- console.error("[runtime] HL deposit failed:", err.message);
4534
- this.signal.reportError("HL Deposit Failed", err.message);
4535
- }
4536
- }
4537
- /**
4538
- * Withdraw USDC from Hyperliquid to the wallet on Arbitrum.
4539
- * Signal format: venue='hyperliquid_withdraw', size=amount in USDC.
4540
- * Uses the withdraw3 EIP-712 signing scheme.
4541
- */
4542
- async executeHyperliquidWithdraw(sig) {
4543
- if (!this.hlSigner || !this.hlClient) {
4544
- this.signal.reportError("HL Withdraw Failed", "Hyperliquid signer/client not initialized");
4545
- return;
4546
- }
4547
- const destination = this.hlSigner.getAddress();
4548
- const amount = sig.size.toString();
4549
- try {
4550
- const { action, signature, nonce } = await this.hlSigner.signWithdraw(destination, amount);
4551
- const apiUrl = this.config.venues?.hyperliquid_perp?.apiUrl ?? "https://api.hyperliquid.xyz";
4552
- const resp = await fetch(`${apiUrl}/exchange`, {
4553
- method: "POST",
4554
- headers: { "Content-Type": "application/json" },
4555
- body: JSON.stringify({ action, nonce, signature, vaultAddress: null })
4556
- });
4557
- if (!resp.ok) {
4558
- const text = await resp.text();
4559
- throw new Error(`HL Exchange API error: ${resp.status} ${text}`);
4560
- }
4561
- const data = await resp.json();
4562
- if (data.status !== "ok") {
4563
- throw new Error(`HL withdraw3 failed: ${JSON.stringify(data)}`);
4564
- }
4565
- console.log(`[runtime] HL withdrawal: ${amount} USDC \u2192 ${destination} on Arbitrum`);
4566
- this.signal.reportInfo("HL Withdrawal", `Withdrew ${amount} USDC from Hyperliquid to ${destination}`);
4567
- } catch (err) {
4568
- console.error("[runtime] HL withdrawal failed:", err.message);
4569
- this.signal.reportError("HL Withdraw Failed", err.message);
4570
- }
4571
- }
4572
- // ── FILL HANDLING ──────────────────────────────────────────
4573
- handleHyperliquidFill(fill) {
4574
- const tradeSignal = {
4575
- venue: "hyperliquid_perp",
4576
- symbol: fill.coin,
4577
- side: fill.side === "B" ? "long" : "short",
4578
- size: parseFloat(fill.sz),
4579
- price: parseFloat(fill.px),
4580
- fee: parseFloat(fill.fee),
4581
- venueFillId: fill.hash,
4582
- venueTimestamp: new Date(fill.time).toISOString(),
4583
- orderType: fill.isMaker ? "limit" : "market"
4584
- };
4585
- const action = fill.side === "B" ? "buy" : "sell";
4586
- const fee = parseFloat(fill.fee);
4587
- let realizedPnL = 0;
4588
- if (action === "buy") {
4589
- realizedPnL = this.positions.recordBuy(
4590
- fill.coin,
4591
- parseFloat(fill.sz),
4592
- parseFloat(fill.px),
4593
- fee,
4594
- "hyperliquid_perp",
4595
- void 0,
4596
- fill.hash
4597
- );
4598
- } else {
4599
- realizedPnL = this.positions.recordSell(
4600
- fill.coin,
4601
- parseFloat(fill.sz),
4602
- parseFloat(fill.px),
4603
- fee,
4604
- "hyperliquid_perp",
4605
- void 0,
4606
- fill.hash
4607
- );
4608
- }
4609
- this.risk.recordTrade(realizedPnL, fee);
4610
- if (this.risk.isDailyLossLimitHit()) {
4611
- console.warn(`[runtime] Daily loss limit hit \u2014 stopping trading`);
4612
- this.signal.reportError("Daily Loss Limit", `Daily PnL: $${this.risk.getDailyPnL().toFixed(2)} exceeds limit of -$${this.risk.getDailyLossLimit().toFixed(2)}`);
4613
- this.stopTrading();
4614
- }
4615
- this.signal.reportPerpFill(tradeSignal);
4616
- }
4617
- async pollPredictionFills() {
4618
- if (!this.pmOrders) return;
4619
- try {
4620
- const newFills = await this.pmOrders.pollNewFills();
4621
- for (const fill of newFills) {
4622
- const tradeSignal = {
4623
- venue: "polymarket",
4624
- chain: "polygon",
4625
- symbol: encodePredictionInstrument(fill.marketConditionId, fill.outcomeIndex),
4626
- side: fill.side === "BUY" ? "buy" : "sell",
4627
- size: parseFloat(fill.size),
4628
- price: parseFloat(fill.price),
4629
- fee: parseFloat(fill.fee),
4630
- venueFillId: fill.tradeId,
4631
- venueTimestamp: new Date(fill.timestamp).toISOString()
4632
- };
4633
- const fillFee = parseFloat(fill.fee);
4634
- let realizedPnL = 0;
4635
- if (fill.side === "BUY") {
4636
- realizedPnL = this.positions.recordBuy(
4637
- tradeSignal.symbol,
4638
- parseFloat(fill.size),
4639
- parseFloat(fill.price),
4640
- fillFee,
4641
- "polymarket",
4642
- "polygon",
4643
- fill.tradeId
4644
- );
4645
- } else {
4646
- realizedPnL = this.positions.recordSell(
4647
- tradeSignal.symbol,
4648
- parseFloat(fill.size),
4649
- parseFloat(fill.price),
4650
- fillFee,
4651
- "polymarket",
4652
- "polygon",
4653
- fill.tradeId
4654
- );
4655
- }
4656
- this.risk.recordTrade(realizedPnL, fillFee);
4657
- if (this.risk.isDailyLossLimitHit()) {
4658
- console.warn(`[runtime] Daily loss limit hit \u2014 stopping trading`);
4659
- this.signal.reportError("Daily Loss Limit", `Daily PnL: $${this.risk.getDailyPnL().toFixed(2)} exceeds limit`);
4660
- this.stopTrading();
4661
- }
4662
- this.signal.reportPredictionFill(tradeSignal);
4663
- }
4664
- } catch (err) {
4665
- console.warn("[runtime] Prediction fill poll error:", err.message);
4666
- }
4667
- }
4668
- // ── COMMANDS ───────────────────────────────────────────────
4669
- handleCommand(command) {
4670
- console.log(`[runtime] Command received: ${command.type} (${command.id})`);
4671
- switch (command.type) {
4672
- case "start_trading":
4673
- this.startTrading();
4674
- this.relay.sendCommandAck(command.id, true, "Trading started");
4675
- break;
4676
- case "stop_trading":
4677
- this.stopTrading();
4678
- this.relay.sendCommandAck(command.id, true, "Trading stopped");
4679
- break;
4680
- case "pause_trading":
4681
- this.stopTrading();
4682
- this.relay.sendCommandAck(command.id, true, "Trading paused");
4683
- break;
4684
- case "update_risk_params":
4685
- if (command.params) {
4686
- this.risk.updateParams(command.params);
4687
- this.sendStatus();
4688
- this.relay.sendCommandAck(command.id, true, "Risk params updated");
4689
- } else {
4690
- this.relay.sendCommandAck(command.id, false, "No params provided");
4691
- }
4692
- break;
4693
- case "get_status":
4694
- this.sendStatus();
4695
- this.relay.sendCommandAck(command.id, true);
4696
- break;
4697
- case "reload_config":
4698
- this.reloadConfig(command);
4699
- break;
4700
- default:
4701
- console.warn(`[runtime] Unknown command: ${command.type}`);
4702
- this.relay.sendCommandAck(command.id, false, `Unknown command: ${command.type}`);
4703
- }
4704
- }
4705
- async reloadConfig(command) {
4706
- try {
4707
- const apiBase = this.config.apiUrl || this.config.relay.url.replace(/\/ws\/.*/, "");
4708
- const res = await fetch(`${apiBase}/v1/agents/${this.config.agentId}`, {
4709
- headers: { "Authorization": `Bearer ${this.config.apiToken}` }
4710
- });
4711
- if (!res.ok) {
4712
- throw new Error(`API returned ${res.status}`);
4713
- }
4714
- const agent = await res.json();
4715
- if (agent.config) {
4716
- const cfg = agent.config;
4717
- const risk = cfg.risk;
4718
- if (risk) {
4719
- const updates = {};
4720
- if (typeof risk.maxPositionSize === "number") updates.maxPositionSizeBps = risk.maxPositionSize * 100;
4721
- if (typeof risk.maxDailyLoss === "number") updates.maxDailyLossBps = risk.maxDailyLoss * 100;
4722
- if (typeof risk.maxConcurrentPositions === "number") updates.maxConcurrentPositions = risk.maxConcurrentPositions;
4723
- if (typeof risk.slippageTolerance === "number") updates.maxSlippageBps = risk.slippageTolerance * 100;
4724
- if (typeof risk.tradingInterval === "number") {
4725
- this.config.trading.tradingIntervalMs = risk.tradingInterval * 1e3;
4726
- }
4727
- if (Object.keys(updates).length > 0) {
4728
- this.risk.updateParams(updates);
4729
- }
4730
- }
4731
- console.log("[runtime] Config reloaded from API");
4732
- this.sendStatus();
4733
- }
4734
- this.relay.sendCommandAck(command.id, true, "Config reloaded");
4735
- } catch (err) {
4736
- console.error("[runtime] Config reload failed:", err.message);
4737
- this.relay.sendCommandAck(command.id, false, err.message);
4738
- }
4739
- }
4740
- // ── STATUS ─────────────────────────────────────────────────
4741
- sendStatus() {
4742
- const status = {
4743
- mode: this.mode,
4744
- agentId: this.config.agentId,
4745
- walletAddress: this.walletAddress || void 0,
4746
- sdkVersion: SDK_VERSION,
4747
- cycleCount: this.cycleCount,
4748
- lastCycleAt: this.lastCycleAt,
4749
- tradingIntervalMs: this.config.trading.tradingIntervalMs,
4750
- llm: {
4751
- provider: this.config.llm.provider,
4752
- model: this.config.llm.model || "default"
4753
- },
4754
- risk: {
4755
- dailyPnL: this.risk.getDailyPnL(),
4756
- dailyLossLimit: this.risk.getDailyLossLimit(),
4757
- isLimitHit: this.risk.isDailyLossLimitHit()
4758
- },
4759
- positions: {
4760
- openPositions: this.positions.getPositions().length,
4761
- totalUnrealizedPnL: 0,
4762
- totalRealizedPnL: this.positions.getRealizedPnL()
4763
- },
4764
- venues: {
4765
- hyperliquid: {
4766
- enabled: !!this.hlClient,
4767
- trading: !!this.hlOrders && this.mode === "trading"
4768
- },
4769
- polymarket: {
4770
- enabled: !!this.pmClient,
4771
- trading: !!this.pmOrders && this.mode === "trading"
4772
- },
4773
- spot: {
4774
- enabled: !!this.spotManager,
4775
- trading: !!this.spotManager && this.mode === "trading"
4776
- },
4777
- bridge: {
4778
- enabled: !!this.bridgeManager
4779
- }
4780
- }
4781
- };
4782
- if (this.paper) {
4783
- const metrics = this.paper.getMetrics();
4784
- status.paper = {
4785
- active: true,
4786
- simulatedValue: this.paper.getEquity(),
4787
- simulatedPnLPct: metrics.totalReturn * 100
4788
- };
4789
- status.portfolioValue = this.paper.getEquity();
4790
- }
4791
- this.relay.sendHeartbeat(status);
4792
- }
4793
- };
4794
-
4795
- export {
4796
- loadConfig,
4797
- generateSampleConfig,
4798
- writeSampleConfig,
4799
- CHAIN_CONFIGS,
4800
- getChainConfig,
4801
- DEFAULT_SPOT_CONFIG,
4802
- RelayClient,
4803
- SignalReporter,
4804
- FileStore,
4805
- PositionTracker,
4806
- createLLMAdapter,
4807
- getTemplate,
4808
- listTemplates,
4809
- loadStrategy,
4810
- RiskManager,
4811
- MarketDataService,
4812
- PaperExecutor,
4813
- HyperliquidClient,
4814
- HYPERLIQUID_DOMAIN,
4815
- HYPERLIQUID_USER_DOMAIN,
4816
- USER_ACTION_TYPES,
4817
- getNextNonce,
4818
- HyperliquidSigner,
4819
- HyperliquidOrderManager,
4820
- HyperliquidPositionManager,
4821
- HyperliquidWebSocket,
4822
- encodePredictionInstrument,
4823
- decodePredictionInstrument,
4824
- PolymarketClient,
4825
- PolymarketOrderManager,
4826
- SpotDEXClient,
4827
- UniswapAdapter,
4828
- AerodromeAdapter,
4829
- SpotSwapManager,
4830
- DEFAULT_BRIDGE_CONFIG,
4831
- AcrossAdapter,
4832
- BridgeManager,
4833
- AgentRuntime
4834
- };