@exagent/agent 0.1.0

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