@exagent/agent 0.1.0 → 0.1.2

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.
@@ -0,0 +1,1615 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/llm/base.ts
9
+ var BaseLLMAdapter = class {
10
+ config;
11
+ constructor(config) {
12
+ this.config = config;
13
+ }
14
+ getMetadata() {
15
+ return {
16
+ provider: this.config.provider,
17
+ model: this.config.model || "unknown",
18
+ isLocal: this.config.provider === "ollama"
19
+ };
20
+ }
21
+ /**
22
+ * Format model name for display
23
+ */
24
+ getDisplayModel() {
25
+ if (this.config.provider === "ollama") {
26
+ return `Local (${this.config.model || "ollama"})`;
27
+ }
28
+ return this.config.model || this.config.provider;
29
+ }
30
+ };
31
+
32
+ // src/llm/openai.ts
33
+ import OpenAI from "openai";
34
+ var OpenAIAdapter = class extends BaseLLMAdapter {
35
+ client;
36
+ constructor(config) {
37
+ super(config);
38
+ if (!config.apiKey && !config.endpoint) {
39
+ throw new Error("OpenAI API key or custom endpoint required");
40
+ }
41
+ this.client = new OpenAI({
42
+ apiKey: config.apiKey || "not-needed-for-custom",
43
+ baseURL: config.endpoint
44
+ });
45
+ }
46
+ async chat(messages) {
47
+ try {
48
+ const response = await this.client.chat.completions.create({
49
+ model: this.config.model || "gpt-4.1",
50
+ messages: messages.map((m) => ({
51
+ role: m.role,
52
+ content: m.content
53
+ })),
54
+ temperature: this.config.temperature,
55
+ max_tokens: this.config.maxTokens
56
+ });
57
+ const choice = response.choices[0];
58
+ if (!choice || !choice.message) {
59
+ throw new Error("No response from OpenAI");
60
+ }
61
+ return {
62
+ content: choice.message.content || "",
63
+ usage: response.usage ? {
64
+ promptTokens: response.usage.prompt_tokens,
65
+ completionTokens: response.usage.completion_tokens,
66
+ totalTokens: response.usage.total_tokens
67
+ } : void 0
68
+ };
69
+ } catch (error) {
70
+ if (error instanceof OpenAI.APIError) {
71
+ throw new Error(`OpenAI API error: ${error.message}`);
72
+ }
73
+ throw error;
74
+ }
75
+ }
76
+ };
77
+
78
+ // src/llm/anthropic.ts
79
+ var AnthropicAdapter = class extends BaseLLMAdapter {
80
+ apiKey;
81
+ baseUrl;
82
+ constructor(config) {
83
+ super(config);
84
+ if (!config.apiKey) {
85
+ throw new Error("Anthropic API key required");
86
+ }
87
+ this.apiKey = config.apiKey;
88
+ this.baseUrl = config.endpoint || "https://api.anthropic.com";
89
+ }
90
+ async chat(messages) {
91
+ const systemMessage = messages.find((m) => m.role === "system");
92
+ const chatMessages = messages.filter((m) => m.role !== "system");
93
+ const body = {
94
+ model: this.config.model || "claude-opus-4-5-20251101",
95
+ max_tokens: this.config.maxTokens || 4096,
96
+ temperature: this.config.temperature,
97
+ system: systemMessage?.content,
98
+ messages: chatMessages.map((m) => ({
99
+ role: m.role,
100
+ content: m.content
101
+ }))
102
+ };
103
+ const response = await fetch(`${this.baseUrl}/v1/messages`, {
104
+ method: "POST",
105
+ headers: {
106
+ "Content-Type": "application/json",
107
+ "x-api-key": this.apiKey,
108
+ "anthropic-version": "2023-06-01"
109
+ },
110
+ body: JSON.stringify(body)
111
+ });
112
+ if (!response.ok) {
113
+ const error = await response.text();
114
+ throw new Error(`Anthropic API error: ${response.status} - ${error}`);
115
+ }
116
+ const data = await response.json();
117
+ const content = data.content?.map(
118
+ (block) => block.type === "text" ? block.text : ""
119
+ ).join("") || "";
120
+ return {
121
+ content,
122
+ usage: data.usage ? {
123
+ promptTokens: data.usage.input_tokens,
124
+ completionTokens: data.usage.output_tokens,
125
+ totalTokens: data.usage.input_tokens + data.usage.output_tokens
126
+ } : void 0
127
+ };
128
+ }
129
+ };
130
+
131
+ // src/llm/ollama.ts
132
+ var OllamaAdapter = class extends BaseLLMAdapter {
133
+ baseUrl;
134
+ constructor(config) {
135
+ super(config);
136
+ this.baseUrl = config.endpoint || "http://localhost:11434";
137
+ }
138
+ /**
139
+ * Check if Ollama is running and the model is available
140
+ */
141
+ async healthCheck() {
142
+ try {
143
+ const response = await fetch(`${this.baseUrl}/api/tags`);
144
+ if (!response.ok) {
145
+ throw new Error("Ollama server not responding");
146
+ }
147
+ const data = await response.json();
148
+ const models = data.models?.map((m) => m.name) || [];
149
+ if (this.config.model && !models.some((m) => m.startsWith(this.config.model))) {
150
+ console.warn(
151
+ `Model "${this.config.model}" not found locally. Available: ${models.join(", ")}`
152
+ );
153
+ console.warn(`Run: ollama pull ${this.config.model}`);
154
+ }
155
+ } catch (error) {
156
+ throw new Error(
157
+ `Cannot connect to Ollama at ${this.baseUrl}. Make sure Ollama is running (ollama serve) or install it from https://ollama.com`
158
+ );
159
+ }
160
+ }
161
+ async chat(messages) {
162
+ const body = {
163
+ model: this.config.model || "llama3.2",
164
+ messages: messages.map((m) => ({
165
+ role: m.role,
166
+ content: m.content
167
+ })),
168
+ stream: false,
169
+ options: {
170
+ temperature: this.config.temperature,
171
+ num_predict: this.config.maxTokens
172
+ }
173
+ };
174
+ const response = await fetch(`${this.baseUrl}/api/chat`, {
175
+ method: "POST",
176
+ headers: {
177
+ "Content-Type": "application/json"
178
+ },
179
+ body: JSON.stringify(body)
180
+ });
181
+ if (!response.ok) {
182
+ const error = await response.text();
183
+ throw new Error(`Ollama API error: ${response.status} - ${error}`);
184
+ }
185
+ const data = await response.json();
186
+ return {
187
+ content: data.message?.content || "",
188
+ usage: data.eval_count ? {
189
+ promptTokens: data.prompt_eval_count || 0,
190
+ completionTokens: data.eval_count,
191
+ totalTokens: (data.prompt_eval_count || 0) + data.eval_count
192
+ } : void 0
193
+ };
194
+ }
195
+ getMetadata() {
196
+ return {
197
+ provider: "ollama",
198
+ model: this.config.model || "llama3.2",
199
+ isLocal: true
200
+ };
201
+ }
202
+ };
203
+
204
+ // src/llm/google.ts
205
+ var GoogleAdapter = class extends BaseLLMAdapter {
206
+ apiKey;
207
+ baseUrl;
208
+ constructor(config) {
209
+ super(config);
210
+ if (!config.apiKey) {
211
+ throw new Error("Google AI API key required");
212
+ }
213
+ this.apiKey = config.apiKey;
214
+ this.baseUrl = config.endpoint || "https://generativelanguage.googleapis.com/v1beta";
215
+ }
216
+ async chat(messages) {
217
+ const model = this.config.model || "gemini-2.5-flash";
218
+ const systemMessage = messages.find((m) => m.role === "system");
219
+ const chatMessages = messages.filter((m) => m.role !== "system");
220
+ const contents = chatMessages.map((m) => ({
221
+ role: m.role === "assistant" ? "model" : "user",
222
+ parts: [{ text: m.content }]
223
+ }));
224
+ const body = {
225
+ contents,
226
+ generationConfig: {
227
+ temperature: this.config.temperature,
228
+ maxOutputTokens: this.config.maxTokens || 4096
229
+ }
230
+ };
231
+ if (systemMessage) {
232
+ body.systemInstruction = {
233
+ parts: [{ text: systemMessage.content }]
234
+ };
235
+ }
236
+ const url = `${this.baseUrl}/models/${model}:generateContent?key=${this.apiKey}`;
237
+ const response = await fetch(url, {
238
+ method: "POST",
239
+ headers: {
240
+ "Content-Type": "application/json"
241
+ },
242
+ body: JSON.stringify(body)
243
+ });
244
+ if (!response.ok) {
245
+ const error = await response.text();
246
+ throw new Error(`Google AI API error: ${response.status} - ${error}`);
247
+ }
248
+ const data = await response.json();
249
+ const candidate = data.candidates?.[0];
250
+ if (!candidate?.content?.parts) {
251
+ throw new Error("No response from Google AI");
252
+ }
253
+ const content = candidate.content.parts.map((part) => part.text || "").join("");
254
+ const usageMetadata = data.usageMetadata;
255
+ return {
256
+ content,
257
+ usage: usageMetadata ? {
258
+ promptTokens: usageMetadata.promptTokenCount || 0,
259
+ completionTokens: usageMetadata.candidatesTokenCount || 0,
260
+ totalTokens: usageMetadata.totalTokenCount || 0
261
+ } : void 0
262
+ };
263
+ }
264
+ };
265
+
266
+ // src/llm/adapter.ts
267
+ async function createLLMAdapter(config) {
268
+ switch (config.provider) {
269
+ case "openai":
270
+ return new OpenAIAdapter(config);
271
+ case "anthropic":
272
+ return new AnthropicAdapter(config);
273
+ case "google":
274
+ return new GoogleAdapter(config);
275
+ case "ollama":
276
+ const adapter = new OllamaAdapter(config);
277
+ await adapter.healthCheck();
278
+ return adapter;
279
+ case "custom":
280
+ return new OpenAIAdapter({
281
+ ...config,
282
+ endpoint: config.endpoint
283
+ });
284
+ default:
285
+ throw new Error(`Unsupported LLM provider: ${config.provider}`);
286
+ }
287
+ }
288
+
289
+ // src/strategy/loader.ts
290
+ import { existsSync } from "fs";
291
+ import { join } from "path";
292
+ import { spawn } from "child_process";
293
+ async function loadStrategy(strategyPath) {
294
+ const basePath = strategyPath || process.env.EXAGENT_STRATEGY || "strategy";
295
+ const tsPath = basePath.endsWith(".ts") || basePath.endsWith(".js") ? basePath : `${basePath}.ts`;
296
+ const jsPath = basePath.endsWith(".ts") || basePath.endsWith(".js") ? basePath.replace(".ts", ".js") : `${basePath}.js`;
297
+ const fullTsPath = tsPath.startsWith("/") ? tsPath : join(process.cwd(), tsPath);
298
+ const fullJsPath = jsPath.startsWith("/") ? jsPath : join(process.cwd(), jsPath);
299
+ if (existsSync(fullTsPath) && fullTsPath.endsWith(".ts")) {
300
+ try {
301
+ const module = await loadTypeScriptModule(fullTsPath);
302
+ if (typeof module.generateSignals !== "function") {
303
+ throw new Error("Strategy must export a generateSignals function");
304
+ }
305
+ console.log(`Loaded custom strategy from ${tsPath}`);
306
+ return module.generateSignals;
307
+ } catch (error) {
308
+ console.error(`Failed to load strategy from ${tsPath}:`, error);
309
+ throw error;
310
+ }
311
+ }
312
+ if (existsSync(fullJsPath)) {
313
+ try {
314
+ const module = await import(fullJsPath);
315
+ if (typeof module.generateSignals !== "function") {
316
+ throw new Error("Strategy must export a generateSignals function");
317
+ }
318
+ console.log(`Loaded custom strategy from ${jsPath}`);
319
+ return module.generateSignals;
320
+ } catch (error) {
321
+ console.error(`Failed to load strategy from ${jsPath}:`, error);
322
+ throw error;
323
+ }
324
+ }
325
+ console.log("No custom strategy found, using default (hold) strategy");
326
+ return defaultStrategy;
327
+ }
328
+ async function loadTypeScriptModule(path) {
329
+ try {
330
+ const tsxPath = __require.resolve("tsx");
331
+ const { pathToFileURL } = await import("url");
332
+ const result = await new Promise((resolve, reject) => {
333
+ const child = spawn(
334
+ process.execPath,
335
+ [
336
+ "--import",
337
+ "tsx/esm",
338
+ "-e",
339
+ `import('${pathToFileURL(path).href}').then(m => console.log(JSON.stringify({ exports: Object.keys(m) }))).catch(e => console.error('ERROR:', e.message))`
340
+ ],
341
+ {
342
+ cwd: process.cwd(),
343
+ env: process.env,
344
+ stdio: ["pipe", "pipe", "pipe"]
345
+ }
346
+ );
347
+ let stdout = "";
348
+ let stderr = "";
349
+ child.stdout.on("data", (data) => stdout += data.toString());
350
+ child.stderr.on("data", (data) => stderr += data.toString());
351
+ child.on("close", (code) => {
352
+ if (code !== 0 || stderr.includes("ERROR:")) {
353
+ reject(new Error(`Failed to load TypeScript: ${stderr || "Unknown error"}`));
354
+ } else {
355
+ resolve(stdout);
356
+ }
357
+ });
358
+ });
359
+ const tsx = await import("tsx/esm/api");
360
+ const unregister = tsx.register();
361
+ try {
362
+ const module = await import(path);
363
+ return module;
364
+ } finally {
365
+ unregister();
366
+ }
367
+ } catch (error) {
368
+ if (error.code === "MODULE_NOT_FOUND" || error.message.includes("Cannot find module")) {
369
+ throw new Error(
370
+ `Cannot load TypeScript strategy. Please either:
371
+ 1. Rename your strategy.ts to strategy.js (remove type annotations)
372
+ 2. Or compile it: npx tsc strategy.ts --outDir . --esModuleInterop
373
+ 3. Or install tsx: npm install tsx`
374
+ );
375
+ }
376
+ throw error;
377
+ }
378
+ }
379
+ var defaultStrategy = async (_marketData, _llm, _config) => {
380
+ return [];
381
+ };
382
+ function validateStrategy(fn) {
383
+ return typeof fn === "function";
384
+ }
385
+
386
+ // src/strategy/templates.ts
387
+ var STRATEGY_TEMPLATES = [
388
+ {
389
+ id: "momentum",
390
+ name: "Momentum Trader",
391
+ description: "Follows price trends and momentum indicators. Buys assets with strong upward momentum.",
392
+ riskLevel: "medium",
393
+ riskWarnings: [
394
+ "Momentum strategies can suffer significant losses during trend reversals",
395
+ "High volatility markets may generate false signals",
396
+ "Past performance does not guarantee future results",
397
+ "This strategy may underperform in sideways markets"
398
+ ],
399
+ systemPrompt: `You are an AI trading analyst specializing in momentum trading strategies.
400
+
401
+ Your role is to analyze market data and identify momentum-based trading opportunities.
402
+
403
+ IMPORTANT CONSTRAINTS:
404
+ - Only recommend trades when there is clear momentum evidence
405
+ - Always consider risk/reward ratios
406
+ - Never recommend more than the configured position size limits
407
+ - Be conservative with confidence scores
408
+
409
+ When analyzing data, look for:
410
+ 1. Price trends (higher highs, higher lows for uptrends)
411
+ 2. Volume confirmation (increasing volume on moves)
412
+ 3. Relative strength vs market benchmarks
413
+
414
+ Respond with JSON in this format:
415
+ {
416
+ "analysis": "Brief market analysis",
417
+ "signals": [
418
+ {
419
+ "action": "buy" | "sell" | "hold",
420
+ "tokenIn": "0x...",
421
+ "tokenOut": "0x...",
422
+ "percentage": 0-100,
423
+ "confidence": 0-1,
424
+ "reasoning": "Why this trade"
425
+ }
426
+ ]
427
+ }`,
428
+ exampleCode: `import { StrategyFunction, MarketData, TradeSignal, LLMAdapter, AgentConfig } from '@exagent/agent';
429
+
430
+ export const generateSignals: StrategyFunction = async (
431
+ marketData: MarketData,
432
+ llm: LLMAdapter,
433
+ config: AgentConfig
434
+ ): Promise<TradeSignal[]> => {
435
+ const response = await llm.chat([
436
+ { role: 'system', content: MOMENTUM_SYSTEM_PROMPT },
437
+ { role: 'user', content: JSON.stringify({
438
+ prices: marketData.prices,
439
+ balances: formatBalances(marketData.balances),
440
+ portfolioValue: marketData.portfolioValue,
441
+ })}
442
+ ]);
443
+
444
+ // Parse LLM response and convert to TradeSignals
445
+ const parsed = JSON.parse(response.content);
446
+ return parsed.signals.map(convertToTradeSignal);
447
+ };`
448
+ },
449
+ {
450
+ id: "value",
451
+ name: "Value Investor",
452
+ description: "Looks for undervalued assets based on fundamentals. Takes long-term positions.",
453
+ riskLevel: "low",
454
+ riskWarnings: [
455
+ "Value traps can result in prolonged losses",
456
+ "Requires patience - may underperform for extended periods",
457
+ "Fundamental analysis may not apply well to all crypto assets",
458
+ "Market sentiment can override fundamentals for long periods"
459
+ ],
460
+ systemPrompt: `You are an AI trading analyst specializing in value investing.
461
+
462
+ Your role is to identify undervalued assets with strong fundamentals.
463
+
464
+ IMPORTANT CONSTRAINTS:
465
+ - Focus on long-term value, not short-term price movements
466
+ - Only recommend assets with clear value propositions
467
+ - Consider protocol revenue, TVL, active users, developer activity
468
+ - Be very selective - quality over quantity
469
+
470
+ When analyzing, consider:
471
+ 1. Protocol fundamentals (revenue, TVL, user growth)
472
+ 2. Token economics (supply schedule, utility)
473
+ 3. Competitive positioning
474
+ 4. Valuation relative to peers
475
+
476
+ Respond with JSON in this format:
477
+ {
478
+ "analysis": "Brief fundamental analysis",
479
+ "signals": [
480
+ {
481
+ "action": "buy" | "sell" | "hold",
482
+ "tokenIn": "0x...",
483
+ "tokenOut": "0x...",
484
+ "percentage": 0-100,
485
+ "confidence": 0-1,
486
+ "reasoning": "Fundamental thesis"
487
+ }
488
+ ]
489
+ }`,
490
+ exampleCode: `import { StrategyFunction } from '@exagent/agent';
491
+
492
+ export const generateSignals: StrategyFunction = async (marketData, llm, config) => {
493
+ // Value strategy runs less frequently
494
+ const response = await llm.chat([
495
+ { role: 'system', content: VALUE_SYSTEM_PROMPT },
496
+ { role: 'user', content: JSON.stringify(marketData) }
497
+ ]);
498
+
499
+ return parseSignals(response.content);
500
+ };`
501
+ },
502
+ {
503
+ id: "arbitrage",
504
+ name: "Arbitrage Hunter",
505
+ description: "Looks for price discrepancies across DEXs. Requires fast execution.",
506
+ riskLevel: "high",
507
+ riskWarnings: [
508
+ "Arbitrage opportunities are highly competitive - professional bots dominate",
509
+ "Slippage and gas costs can eliminate profits",
510
+ "MEV bots may front-run your transactions",
511
+ "Requires very fast execution and may not be profitable with standard infrastructure",
512
+ "This strategy is generally NOT recommended for beginners"
513
+ ],
514
+ systemPrompt: `You are an AI trading analyst specializing in arbitrage detection.
515
+
516
+ Your role is to identify price discrepancies that may offer arbitrage opportunities.
517
+
518
+ IMPORTANT CONSTRAINTS:
519
+ - Account for gas costs in all calculations
520
+ - Account for slippage (assume 0.3% minimum)
521
+ - Only flag opportunities with >1% net profit potential
522
+ - Consider MEV risk - assume some profit extraction
523
+
524
+ This is an advanced strategy with high competition.
525
+
526
+ Respond with JSON in this format:
527
+ {
528
+ "opportunities": [
529
+ {
530
+ "description": "What the arbitrage is",
531
+ "expectedProfit": "Net profit after costs",
532
+ "confidence": 0-1,
533
+ "warning": "Risks specific to this opportunity"
534
+ }
535
+ ]
536
+ }`,
537
+ exampleCode: `// Note: Pure arbitrage requires specialized infrastructure
538
+ // This template is for educational purposes
539
+
540
+ import { StrategyFunction } from '@exagent/agent';
541
+
542
+ export const generateSignals: StrategyFunction = async (marketData, llm, config) => {
543
+ // Arbitrage requires real-time price feeds from multiple sources
544
+ // Standard LLM-based analysis is too slow for most arbitrage
545
+ console.warn('Arbitrage strategy requires specialized infrastructure');
546
+ return [];
547
+ };`
548
+ },
549
+ {
550
+ id: "custom",
551
+ name: "Custom Strategy",
552
+ description: "Build your own strategy from scratch. Full control over logic and prompts.",
553
+ riskLevel: "extreme",
554
+ riskWarnings: [
555
+ "Custom strategies have no guardrails - you are fully responsible",
556
+ "LLMs can hallucinate or make errors - always validate outputs",
557
+ "Test thoroughly on testnet before using real funds",
558
+ "Consider edge cases: what happens if the LLM returns invalid JSON?",
559
+ "Your prompts and strategy logic are your competitive advantage - protect them",
560
+ "Agents may not behave exactly as expected based on your prompts"
561
+ ],
562
+ systemPrompt: `// Define your own system prompt here
563
+
564
+ You are a trading AI. Analyze the market data and provide trading signals.
565
+
566
+ // Add your specific instructions, constraints, and output format.
567
+
568
+ Respond with JSON:
569
+ {
570
+ "signals": []
571
+ }`,
572
+ exampleCode: `import { StrategyFunction, MarketData, TradeSignal, LLMAdapter, AgentConfig } from '@exagent/agent';
573
+
574
+ /**
575
+ * Custom Strategy Template
576
+ *
577
+ * Customize this file with your own trading logic and prompts.
578
+ * Your prompts are YOUR intellectual property - we don't store them.
579
+ */
580
+ export const generateSignals: StrategyFunction = async (
581
+ marketData: MarketData,
582
+ llm: LLMAdapter,
583
+ config: AgentConfig
584
+ ): Promise<TradeSignal[]> => {
585
+ // Your custom system prompt (this is your secret sauce)
586
+ const systemPrompt = \`
587
+ Your custom instructions here...
588
+ \`;
589
+
590
+ // Call the LLM with your prompt
591
+ const response = await llm.chat([
592
+ { role: 'system', content: systemPrompt },
593
+ { role: 'user', content: JSON.stringify(marketData) }
594
+ ]);
595
+
596
+ // Parse and return signals
597
+ // IMPORTANT: Validate LLM output before using
598
+ try {
599
+ const parsed = JSON.parse(response.content);
600
+ return parsed.signals || [];
601
+ } catch (e) {
602
+ console.error('Failed to parse LLM response:', e);
603
+ return []; // Safe fallback: no trades
604
+ }
605
+ };`
606
+ }
607
+ ];
608
+ function getStrategyTemplate(id) {
609
+ return STRATEGY_TEMPLATES.find((t) => t.id === id);
610
+ }
611
+ function getAllStrategyTemplates() {
612
+ return STRATEGY_TEMPLATES;
613
+ }
614
+
615
+ // src/trading/executor.ts
616
+ var TradeExecutor = class {
617
+ client;
618
+ config;
619
+ constructor(client, config) {
620
+ this.client = client;
621
+ this.config = config;
622
+ }
623
+ /**
624
+ * Execute a single trade signal
625
+ */
626
+ async execute(signal) {
627
+ if (signal.action === "hold") {
628
+ return { success: true };
629
+ }
630
+ try {
631
+ console.log(`Executing ${signal.action}: ${signal.tokenIn} -> ${signal.tokenOut}`);
632
+ console.log(`Amount: ${signal.amountIn.toString()}, Confidence: ${signal.confidence}`);
633
+ if (!this.validateSignal(signal)) {
634
+ return { success: false, error: "Signal exceeds position limits" };
635
+ }
636
+ const result = await this.client.trade({
637
+ tokenIn: signal.tokenIn,
638
+ tokenOut: signal.tokenOut,
639
+ amountIn: signal.amountIn,
640
+ maxSlippageBps: 100
641
+ // 1% default slippage
642
+ });
643
+ console.log(`Trade executed: ${result.hash}`);
644
+ return { success: true, txHash: result.hash };
645
+ } catch (error) {
646
+ const message = error instanceof Error ? error.message : "Unknown error";
647
+ console.error(`Trade failed: ${message}`);
648
+ return { success: false, error: message };
649
+ }
650
+ }
651
+ /**
652
+ * Execute multiple trade signals
653
+ * Returns results for each signal
654
+ */
655
+ async executeAll(signals) {
656
+ const results = [];
657
+ for (const signal of signals) {
658
+ const result = await this.execute(signal);
659
+ results.push({ signal, ...result });
660
+ if (signals.indexOf(signal) < signals.length - 1) {
661
+ await this.delay(1e3);
662
+ }
663
+ }
664
+ return results;
665
+ }
666
+ /**
667
+ * Validate a signal against config limits
668
+ */
669
+ validateSignal(signal) {
670
+ if (signal.confidence < 0.5) {
671
+ console.warn(`Signal confidence ${signal.confidence} below threshold (0.5)`);
672
+ return false;
673
+ }
674
+ return true;
675
+ }
676
+ delay(ms) {
677
+ return new Promise((resolve) => setTimeout(resolve, ms));
678
+ }
679
+ };
680
+
681
+ // src/trading/risk.ts
682
+ var RiskManager = class {
683
+ config;
684
+ dailyPnL = 0;
685
+ lastResetDate = "";
686
+ constructor(config) {
687
+ this.config = config;
688
+ }
689
+ /**
690
+ * Filter signals through risk checks
691
+ * Returns only signals that pass all guardrails
692
+ */
693
+ filterSignals(signals, marketData) {
694
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
695
+ if (today !== this.lastResetDate) {
696
+ this.dailyPnL = 0;
697
+ this.lastResetDate = today;
698
+ }
699
+ if (this.isDailyLossLimitHit(marketData.portfolioValue)) {
700
+ console.warn("Daily loss limit reached - no new trades");
701
+ return [];
702
+ }
703
+ return signals.filter((signal) => this.validateSignal(signal, marketData));
704
+ }
705
+ /**
706
+ * Validate individual signal against risk limits
707
+ */
708
+ validateSignal(signal, marketData) {
709
+ if (signal.action === "hold") {
710
+ return true;
711
+ }
712
+ const signalValue = this.estimateSignalValue(signal, marketData);
713
+ const maxPositionValue = marketData.portfolioValue * this.config.maxPositionSizeBps / 1e4;
714
+ if (signalValue > maxPositionValue) {
715
+ console.warn(
716
+ `Signal exceeds position limit: ${signalValue.toFixed(2)} > ${maxPositionValue.toFixed(2)}`
717
+ );
718
+ return false;
719
+ }
720
+ if (signal.confidence < 0.5) {
721
+ console.warn(`Signal confidence too low: ${signal.confidence}`);
722
+ return false;
723
+ }
724
+ return true;
725
+ }
726
+ /**
727
+ * Check if daily loss limit has been hit
728
+ */
729
+ isDailyLossLimitHit(portfolioValue) {
730
+ const maxLoss = portfolioValue * this.config.maxDailyLossBps / 1e4;
731
+ return this.dailyPnL < -maxLoss;
732
+ }
733
+ /**
734
+ * Estimate USD value of a trade signal
735
+ */
736
+ estimateSignalValue(signal, marketData) {
737
+ const price = marketData.prices[signal.tokenIn] || 0;
738
+ const amount = Number(signal.amountIn) / 1e18;
739
+ return amount * price;
740
+ }
741
+ /**
742
+ * Update daily PnL after a trade
743
+ */
744
+ updatePnL(pnl) {
745
+ this.dailyPnL += pnl;
746
+ }
747
+ /**
748
+ * Get current risk status
749
+ */
750
+ getStatus() {
751
+ return {
752
+ dailyPnL: this.dailyPnL,
753
+ dailyLossLimit: this.config.maxDailyLossBps / 100,
754
+ // As percentage
755
+ isLimitHit: this.dailyPnL < -(this.config.maxDailyLossBps / 100)
756
+ };
757
+ }
758
+ };
759
+
760
+ // src/trading/market.ts
761
+ var MarketDataService = class {
762
+ rpcUrl;
763
+ constructor(rpcUrl) {
764
+ this.rpcUrl = rpcUrl;
765
+ }
766
+ /**
767
+ * Fetch current market data for the agent
768
+ */
769
+ async fetchMarketData(walletAddress, tokenAddresses) {
770
+ const prices = await this.fetchPrices(tokenAddresses);
771
+ const balances = await this.fetchBalances(walletAddress, tokenAddresses);
772
+ const portfolioValue = this.calculatePortfolioValue(balances, prices);
773
+ return {
774
+ timestamp: Date.now(),
775
+ prices,
776
+ balances,
777
+ portfolioValue
778
+ };
779
+ }
780
+ /**
781
+ * Fetch token prices from price oracle
782
+ */
783
+ async fetchPrices(tokenAddresses) {
784
+ const prices = {};
785
+ const knownPrices = {
786
+ // WETH
787
+ "0x4200000000000000000000000000000000000006": 3500,
788
+ // USDC
789
+ "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913": 1,
790
+ // USDbC (bridged USDC)
791
+ "0xd9aAEc86B65D86f6A7B5B1b0c42FFA531710b6CA": 1
792
+ };
793
+ for (const address of tokenAddresses) {
794
+ prices[address.toLowerCase()] = knownPrices[address.toLowerCase()] || 0;
795
+ }
796
+ return prices;
797
+ }
798
+ /**
799
+ * Fetch token balances from chain
800
+ */
801
+ async fetchBalances(walletAddress, tokenAddresses) {
802
+ const balances = {};
803
+ for (const address of tokenAddresses) {
804
+ balances[address.toLowerCase()] = 0n;
805
+ }
806
+ return balances;
807
+ }
808
+ /**
809
+ * Calculate total portfolio value in USD
810
+ */
811
+ calculatePortfolioValue(balances, prices) {
812
+ let total = 0;
813
+ for (const [address, balance] of Object.entries(balances)) {
814
+ const price = prices[address.toLowerCase()] || 0;
815
+ const amount = Number(balance) / 1e18;
816
+ total += amount * price;
817
+ }
818
+ return total;
819
+ }
820
+ };
821
+
822
+ // src/vault/manager.ts
823
+ import { createPublicClient, createWalletClient, http } from "viem";
824
+ import { privateKeyToAccount } from "viem/accounts";
825
+ import { baseSepolia, base } from "viem/chains";
826
+ var ADDRESSES = {
827
+ testnet: {
828
+ vaultFactory: "0x5c099daaE33801a907Bb57011c6749655b55dc75",
829
+ registry: "0xCF48C341e3FebeCA5ECB7eb2535f61A2Ba855d9C",
830
+ usdc: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
831
+ },
832
+ mainnet: {
833
+ vaultFactory: "0x0000000000000000000000000000000000000000",
834
+ // TODO: Deploy
835
+ registry: "0x0000000000000000000000000000000000000000",
836
+ usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
837
+ // Base mainnet USDC
838
+ }
839
+ };
840
+ var VAULT_FACTORY_ABI = [
841
+ {
842
+ type: "function",
843
+ name: "vaults",
844
+ inputs: [{ name: "agentId", type: "uint256" }, { name: "asset", type: "address" }],
845
+ outputs: [{ type: "address" }],
846
+ stateMutability: "view"
847
+ },
848
+ {
849
+ type: "function",
850
+ name: "canCreateVault",
851
+ inputs: [{ name: "creator", type: "address" }],
852
+ outputs: [{ name: "canCreate", type: "bool" }, { name: "reason", type: "string" }],
853
+ stateMutability: "view"
854
+ },
855
+ {
856
+ type: "function",
857
+ name: "createVault",
858
+ inputs: [
859
+ { name: "agentId", type: "uint256" },
860
+ { name: "asset", type: "address" },
861
+ { name: "name", type: "string" },
862
+ { name: "symbol", type: "string" },
863
+ { name: "feeRecipient", type: "address" }
864
+ ],
865
+ outputs: [{ type: "address" }],
866
+ stateMutability: "nonpayable"
867
+ },
868
+ {
869
+ type: "function",
870
+ name: "minimumVeEXARequired",
871
+ inputs: [],
872
+ outputs: [{ type: "uint256" }],
873
+ stateMutability: "view"
874
+ },
875
+ {
876
+ type: "function",
877
+ name: "eXABurnFee",
878
+ inputs: [],
879
+ outputs: [{ type: "uint256" }],
880
+ stateMutability: "view"
881
+ }
882
+ ];
883
+ var VAULT_ABI = [
884
+ {
885
+ type: "function",
886
+ name: "totalAssets",
887
+ inputs: [],
888
+ outputs: [{ type: "uint256" }],
889
+ stateMutability: "view"
890
+ },
891
+ {
892
+ type: "function",
893
+ name: "executeTrade",
894
+ inputs: [
895
+ { name: "tokenIn", type: "address" },
896
+ { name: "tokenOut", type: "address" },
897
+ { name: "amountIn", type: "uint256" },
898
+ { name: "minAmountOut", type: "uint256" },
899
+ { name: "aggregator", type: "address" },
900
+ { name: "swapData", type: "bytes" },
901
+ { name: "deadline", type: "uint256" }
902
+ ],
903
+ outputs: [{ type: "uint256" }],
904
+ stateMutability: "nonpayable"
905
+ }
906
+ ];
907
+ var VaultManager = class {
908
+ config;
909
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
910
+ publicClient;
911
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
912
+ walletClient;
913
+ addresses;
914
+ account;
915
+ chain;
916
+ cachedVaultAddress = null;
917
+ lastVaultCheck = 0;
918
+ VAULT_CACHE_TTL = 6e4;
919
+ // 1 minute
920
+ constructor(config) {
921
+ this.config = config;
922
+ this.addresses = ADDRESSES[config.network];
923
+ this.account = privateKeyToAccount(config.walletKey);
924
+ this.chain = config.network === "mainnet" ? base : baseSepolia;
925
+ const rpcUrl = config.network === "mainnet" ? "https://mainnet.base.org" : "https://sepolia.base.org";
926
+ this.publicClient = createPublicClient({
927
+ chain: this.chain,
928
+ transport: http(rpcUrl)
929
+ });
930
+ this.walletClient = createWalletClient({
931
+ account: this.account,
932
+ chain: this.chain,
933
+ transport: http(rpcUrl)
934
+ });
935
+ }
936
+ /**
937
+ * Get the agent's vault policy
938
+ */
939
+ get policy() {
940
+ return this.config.vaultConfig.policy;
941
+ }
942
+ /**
943
+ * Check if vault trading is preferred when a vault exists
944
+ */
945
+ get preferVaultTrading() {
946
+ return this.config.vaultConfig.preferVaultTrading;
947
+ }
948
+ /**
949
+ * Get comprehensive vault status
950
+ */
951
+ async getVaultStatus() {
952
+ const vaultAddress = await this.getVaultAddress();
953
+ const hasVault = vaultAddress !== null;
954
+ let totalAssets = BigInt(0);
955
+ if (hasVault && vaultAddress) {
956
+ try {
957
+ totalAssets = await this.publicClient.readContract({
958
+ address: vaultAddress,
959
+ abi: VAULT_ABI,
960
+ functionName: "totalAssets"
961
+ });
962
+ } catch {
963
+ }
964
+ }
965
+ const [canCreateResult, requirements] = await Promise.all([
966
+ this.publicClient.readContract({
967
+ address: this.addresses.vaultFactory,
968
+ abi: VAULT_FACTORY_ABI,
969
+ functionName: "canCreateVault",
970
+ args: [this.account.address]
971
+ }),
972
+ this.getRequirements()
973
+ ]);
974
+ return {
975
+ hasVault,
976
+ vaultAddress,
977
+ totalAssets,
978
+ canCreateVault: canCreateResult[0],
979
+ cannotCreateReason: canCreateResult[0] ? null : canCreateResult[1],
980
+ requirementsMet: canCreateResult[0] || requirements.isBypassed,
981
+ requirements
982
+ };
983
+ }
984
+ /**
985
+ * Get vault creation requirements
986
+ */
987
+ async getRequirements() {
988
+ const [veXARequired, burnFee] = await Promise.all([
989
+ this.publicClient.readContract({
990
+ address: this.addresses.vaultFactory,
991
+ abi: VAULT_FACTORY_ABI,
992
+ functionName: "minimumVeEXARequired"
993
+ }),
994
+ this.publicClient.readContract({
995
+ address: this.addresses.vaultFactory,
996
+ abi: VAULT_FACTORY_ABI,
997
+ functionName: "eXABurnFee"
998
+ })
999
+ ]);
1000
+ const isBypassed = veXARequired === BigInt(0) && burnFee === BigInt(0);
1001
+ return { veXARequired, burnFee, isBypassed };
1002
+ }
1003
+ /**
1004
+ * Get the agent's vault address (cached)
1005
+ */
1006
+ async getVaultAddress() {
1007
+ const now = Date.now();
1008
+ if (this.cachedVaultAddress && now - this.lastVaultCheck < this.VAULT_CACHE_TTL) {
1009
+ return this.cachedVaultAddress;
1010
+ }
1011
+ const vaultAddress = await this.publicClient.readContract({
1012
+ address: this.addresses.vaultFactory,
1013
+ abi: VAULT_FACTORY_ABI,
1014
+ functionName: "vaults",
1015
+ args: [this.config.agentId, this.addresses.usdc]
1016
+ });
1017
+ this.lastVaultCheck = now;
1018
+ if (vaultAddress === "0x0000000000000000000000000000000000000000") {
1019
+ this.cachedVaultAddress = null;
1020
+ return null;
1021
+ }
1022
+ this.cachedVaultAddress = vaultAddress;
1023
+ return vaultAddress;
1024
+ }
1025
+ /**
1026
+ * Check if the agent should create a vault based on policy and qualification
1027
+ */
1028
+ async shouldCreateVault() {
1029
+ if (this.policy === "disabled") {
1030
+ return { should: false, reason: "Vault creation disabled by policy" };
1031
+ }
1032
+ if (this.policy === "manual") {
1033
+ return { should: false, reason: "Vault creation set to manual - waiting for owner instruction" };
1034
+ }
1035
+ const status = await this.getVaultStatus();
1036
+ if (status.hasVault) {
1037
+ return { should: false, reason: "Vault already exists" };
1038
+ }
1039
+ if (!status.canCreateVault) {
1040
+ return { should: false, reason: status.cannotCreateReason || "Requirements not met" };
1041
+ }
1042
+ return { should: true, reason: "Agent is qualified and auto-creation is enabled" };
1043
+ }
1044
+ /**
1045
+ * Create a vault for the agent
1046
+ * @returns Vault address if successful
1047
+ */
1048
+ async createVault() {
1049
+ if (this.policy === "disabled") {
1050
+ return { success: false, error: "Vault creation disabled by policy" };
1051
+ }
1052
+ const existingVault = await this.getVaultAddress();
1053
+ if (existingVault) {
1054
+ return { success: false, error: "Vault already exists", vaultAddress: existingVault };
1055
+ }
1056
+ const status = await this.getVaultStatus();
1057
+ if (!status.canCreateVault) {
1058
+ return { success: false, error: status.cannotCreateReason || "Requirements not met" };
1059
+ }
1060
+ const vaultName = this.config.vaultConfig.defaultName || `${this.config.agentName} Trading Vault`;
1061
+ const vaultSymbol = this.config.vaultConfig.defaultSymbol || `ex${this.config.agentName.replace(/[^a-zA-Z]/g, "").slice(0, 4).toUpperCase()}`;
1062
+ const feeRecipient = this.config.vaultConfig.feeRecipient || this.account.address;
1063
+ try {
1064
+ const hash = await this.walletClient.writeContract({
1065
+ address: this.addresses.vaultFactory,
1066
+ abi: VAULT_FACTORY_ABI,
1067
+ functionName: "createVault",
1068
+ args: [
1069
+ this.config.agentId,
1070
+ this.addresses.usdc,
1071
+ vaultName,
1072
+ vaultSymbol,
1073
+ feeRecipient
1074
+ ],
1075
+ chain: this.chain,
1076
+ account: this.account
1077
+ });
1078
+ const receipt = await this.publicClient.waitForTransactionReceipt({ hash });
1079
+ if (receipt.status !== "success") {
1080
+ return { success: false, error: "Transaction failed", txHash: hash };
1081
+ }
1082
+ const vaultAddress = await this.getVaultAddress();
1083
+ this.cachedVaultAddress = vaultAddress;
1084
+ return {
1085
+ success: true,
1086
+ vaultAddress,
1087
+ txHash: hash
1088
+ };
1089
+ } catch (error) {
1090
+ return {
1091
+ success: false,
1092
+ error: error instanceof Error ? error.message : "Unknown error"
1093
+ };
1094
+ }
1095
+ }
1096
+ /**
1097
+ * Execute a trade through the vault (if it exists and policy allows)
1098
+ * Returns null if should use direct trading instead
1099
+ */
1100
+ async executeVaultTrade(params) {
1101
+ if (!this.preferVaultTrading) {
1102
+ return null;
1103
+ }
1104
+ const vaultAddress = await this.getVaultAddress();
1105
+ if (!vaultAddress) {
1106
+ return null;
1107
+ }
1108
+ const deadline = params.deadline || BigInt(Math.floor(Date.now() / 1e3) + 3600);
1109
+ try {
1110
+ const hash = await this.walletClient.writeContract({
1111
+ address: vaultAddress,
1112
+ abi: VAULT_ABI,
1113
+ functionName: "executeTrade",
1114
+ args: [
1115
+ params.tokenIn,
1116
+ params.tokenOut,
1117
+ params.amountIn,
1118
+ params.minAmountOut,
1119
+ params.aggregator,
1120
+ params.swapData,
1121
+ deadline
1122
+ ],
1123
+ chain: this.chain,
1124
+ account: this.account
1125
+ });
1126
+ return { usedVault: true, txHash: hash };
1127
+ } catch (error) {
1128
+ return {
1129
+ usedVault: true,
1130
+ error: error instanceof Error ? error.message : "Vault trade failed"
1131
+ };
1132
+ }
1133
+ }
1134
+ /**
1135
+ * Run the auto-creation check (call this periodically in the agent loop)
1136
+ * Only creates vault if policy is 'auto_when_qualified'
1137
+ */
1138
+ async checkAndAutoCreateVault() {
1139
+ const shouldCreate = await this.shouldCreateVault();
1140
+ if (!shouldCreate.should) {
1141
+ const status = await this.getVaultStatus();
1142
+ if (status.hasVault) {
1143
+ return { action: "already_exists", vaultAddress: status.vaultAddress, reason: "Vault already exists" };
1144
+ }
1145
+ if (this.policy !== "auto_when_qualified") {
1146
+ return { action: "skipped", reason: shouldCreate.reason };
1147
+ }
1148
+ return { action: "not_qualified", reason: shouldCreate.reason };
1149
+ }
1150
+ const result = await this.createVault();
1151
+ if (result.success) {
1152
+ return {
1153
+ action: "created",
1154
+ vaultAddress: result.vaultAddress,
1155
+ reason: "Vault created automatically"
1156
+ };
1157
+ }
1158
+ return { action: "not_qualified", reason: result.error || "Creation failed" };
1159
+ }
1160
+ };
1161
+
1162
+ // src/runtime.ts
1163
+ import { ExagentClient, ExagentRegistry } from "@exagent/sdk";
1164
+ var AgentRuntime = class {
1165
+ config;
1166
+ client;
1167
+ llm;
1168
+ strategy;
1169
+ executor;
1170
+ riskManager;
1171
+ marketData;
1172
+ vaultManager;
1173
+ isRunning = false;
1174
+ configHash;
1175
+ lastVaultCheck = 0;
1176
+ VAULT_CHECK_INTERVAL = 3e5;
1177
+ // Check vault status every 5 minutes
1178
+ constructor(config) {
1179
+ this.config = config;
1180
+ }
1181
+ /**
1182
+ * Initialize the agent runtime
1183
+ */
1184
+ async initialize() {
1185
+ console.log(`Initializing agent: ${this.config.name} (ID: ${this.config.agentId})`);
1186
+ this.client = new ExagentClient({
1187
+ privateKey: this.config.privateKey,
1188
+ network: this.config.network
1189
+ });
1190
+ console.log(`Wallet: ${this.client.address}`);
1191
+ const agent = await this.client.registry.getAgent(BigInt(this.config.agentId));
1192
+ if (!agent) {
1193
+ throw new Error(`Agent ID ${this.config.agentId} not found on-chain. Please register first.`);
1194
+ }
1195
+ console.log(`Agent verified: ${agent.name}`);
1196
+ await this.ensureWalletLinked();
1197
+ console.log(`Initializing LLM: ${this.config.llm.provider}`);
1198
+ this.llm = await createLLMAdapter(this.config.llm);
1199
+ const llmMeta = this.llm.getMetadata();
1200
+ console.log(`LLM ready: ${llmMeta.provider} (${llmMeta.model})`);
1201
+ await this.syncConfigHash();
1202
+ this.strategy = await loadStrategy();
1203
+ this.executor = new TradeExecutor(this.client, this.config);
1204
+ this.riskManager = new RiskManager(this.config.trading);
1205
+ this.marketData = new MarketDataService(this.getRpcUrl());
1206
+ await this.initializeVaultManager();
1207
+ console.log("Agent initialized successfully");
1208
+ }
1209
+ /**
1210
+ * Initialize the vault manager based on config
1211
+ */
1212
+ async initializeVaultManager() {
1213
+ const vaultConfig = this.config.vault || { policy: "disabled", preferVaultTrading: false };
1214
+ this.vaultManager = new VaultManager({
1215
+ agentId: BigInt(this.config.agentId),
1216
+ agentName: this.config.name,
1217
+ network: this.config.network,
1218
+ walletKey: this.config.privateKey,
1219
+ vaultConfig
1220
+ });
1221
+ console.log(`Vault policy: ${vaultConfig.policy}`);
1222
+ const status = await this.vaultManager.getVaultStatus();
1223
+ if (status.hasVault) {
1224
+ console.log(`Vault exists: ${status.vaultAddress}`);
1225
+ console.log(`Vault TVL: ${Number(status.totalAssets) / 1e6} USDC`);
1226
+ } else {
1227
+ console.log("No vault exists for this agent");
1228
+ if (vaultConfig.policy === "auto_when_qualified") {
1229
+ if (status.canCreateVault) {
1230
+ console.log("Agent is qualified to create vault - will attempt on next check");
1231
+ } else {
1232
+ console.log(`Cannot create vault yet: ${status.cannotCreateReason}`);
1233
+ }
1234
+ }
1235
+ }
1236
+ }
1237
+ /**
1238
+ * Ensure the current wallet is linked to the agent
1239
+ */
1240
+ async ensureWalletLinked() {
1241
+ const agentId = BigInt(this.config.agentId);
1242
+ const address = this.client.address;
1243
+ const isLinked = await this.client.registry.isLinkedWallet(agentId, address);
1244
+ if (!isLinked) {
1245
+ console.log("Wallet not linked, linking now...");
1246
+ const agent = await this.client.registry.getAgent(agentId);
1247
+ if (agent?.owner.toLowerCase() !== address.toLowerCase()) {
1248
+ throw new Error(
1249
+ `Cannot link wallet: ${address} is not the owner of agent ${this.config.agentId}. Owner is ${agent?.owner}`
1250
+ );
1251
+ }
1252
+ await this.client.registry.linkOwnWallet(agentId);
1253
+ console.log("Wallet linked successfully");
1254
+ } else {
1255
+ console.log("Wallet already linked");
1256
+ }
1257
+ }
1258
+ /**
1259
+ * Sync the LLM config hash to chain for epoch tracking
1260
+ * This ensures trades are attributed to the correct config epoch
1261
+ */
1262
+ async syncConfigHash() {
1263
+ const agentId = BigInt(this.config.agentId);
1264
+ const llmMeta = this.llm.getMetadata();
1265
+ this.configHash = ExagentRegistry.calculateConfigHash(llmMeta.provider, llmMeta.model);
1266
+ console.log(`Config hash: ${this.configHash}`);
1267
+ const onChainHash = await this.client.registry.getConfigHash(agentId);
1268
+ if (onChainHash !== this.configHash) {
1269
+ console.log("Config changed, updating on-chain...");
1270
+ await this.client.registry.updateConfig(agentId, this.configHash);
1271
+ const newEpoch = await this.client.registry.getCurrentEpoch(agentId);
1272
+ console.log(`Config updated, new epoch started: ${newEpoch}`);
1273
+ } else {
1274
+ const currentEpoch = await this.client.registry.getCurrentEpoch(agentId);
1275
+ console.log(`Config hash matches on-chain (epoch ${currentEpoch})`);
1276
+ }
1277
+ }
1278
+ /**
1279
+ * Get the current config hash (for trade execution)
1280
+ */
1281
+ getConfigHash() {
1282
+ return this.configHash;
1283
+ }
1284
+ /**
1285
+ * Start the trading loop
1286
+ */
1287
+ async run() {
1288
+ if (this.isRunning) {
1289
+ throw new Error("Agent is already running");
1290
+ }
1291
+ this.isRunning = true;
1292
+ console.log("Starting trading loop...");
1293
+ console.log(`Interval: ${this.config.trading.tradingIntervalMs}ms`);
1294
+ while (this.isRunning) {
1295
+ try {
1296
+ await this.runCycle();
1297
+ } catch (error) {
1298
+ console.error("Error in trading cycle:", error);
1299
+ }
1300
+ await this.sleep(this.config.trading.tradingIntervalMs);
1301
+ }
1302
+ }
1303
+ /**
1304
+ * Run a single trading cycle
1305
+ */
1306
+ async runCycle() {
1307
+ console.log(`
1308
+ --- Trading Cycle: ${(/* @__PURE__ */ new Date()).toISOString()} ---`);
1309
+ await this.checkVaultAutoCreation();
1310
+ const tokens = this.config.allowedTokens || this.getDefaultTokens();
1311
+ const marketData = await this.marketData.fetchMarketData(this.client.address, tokens);
1312
+ console.log(`Portfolio value: $${marketData.portfolioValue.toFixed(2)}`);
1313
+ const signals = await this.strategy(marketData, this.llm, this.config);
1314
+ console.log(`Strategy generated ${signals.length} signals`);
1315
+ const filteredSignals = this.riskManager.filterSignals(signals, marketData);
1316
+ console.log(`${filteredSignals.length} signals passed risk checks`);
1317
+ if (filteredSignals.length > 0) {
1318
+ const results = await this.executor.executeAll(filteredSignals);
1319
+ for (const result of results) {
1320
+ if (result.success) {
1321
+ console.log(`Trade executed: ${result.signal.action} - ${result.txHash}`);
1322
+ } else {
1323
+ console.warn(`Trade failed: ${result.error}`);
1324
+ }
1325
+ }
1326
+ }
1327
+ }
1328
+ /**
1329
+ * Check for vault auto-creation based on policy
1330
+ */
1331
+ async checkVaultAutoCreation() {
1332
+ const now = Date.now();
1333
+ if (now - this.lastVaultCheck < this.VAULT_CHECK_INTERVAL) {
1334
+ return;
1335
+ }
1336
+ this.lastVaultCheck = now;
1337
+ const result = await this.vaultManager.checkAndAutoCreateVault();
1338
+ switch (result.action) {
1339
+ case "created":
1340
+ console.log(`\u{1F389} Vault created automatically: ${result.vaultAddress}`);
1341
+ break;
1342
+ case "already_exists":
1343
+ break;
1344
+ case "skipped":
1345
+ break;
1346
+ case "not_qualified":
1347
+ console.log(`Vault auto-creation pending: ${result.reason}`);
1348
+ break;
1349
+ }
1350
+ }
1351
+ /**
1352
+ * Stop the trading loop
1353
+ */
1354
+ stop() {
1355
+ console.log("Stopping agent...");
1356
+ this.isRunning = false;
1357
+ }
1358
+ /**
1359
+ * Get RPC URL based on network
1360
+ */
1361
+ getRpcUrl() {
1362
+ if (this.config.network === "mainnet") {
1363
+ return "https://mainnet.base.org";
1364
+ }
1365
+ return "https://sepolia.base.org";
1366
+ }
1367
+ /**
1368
+ * Default tokens to track
1369
+ */
1370
+ getDefaultTokens() {
1371
+ if (this.config.network === "mainnet") {
1372
+ return [
1373
+ "0x4200000000000000000000000000000000000006",
1374
+ // WETH
1375
+ "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
1376
+ // USDC
1377
+ ];
1378
+ }
1379
+ return [
1380
+ "0x4200000000000000000000000000000000000006"
1381
+ // WETH
1382
+ ];
1383
+ }
1384
+ sleep(ms) {
1385
+ return new Promise((resolve) => setTimeout(resolve, ms));
1386
+ }
1387
+ /**
1388
+ * Get current status
1389
+ */
1390
+ getStatus() {
1391
+ const vaultConfig = this.config.vault || { policy: "disabled" };
1392
+ return {
1393
+ isRunning: this.isRunning,
1394
+ agentId: Number(this.config.agentId),
1395
+ wallet: this.client?.address || "not initialized",
1396
+ llm: {
1397
+ provider: this.config.llm.provider,
1398
+ model: this.config.llm.model || "default"
1399
+ },
1400
+ configHash: this.configHash || "not initialized",
1401
+ risk: this.riskManager?.getStatus() || { dailyPnL: 0, dailyLossLimit: 0, isLimitHit: false },
1402
+ vault: {
1403
+ policy: vaultConfig.policy,
1404
+ hasVault: false,
1405
+ // Updated async via getVaultStatus
1406
+ vaultAddress: null
1407
+ }
1408
+ };
1409
+ }
1410
+ /**
1411
+ * Get detailed vault status (async)
1412
+ */
1413
+ async getVaultStatus() {
1414
+ if (!this.vaultManager) {
1415
+ return null;
1416
+ }
1417
+ return this.vaultManager.getVaultStatus();
1418
+ }
1419
+ /**
1420
+ * Manually trigger vault creation (for 'manual' policy)
1421
+ */
1422
+ async createVault() {
1423
+ if (!this.vaultManager) {
1424
+ return { success: false, error: "Vault manager not initialized" };
1425
+ }
1426
+ const policy = this.config.vault?.policy || "disabled";
1427
+ if (policy === "disabled") {
1428
+ return { success: false, error: "Vault creation is disabled by policy" };
1429
+ }
1430
+ return this.vaultManager.createVault();
1431
+ }
1432
+ };
1433
+
1434
+ // src/types.ts
1435
+ import { z } from "zod";
1436
+ var WalletSetupSchema = z.enum(["generate", "provide"]);
1437
+ var LLMProviderSchema = z.enum(["openai", "anthropic", "google", "deepseek", "mistral", "groq", "together", "ollama", "custom"]);
1438
+ var LLMConfigSchema = z.object({
1439
+ provider: LLMProviderSchema,
1440
+ model: z.string().optional(),
1441
+ apiKey: z.string().optional(),
1442
+ endpoint: z.string().url().optional(),
1443
+ temperature: z.number().min(0).max(2).default(0.7),
1444
+ maxTokens: z.number().positive().default(4096)
1445
+ });
1446
+ var RiskUniverseSchema = z.enum(["core", "established", "derivatives", "emerging", "frontier"]);
1447
+ var TradingConfigSchema = z.object({
1448
+ timeHorizon: z.enum(["intraday", "swing", "position"]).default("swing"),
1449
+ maxPositionSizeBps: z.number().min(100).max(1e4).default(1e3),
1450
+ // 1-100%
1451
+ maxDailyLossBps: z.number().min(0).max(1e4).default(500),
1452
+ // 0-100%
1453
+ maxConcurrentPositions: z.number().min(1).max(100).default(5),
1454
+ tradingIntervalMs: z.number().min(1e3).default(6e4)
1455
+ // minimum 1 second
1456
+ });
1457
+ var VaultPolicySchema = z.enum([
1458
+ "disabled",
1459
+ // Never create a vault - trade with agent's own capital only
1460
+ "manual",
1461
+ // Only create vault when explicitly directed by owner
1462
+ "auto_when_qualified"
1463
+ // Automatically create vault when requirements are met
1464
+ ]);
1465
+ var VaultConfigSchema = z.object({
1466
+ // Policy for vault creation (asked during deployment)
1467
+ policy: VaultPolicySchema.default("manual"),
1468
+ // Default vault name (auto-generated from agent name if not set)
1469
+ defaultName: z.string().optional(),
1470
+ // Default vault symbol (auto-generated if not set)
1471
+ defaultSymbol: z.string().optional(),
1472
+ // Fee recipient for vault fees (default: agent wallet)
1473
+ feeRecipient: z.string().optional(),
1474
+ // When vault exists, trade through vault instead of direct trading
1475
+ // This pools depositors' capital with the agent's trades
1476
+ preferVaultTrading: z.boolean().default(true)
1477
+ });
1478
+ var WalletConfigSchema = z.object({
1479
+ setup: WalletSetupSchema.default("provide")
1480
+ }).optional();
1481
+ var AgentConfigSchema = z.object({
1482
+ // Identity (from on-chain registration)
1483
+ agentId: z.union([z.number().positive(), z.string()]),
1484
+ name: z.string().min(3).max(32),
1485
+ // Network
1486
+ network: z.enum(["mainnet", "testnet"]).default("testnet"),
1487
+ // Wallet setup preference
1488
+ wallet: WalletConfigSchema,
1489
+ // LLM
1490
+ llm: LLMConfigSchema,
1491
+ // Trading parameters
1492
+ riskUniverse: RiskUniverseSchema.default("established"),
1493
+ trading: TradingConfigSchema.default({}),
1494
+ // Vault configuration (copy trading)
1495
+ vault: VaultConfigSchema.default({}),
1496
+ // Allowed tokens (addresses)
1497
+ allowedTokens: z.array(z.string()).optional()
1498
+ });
1499
+
1500
+ // src/config.ts
1501
+ import { readFileSync, existsSync as existsSync2 } from "fs";
1502
+ import { join as join2 } from "path";
1503
+ import { config as loadEnv } from "dotenv";
1504
+ function loadConfig(configPath) {
1505
+ loadEnv();
1506
+ const configFile = configPath || process.env.EXAGENT_CONFIG || "agent-config.json";
1507
+ const fullPath = configFile.startsWith("/") ? configFile : join2(process.cwd(), configFile);
1508
+ if (!existsSync2(fullPath)) {
1509
+ throw new Error(`Config file not found: ${fullPath}`);
1510
+ }
1511
+ const rawConfig = JSON.parse(readFileSync(fullPath, "utf-8"));
1512
+ const config = AgentConfigSchema.parse(rawConfig);
1513
+ const privateKey = process.env.EXAGENT_PRIVATE_KEY;
1514
+ if (!privateKey) {
1515
+ throw new Error("EXAGENT_PRIVATE_KEY not set in environment");
1516
+ }
1517
+ if (!privateKey.startsWith("0x") || privateKey.length !== 66) {
1518
+ throw new Error("EXAGENT_PRIVATE_KEY must be a valid 32-byte hex string starting with 0x");
1519
+ }
1520
+ const llmConfig = { ...config.llm };
1521
+ if (process.env.OPENAI_API_KEY && config.llm.provider === "openai") {
1522
+ llmConfig.apiKey = process.env.OPENAI_API_KEY;
1523
+ }
1524
+ if (process.env.ANTHROPIC_API_KEY && config.llm.provider === "anthropic") {
1525
+ llmConfig.apiKey = process.env.ANTHROPIC_API_KEY;
1526
+ }
1527
+ if (process.env.GOOGLE_AI_API_KEY && config.llm.provider === "google") {
1528
+ llmConfig.apiKey = process.env.GOOGLE_AI_API_KEY;
1529
+ }
1530
+ if (process.env.EXAGENT_LLM_URL) {
1531
+ llmConfig.endpoint = process.env.EXAGENT_LLM_URL;
1532
+ }
1533
+ if (process.env.EXAGENT_LLM_MODEL) {
1534
+ llmConfig.model = process.env.EXAGENT_LLM_MODEL;
1535
+ }
1536
+ const network = process.env.EXAGENT_NETWORK || config.network;
1537
+ return {
1538
+ ...config,
1539
+ llm: llmConfig,
1540
+ network,
1541
+ privateKey
1542
+ };
1543
+ }
1544
+ function validateConfig(config) {
1545
+ if (!config.privateKey) {
1546
+ throw new Error("Private key is required");
1547
+ }
1548
+ if (config.llm.provider !== "ollama" && !config.llm.apiKey) {
1549
+ throw new Error(`API key required for ${config.llm.provider} provider`);
1550
+ }
1551
+ if (config.llm.provider === "ollama" && !config.llm.endpoint) {
1552
+ config.llm.endpoint = "http://localhost:11434";
1553
+ }
1554
+ if (config.llm.provider === "custom" && !config.llm.endpoint) {
1555
+ throw new Error("Endpoint required for custom LLM provider");
1556
+ }
1557
+ if (!config.agentId || Number(config.agentId) <= 0) {
1558
+ throw new Error("Valid agent ID required");
1559
+ }
1560
+ }
1561
+ function createSampleConfig(agentId, name) {
1562
+ return {
1563
+ agentId,
1564
+ name,
1565
+ network: "testnet",
1566
+ llm: {
1567
+ provider: "openai",
1568
+ model: "gpt-4.1",
1569
+ temperature: 0.7,
1570
+ maxTokens: 4096
1571
+ },
1572
+ riskUniverse: "established",
1573
+ trading: {
1574
+ timeHorizon: "swing",
1575
+ maxPositionSizeBps: 1e3,
1576
+ maxDailyLossBps: 500,
1577
+ maxConcurrentPositions: 5,
1578
+ tradingIntervalMs: 6e4
1579
+ },
1580
+ vault: {
1581
+ // Default to manual - user must explicitly enable auto-creation
1582
+ policy: "manual",
1583
+ // Will use agent name for vault name if not set
1584
+ preferVaultTrading: true
1585
+ }
1586
+ };
1587
+ }
1588
+
1589
+ export {
1590
+ BaseLLMAdapter,
1591
+ OpenAIAdapter,
1592
+ AnthropicAdapter,
1593
+ OllamaAdapter,
1594
+ createLLMAdapter,
1595
+ loadStrategy,
1596
+ validateStrategy,
1597
+ STRATEGY_TEMPLATES,
1598
+ getStrategyTemplate,
1599
+ getAllStrategyTemplates,
1600
+ TradeExecutor,
1601
+ RiskManager,
1602
+ MarketDataService,
1603
+ VaultManager,
1604
+ AgentRuntime,
1605
+ LLMProviderSchema,
1606
+ LLMConfigSchema,
1607
+ RiskUniverseSchema,
1608
+ TradingConfigSchema,
1609
+ VaultPolicySchema,
1610
+ VaultConfigSchema,
1611
+ AgentConfigSchema,
1612
+ loadConfig,
1613
+ validateConfig,
1614
+ createSampleConfig
1615
+ };