nyxora 26.6.5 → 26.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +6 -4
  3. package/SECURITY.md +10 -1
  4. package/bin/nyxora.mjs +37 -5
  5. package/dist/packages/core/src/agent/limitOrderManager.js +178 -0
  6. package/dist/packages/core/src/agent/reasoning.js +505 -0
  7. package/dist/packages/core/src/agent/transactionManager.js +38 -0
  8. package/dist/packages/core/src/agent/updateProfile.js +52 -0
  9. package/dist/packages/core/src/config/parser.js +163 -0
  10. package/dist/packages/core/src/config/paths.js +35 -0
  11. package/dist/packages/core/src/gateway/cli.js +107 -0
  12. package/dist/packages/core/src/gateway/googleAuthModule.js +191 -0
  13. package/dist/packages/core/src/gateway/server.js +429 -0
  14. package/dist/packages/core/src/gateway/setup-cli.js +41 -0
  15. package/dist/packages/core/src/gateway/setup.js +365 -0
  16. package/dist/packages/core/src/gateway/telegram.js +235 -0
  17. package/dist/packages/core/src/gateway/test.js +15 -0
  18. package/dist/packages/core/src/gateway/tracker.js +49 -0
  19. package/dist/packages/core/src/memory/logger.js +186 -0
  20. package/dist/packages/core/src/system/pluginManager.js +90 -0
  21. package/dist/packages/core/src/system/skills/analyzeDocument.js +65 -0
  22. package/dist/packages/core/src/system/skills/browseWeb.js +50 -0
  23. package/dist/packages/core/src/system/skills/executeShell.js +38 -0
  24. package/dist/packages/core/src/system/skills/googleWorkspace.js +242 -0
  25. package/dist/packages/core/src/system/skills/installSkill.js +51 -0
  26. package/dist/packages/core/src/system/skills/readFile.js +39 -0
  27. package/dist/packages/core/src/system/skills/searchWeb.js +203 -0
  28. package/dist/packages/core/src/system/skills/updateSecurityPolicy.js +60 -0
  29. package/dist/packages/core/src/system/skills/writeFile.js +44 -0
  30. package/dist/packages/core/src/test-all-routers.js +74 -0
  31. package/dist/packages/core/src/test-router.js +37 -0
  32. package/dist/packages/core/src/utils/dynamicTokenUpdater.js +67 -0
  33. package/dist/packages/core/src/utils/formatter.js +39 -0
  34. package/dist/packages/core/src/utils/safeLogger.js +59 -0
  35. package/dist/packages/core/src/utils/skillManager.js +50 -0
  36. package/dist/packages/core/src/utils/state.js +30 -0
  37. package/dist/packages/core/src/utils/userWhitelistManager.js +50 -0
  38. package/dist/packages/core/src/web3/config.js +97 -0
  39. package/dist/packages/core/src/web3/skills/bridgeToken.js +276 -0
  40. package/dist/packages/core/src/web3/skills/checkAddress.js +52 -0
  41. package/dist/packages/core/src/web3/skills/checkPortfolio.js +206 -0
  42. package/dist/packages/core/src/web3/skills/checkSecurity.js +70 -0
  43. package/dist/packages/core/src/web3/skills/createWallet.js +34 -0
  44. package/dist/packages/core/src/web3/skills/customTx.js +116 -0
  45. package/dist/packages/core/src/web3/skills/getBalance.js +112 -0
  46. package/dist/packages/core/src/web3/skills/getMyAddress.js +29 -0
  47. package/dist/packages/core/src/web3/skills/getPrice.js +44 -0
  48. package/dist/packages/core/src/web3/skills/marketAnalysis.js +96 -0
  49. package/dist/packages/core/src/web3/skills/mintNft.js +144 -0
  50. package/dist/packages/core/src/web3/skills/swapToken.js +314 -0
  51. package/dist/packages/core/src/web3/skills/transfer.js +134 -0
  52. package/dist/packages/core/src/web3/utils/routers.js +101 -0
  53. package/dist/packages/core/src/web3/utils/tokens.js +157 -0
  54. package/dist/packages/policy/src/server.js +173 -0
  55. package/dist/packages/signer/src/crypto.js +35 -0
  56. package/dist/packages/signer/src/server.js +230 -0
  57. package/funding.json +5 -0
  58. package/launcher.ts +19 -12
  59. package/package.json +4 -3
  60. package/packages/core/package.json +8 -3
  61. package/packages/core/src/agent/reasoning.ts +23 -4
  62. package/packages/core/src/config/parser.ts +9 -8
  63. package/packages/core/src/gateway/cli.ts +6 -1
  64. package/packages/core/src/gateway/server.ts +78 -47
  65. package/packages/core/src/memory/logger.ts +23 -2
  66. package/packages/core/src/web3/config.ts +2 -1
  67. package/packages/core/src/web3/skills/bridgeToken.ts +60 -42
  68. package/packages/core/src/web3/skills/checkSecurity.ts +1 -0
  69. package/packages/core/src/web3/skills/customTx.ts +12 -2
  70. package/packages/core/src/web3/skills/getBalance.ts +5 -16
  71. package/packages/core/src/web3/skills/mintNft.ts +13 -2
  72. package/packages/core/src/web3/skills/swapToken.ts +28 -12
  73. package/packages/core/src/web3/skills/transfer.ts +17 -17
  74. package/packages/core/src/web3/utils/tokens.ts +51 -2
  75. package/packages/dashboard/dist/assets/index-DWxWzOS7.js +306 -0
  76. package/packages/dashboard/dist/index.html +1 -1
  77. package/packages/dashboard/package.json +1 -1
  78. package/packages/policy/src/server.ts +1 -1
  79. package/packages/signer/src/server.ts +39 -2
  80. package/tsconfig.json +3 -2
  81. package/packages/dashboard/dist/assets/index-Xhv1dj6H.js +0 -300
package/CHANGELOG.md CHANGED
@@ -5,6 +5,47 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepashangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [26.6.6] - 2026-06-05
9
+ ### Enterprise Stability Upgrades
10
+ - **Strict LLM Output Validation**: Added robust try-catch parsing for LLM tool arguments in `reasoning.ts`. If the AI outputs malformed JSON, the error is fed back into the reasoning loop, allowing the model to autonomously self-correct without crashing the agent pipeline.
11
+ - **Transaction Simulation (Dry-Run)**: Integrated `publicClient.estimateGas` in the Signer Vault before broadcasting transactions. This ensures all Web3 transactions are simulated at the node level, preventing users from wasting gas fees on reverted transactions (e.g., due to insufficient slippage or balance).
12
+ - **Graceful Shutdown (Keyring Security)**: Replaced `SIGKILL` with `SIGTERM` in `launcher.ts` and added explicit process termination listeners in the Signer server. When a user exits the CLI using `Ctrl+C`, the system elegantly clears the in-memory `vaultPrivateKey` reference and unlinks unix sockets, securing the local Keyring vault before terminating.
13
+ - **Undefined Function Fix**: Fixed a silent `TypeError` bug in `reasoning.ts` where a failed LLM parsing attempt would call an undefined `executeReasoningLoop` function. Now gracefully loops via standard `logger.addEntry` continuation.
14
+
15
+ ### Bug Fixes & UX Enhancements
16
+ - **Destructive Config Overwrite Fix**: Fixed a critical bug in `/api/config` where saving settings via the Dashboard UI would silently delete the user's Telegram Bot token and system permissions. The API now performs a deep merge with `config.yaml`.
17
+ - **Asynchronous Transaction UI**: Detached the Web3 transaction execution loop from the Dashboard UI `/approve` endpoint. Approvals now instantly return a success state to the UI (preventing 3-minute freezes) while the transaction safely confirms in the background and reports back via chat.
18
+
19
+ ### Performance & Speed Optimizations
20
+ - **SQLite Indexing (O(1) Lookup)**: Added an automatic `CREATE INDEX` for `session_id` in the memory logger database, drastically reducing query latency from O(n) full table scans to instantaneous lookups for large chat histories.
21
+ - **Sliding Window Context Limit**: Overhauled `getHistory()` with an SQL subquery `LIMIT 40` approach. The agent now only feeds the most recent 40 messages to the LLM context, massively reducing API token costs and preventing latency bloat.
22
+ - **Pre-Compiled Runtime (ts-node Elimination)**: Replaced on-the-fly TypeScript compilation (`ts-node`) with ahead-of-time compilation (`tsc`). `launcher.ts` and `nyxora.mjs` now natively detect and execute compiled `.js` files from the `dist/` directory, resulting in near-instant daemon startup times.
23
+ - **Global Token Metadata Cache (OOM Protected)**: Implemented an in-memory Bounded LRU Cache (max 1000 items) in `tokens.ts` for caching `decimals` and `symbol`. This eliminates repetitive RPC calls for immutable token data, shielding the system from Out-Of-Memory crashes if spammed with fake tokens.
24
+ - **Web3 RPC Parallelization**: Refactored `transfer.ts`, `swapToken.ts`, `bridgeToken.ts`, and `getBalance.ts` to replace slow, sequential `readContract` calls with `Promise.all` fetching via `getTokenMetadata()`. Web3 action preparation latency has been reduced to near 0ms for cached tokens.
25
+
26
+ ## [26.6.5-1.0] - 2026-06-05
27
+ ### Bug Fixes & Improvements
28
+ - **Transaction Stability**: Added 30-second `AbortSignal` timeout safety net across all Web3 skills (`swapToken`, `transfer`, `bridgeToken`, `mintNft`, `customTx`) to prevent UI hanging when RPC nodes are unresponsive.
29
+ - **Multi-Session Transaction Logs**: Fixed an issue where Web3 transaction status messages (Approve/Reject/Success/Failure) were logged to the `default` session instead of the user's active session window, by attaching the correct `sessionId` with `Content-Type: application/json` headers in dashboard API requests.
30
+ - **UI Tool Rendering Bug**: Fixed a React rendering bug in `App.tsx` where the AI's internal tool execution notification (green bubble) would be hidden if the AI generated both conversational text and a tool execution in the same response.
31
+ - **Base Sepolia Support**: Officially added `base_sepolia` testnet to the supported networks list and `bridgeToken` mappings to prevent AI confusion when resolving bridge destinations.
32
+ - **Default Policy Override (Plug & Play)**: Adjusted the default `config.yaml` template and internal Policy Engine defaults to set `allow_transfer`, `allow_swap`, `allow_shell_execution`, and `allow_file_write` to `true`. Also uncapped `max_usd_per_tx` to `$999,999,999` by default, ensuring a seamless "plug and play" experience for new users without needing manual configuration edits.
33
+ - **Viem RPC Timeout**: Injected a strict 15-second timeout inside the `signer` vault's `viem` HTTP transport to prevent indefinite freezing during blockchain gas estimation when the node is heavily rate-limited.
34
+ - **Auto-Approve Signature Fix**: Added internal HMAC signature generation across all Web3 transaction execution modules (Transfer, Bridge, Mint, CustomTx) to resolve the `Missing internal signature for autoApprove` error during manual dashboard approvals or policy bypasses.
35
+ - **LayerZero Testnet Route**: Upgraded the testnet Bridge mock implementation to utilize LayerZero's V2 Endpoint router (`0x1a44...`) for simulated testnet bridging transactions.
36
+ - **Transaction Result Formatting**: Fixed an issue where the AI would output raw JSON stringified payloads for successful transactions. The chat notification is now properly formatted to clearly display the transaction hash.
37
+ - **Base Sepolia UI Integration**: Synchronized the Dashboard's Network Selector dropdown and Default Web3 Chain settings menu to include the newly added `Base Sepolia (Testnet)` network.
38
+ - **LayerZero Mainnet Removal (Stargate V2)**: Completely removed the experimental LayerZero/Stargate V2 integration from the core bridging engine to prevent interaction with potentially outdated or unverified mainnet smart contracts. Removed the corresponding "LayerZero" routing option from the Dashboard UI dropdown to ensure a highly stable and secure bridging experience exclusively via Li.Fi and Relay.
39
+ - **Relay MEV Protection (Slippage)**: Hardened the `getRelayQuote` HTTP POST request by injecting a strict `slippageTolerance` parameter (default 0.5%). This closes a critical vulnerability where unbounded Relay executions could expose user funds to front-running and MEV attacks during volatile market conditions.
40
+ - **Strict NLP Exactness (Rule 8)**: Injected CRITICAL RULE 8 into the core reasoning pipeline (`reasoning.ts`). The AI is now strictly forbidden from hallucinating or guessing ambiguous transaction parameters (tokens, amounts, or destination networks). It will automatically halt and politely ask the user for explicit clarification before constructing any Web3 payloads.
41
+ - **NLP Context Override System**: Documented the NLP fallback override mechanism in `README.md` and Vitepress documentation to clarify how explicit user chat instructions dynamically bypass Dashboard configurations.
42
+
43
+ ### UI/UX Fixes
44
+ - **Pending Transactions Widget**: Fixed a rendering bug where the Approve/Reject popup was not being injected into the DOM, preventing users from signing transactions.
45
+
46
+ ### Core AI Engine
47
+ - **Strict Language Matching**: Optimized CRITICAL RULE 2 in the System Prompt. The AI now completely ignores historical chat language context and strictly matches the language of the user's latest prompt.
48
+
8
49
  ## [26.6.5] - 2026-06-04 (Hotfix Patch)
9
50
  ### Fixed
10
51
  - **NPM Monorepo Resolution:** Synced `@inquirer/search` and `duck-duck-scrape` to root `package.json` to prevent `MODULE_NOT_FOUND` and `ERR_CONNECTION_REFUSED` on global installations.
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  # Nyxora Agent 🤖
2
- **Dual-Engine AI Agent: Bridging On-Chain Execution with Off-Chain Automation.**
2
+ **Your Personal Web3 Assistant.**
3
3
 
4
4
 
5
5
  [![MCP Supported](https://img.shields.io/badge/MCP-Supported-blue.svg)](#)
@@ -27,6 +27,7 @@ It operates under an institutional-grade **Cryptographically Bound Human-in-the-
27
27
 
28
28
  ### 🌐 Web3 Skills (On-Chain)
29
29
  * **Security Scanner**: Nyxora can scan smart contracts via GoPlus Labs to detect Honeypots, Hidden Taxes, and malicious proxy upgrades before you buy.
30
+ * **Anti-MEV Slippage Protection**: Hardened routing engine with dynamic Slippage Tolerance (default 0.5%) for Relay and Li.Fi. You can manually adjust slippage via the UI or dynamically override it using natural language (e.g., "Swap 1 ETH to PEPE with 10% slippage").
30
31
  * **Automated Take Profit (TP) & Cut Loss (CL)**: The trader's holy grail. Set natural language rules (e.g., "Sell my PEPE if price drops below $0.001"). Nyxora runs a background cron monitor and executes the swap while you sleep.
31
32
  * **Cross-Chain Hybrid Market Scanner**: Real-time asset tracking combining CoinGecko global data with DexScreener on-chain metrics across Ethereum, Base, Solana, BSC, and more.
32
33
  * **"Lean Degen" Auto-Whitelist**: Automatically intercepts Contract Addresses (CAs) whenever you check balances or swap tokens, saving them to your localized `user_whitelist.json` for future tracking.
@@ -42,6 +43,7 @@ It operates under an institutional-grade **Cryptographically Bound Human-in-the-
42
43
  * **Dynamic Trending Tokens**: Live top 5 crypto assets feed directly injected into the dashboard, completely clickable for instant AI market analysis.
43
44
  * **Premium Utility-Centric UI**: A sleek, dark-themed dashboard built for high readability and professional Web3 execution, featuring Pseudo-Generative UI widgets (`<BalanceWidget>`, `<MarketWidget>`, `<SwapWidget>`).
44
45
  * **Massive 2026 Model Roster**: Out-of-the-box support for cutting-edge models via Google Gemini, OpenAI, Groq, Mistral, xAI, DeepSeek, OpenRouter, and local Ollama, equipped with a searchable CLI prompt to instantly find your favorite model.
46
+ * **Strict NLP Exactness (Rule 8)**: The AI is rigorously instructed never to hallucinate or guess missing transaction parameters (like destination chains or swap amounts). It halts and requests human clarification, guaranteeing 100% precision.
45
47
  * **Context Overrides Defaults (NLP Intelligence)**: The Dashboard configuration (default chain & router) acts only as a safety net. If you issue an explicit command via Telegram (e.g., *"Swap 10 USDC to USDT on Arbitrum using Li.Fi"*), the NLP engine dynamically bypasses the default settings and executes exactly what you asked for, ensuring maximum flexibility.
46
48
  * **Deep Personalization**: Feed the agent custom rules via `user.md` and define its core persona via `IDENTITY.md`.
47
49
 
@@ -107,10 +109,10 @@ npm run build
107
109
  # 3. Interactive Setup Wizard (API Keys, Wallet, Telegram)
108
110
  npm run setup
109
111
 
110
- # 4. Start the Development Server (Single-Command Boot)
111
- # This will start the backend vault/services and the frontend Dashboard simultaneously
112
- npm run dev
112
+ # 4. Start the Application
113
+ npm start
113
114
  ```
115
+ *(If you are actively developing and modifying the source code, use `npm run dev` to enable hot-reloading for the frontend and backend).*
114
116
  > **⚠️ IMPORTANT:** Whenever you re-run `npm run setup` or manually edit the config files, you **must restart the dev server** for the changes to take effect.
115
117
 
116
118
  ---
package/SECURITY.md CHANGED
@@ -78,7 +78,16 @@ To prevent Supply Chain Attacks, the sandbox **permanently blacklists** critical
78
78
  * `child_process`: Plugins cannot spawn silent background terminals or malicious `curl | bash` supply chain payloads.
79
79
  * `os`, `net`, `cluster`: Blocked to prevent network-level exploitation.
80
80
 
81
- ## 5. Reporting Vulnerabilities
81
+ ## 5. Anti-MEV & Slippage Defense
82
+
83
+ To protect user funds from front-running and Maximal Extractable Value (MEV) attacks, Nyxora strictly enforces a **Default Slippage Tolerance of 0.5%** for all decentralized exchange (DEX) routing via Li.Fi and Relay.
84
+
85
+ Unlike typical web3 interfaces that might expose you to unlimited slippage if left unconfigured, Nyxora's backend hardcodes this protection layer into the API payload.
86
+ If an AI agent attempts to execute a swap without explicit slippage instructions, the `swapToken` and `bridgeToken` engines will automatically inject the `0.5%` boundary.
87
+
88
+ Users can safely override this limit globally via the Dashboard UI Settings or dynamically via NLP chat commands for specific high-volatility pairs (e.g., "Swap with 10% slippage").
89
+
90
+ ## 6. Reporting Vulnerabilities
82
91
 
83
92
  If you discover a vulnerability in the Nyxora architecture, please DO NOT open a public issue.
84
93
  Instead, email the core maintainer directly at **ainyxor@gmail.com**.
package/bin/nyxora.mjs CHANGED
@@ -63,7 +63,14 @@ async function start() {
63
63
  } catch(e) {}
64
64
  }
65
65
 
66
- const child = spawn('npx', ['ts-node', '-T', 'launcher.ts'], {
66
+ const compiledLauncher = path.join(projectRoot, 'dist', 'launcher.js');
67
+ const useCompiled = fs.existsSync(compiledLauncher);
68
+ const cmd = useCompiled ? 'node' : 'npx';
69
+ const args = useCompiled ? [compiledLauncher] : ['ts-node', '-T', 'launcher.ts'];
70
+
71
+ if (useCompiled) console.log('⚡ Using pre-compiled JS for blazing fast startup...');
72
+
73
+ const child = spawn(cmd, args, {
67
74
  cwd: projectRoot,
68
75
  detached: true,
69
76
  stdio: ['ignore', out, err],
@@ -199,7 +206,25 @@ Comment=Start Nyxora in the background
199
206
 
200
207
  async function setup() {
201
208
  console.log("Running Nyxora Setup Wizard...");
202
- const child = spawn('npx', ['ts-node', '-T', 'packages/core/src/gateway/setup-cli.ts'], {
209
+ const compiledSetup = path.join(projectRoot, 'dist', 'packages/core/src/gateway/setup-cli.js');
210
+ const useCompiled = fs.existsSync(compiledSetup);
211
+ const cmd = useCompiled ? 'node' : 'npx';
212
+ const args = useCompiled ? [compiledSetup] : ['ts-node', '-T', 'packages/core/src/gateway/setup-cli.ts'];
213
+ const child = spawn(cmd, args, {
214
+ cwd: projectRoot,
215
+ stdio: 'inherit',
216
+ env: { ...process.env, TS_NODE_CACHE: 'false' }
217
+ });
218
+
219
+ await new Promise(resolve => child.on('close', resolve));
220
+ }
221
+
222
+ async function clearMemory(cliArgs) {
223
+ const compiledCli = path.join(projectRoot, 'dist', 'packages/core/src/gateway/cli.js');
224
+ const useCompiled = fs.existsSync(compiledCli);
225
+ const cmd = useCompiled ? 'node' : 'npx';
226
+ const args = useCompiled ? [compiledCli, 'clear', ...cliArgs] : ['ts-node', '-T', 'packages/core/src/gateway/cli.ts', 'clear', ...cliArgs];
227
+ const child = spawn(cmd, args, {
203
228
  cwd: projectRoot,
204
229
  stdio: 'inherit',
205
230
  env: { ...process.env, TS_NODE_CACHE: 'false' }
@@ -208,8 +233,12 @@ async function setup() {
208
233
  await new Promise(resolve => child.on('close', resolve));
209
234
  }
210
235
 
211
- async function clearMemory(args) {
212
- const child = spawn('npx', ['ts-node', '-T', 'packages/core/src/gateway/cli.ts', 'clear', ...args], {
236
+ async function setKey(cliArgs) {
237
+ const compiledCli = path.join(projectRoot, 'dist', 'packages/core/src/gateway/cli.js');
238
+ const useCompiled = fs.existsSync(compiledCli);
239
+ const cmd = useCompiled ? 'node' : 'npx';
240
+ const args = useCompiled ? [compiledCli, 'set-key', ...cliArgs] : ['ts-node', '-T', 'packages/core/src/gateway/cli.ts', 'set-key', ...cliArgs];
241
+ const child = spawn(cmd, args, {
213
242
  cwd: projectRoot,
214
243
  stdio: 'inherit',
215
244
  env: { ...process.env, TS_NODE_CACHE: 'false' }
@@ -222,6 +251,7 @@ async function main() {
222
251
  switch (command) {
223
252
  case 'setup': await setup(); break;
224
253
  case 'clear': await clearMemory(process.argv.slice(3)); break;
254
+ case 'set-key': await setKey(process.argv.slice(3)); break;
225
255
  case 'start': await start(); break;
226
256
  case 'stop': await stop(); break;
227
257
  case 'restart': await restart(); break;
@@ -238,7 +268,7 @@ async function main() {
238
268
  break;
239
269
  default:
240
270
  console.log(`
241
- Nyxora CLI Manager
271
+ Nyxora CLI Manager - Your Personal Web3 Assistant
242
272
  Usage: nyxora <command>
243
273
 
244
274
  Commands:
@@ -250,9 +280,11 @@ Commands:
250
280
  clear Atomically clear the AI's short/long-term memory SQLite database
251
281
  clean-logs Clear the daemon logs
252
282
  autostart Enable/disable autostart on boot (usage: nyxora autostart enable)
283
+ set-key Securely save API Key (usage: nyxora set-key <provider> <key>)
253
284
 
254
285
  Options:
255
286
  -v, --version Show current version
287
+ -h, --help Show this help menu
256
288
  `);
257
289
  }
258
290
  }
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.cancelLimitOrderToolDefinition = exports.listLimitOrdersToolDefinition = exports.createLimitOrderToolDefinition = exports.limitOrderManager = exports.LimitOrderManager = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const parser_1 = require("../config/parser");
9
+ const paths_1 = require("../config/paths");
10
+ const config_1 = require("../web3/config");
11
+ const tokens_1 = require("../web3/utils/tokens");
12
+ const swapToken_1 = require("../web3/skills/swapToken");
13
+ const transactionManager_1 = require("./transactionManager");
14
+ const reasoning_1 = require("./reasoning");
15
+ class LimitOrderManager {
16
+ filePath;
17
+ orders = [];
18
+ monitorInterval = null;
19
+ constructor() {
20
+ const config = (0, parser_1.loadConfig)();
21
+ this.filePath = (0, paths_1.getPath)(config.memory?.path ? config.memory.path.replace('memory.json', 'orders.json') : 'orders.json');
22
+ this.loadOrders();
23
+ }
24
+ loadOrders() {
25
+ if (fs_1.default.existsSync(this.filePath)) {
26
+ try {
27
+ const data = fs_1.default.readFileSync(this.filePath, 'utf-8');
28
+ this.orders = JSON.parse(data);
29
+ }
30
+ catch (error) {
31
+ this.orders = [];
32
+ }
33
+ }
34
+ }
35
+ saveOrders() {
36
+ try {
37
+ fs_1.default.writeFileSync(this.filePath, JSON.stringify(this.orders, null, 2));
38
+ }
39
+ catch (error) { }
40
+ }
41
+ createOrder(chainName, fromToken, toToken, amountStr, targetPriceUsd, condition) {
42
+ const id = `order_${Date.now()}_${Math.random().toString(36).substr(2, 5)}`;
43
+ const order = {
44
+ id, chainName, fromToken, toToken, amountStr, targetPriceUsd, condition, status: 'pending', createdAt: Date.now()
45
+ };
46
+ this.orders.push(order);
47
+ this.saveOrders();
48
+ return `Limit order created successfully. ID: ${id}. The system will monitor ${fromToken} price on ${chainName} and execute the swap to ${toToken} when price is ${condition} $${targetPriceUsd}.`;
49
+ }
50
+ listOrders() {
51
+ const pending = this.orders.filter(o => o.status === 'pending');
52
+ if (pending.length === 0)
53
+ return "No active limit orders.";
54
+ let report = "Active Limit Orders:\n";
55
+ pending.forEach(o => {
56
+ report += `- [${o.id}] Swap ${o.amountStr} ${o.fromToken} -> ${o.toToken} on ${o.chainName} when ${o.fromToken} is ${o.condition} $${o.targetPriceUsd}\n`;
57
+ });
58
+ return report;
59
+ }
60
+ cancelOrder(id) {
61
+ const order = this.orders.find(o => o.id === id);
62
+ if (!order)
63
+ return `Order ${id} not found.`;
64
+ if (order.status !== 'pending')
65
+ return `Order ${id} cannot be cancelled because it is ${order.status}.`;
66
+ order.status = 'cancelled';
67
+ this.saveOrders();
68
+ return `Order ${id} cancelled successfully.`;
69
+ }
70
+ startMonitor() {
71
+ if (this.monitorInterval)
72
+ clearInterval(this.monitorInterval);
73
+ // Monitor every 60 seconds
74
+ this.monitorInterval = setInterval(() => this.checkOrders(), 60000);
75
+ console.log('[LimitOrderManager] Order monitoring started (interval: 60s)');
76
+ }
77
+ async checkOrders() {
78
+ const pending = this.orders.filter(o => o.status === 'pending');
79
+ if (pending.length === 0)
80
+ return;
81
+ for (const order of pending) {
82
+ try {
83
+ let tokenAddress = (0, tokens_1.resolveToken)(order.fromToken, order.chainName);
84
+ if (tokenAddress === "0x0000000000000000000000000000000000000000") {
85
+ tokenAddress = (0, tokens_1.resolveToken)("W" + order.fromToken, order.chainName);
86
+ }
87
+ const res = await fetch(`https://api.dexscreener.com/latest/dex/tokens/${tokenAddress}`);
88
+ if (!res.ok)
89
+ continue;
90
+ const data = await res.json();
91
+ if (!data.pairs || data.pairs.length === 0)
92
+ continue;
93
+ let pair = data.pairs.find((p) => p.chainId === order.chainName) || data.pairs[0];
94
+ const currentPrice = parseFloat(pair.priceUsd);
95
+ let shouldExecute = false;
96
+ if (order.condition === 'above' && currentPrice >= order.targetPriceUsd)
97
+ shouldExecute = true;
98
+ if (order.condition === 'below' && currentPrice <= order.targetPriceUsd)
99
+ shouldExecute = true;
100
+ if (shouldExecute) {
101
+ console.log(`[LimitOrderManager] Condition met for order ${order.id}. Current price $${currentPrice} is ${order.condition} $${order.targetPriceUsd}. Executing...`);
102
+ // 1. Prepare Swap
103
+ const prepareResult = await (0, swapToken_1.prepareSwapToken)(order.chainName, order.fromToken, order.toToken, order.amountStr, 'auto');
104
+ // 2. Extract Tx ID
105
+ const txMatch = prepareResult.match(/Transaction ID: ([\w-]+)\./);
106
+ if (!txMatch) {
107
+ order.status = 'failed';
108
+ this.saveOrders();
109
+ (0, reasoning_1.processUserInput)(`Limit order ${order.id} execution failed during preparation. Output: ${prepareResult}`, 'system').catch(() => { });
110
+ continue;
111
+ }
112
+ const txId = txMatch[1];
113
+ const tx = transactionManager_1.txManager.getTransaction(txId);
114
+ if (!tx)
115
+ throw new Error("Transaction not found in manager");
116
+ // 3. Execute Swap automatically (bypass policy with autoApprove: true)
117
+ const executeResult = await (0, swapToken_1.executeSwap)(order.chainName, tx.details, true);
118
+ if (executeResult.includes('executed') || executeResult.includes('successful')) {
119
+ transactionManager_1.txManager.updateStatus(txId, 'executed', executeResult);
120
+ order.status = 'executed';
121
+ this.saveOrders();
122
+ (0, reasoning_1.processUserInput)(`Limit order ${order.id} just EXECUTED automatically! Price hit $${currentPrice}. Swap result: ${executeResult}. Please notify the user immediately!`, 'system').catch(() => { });
123
+ }
124
+ else {
125
+ transactionManager_1.txManager.updateStatus(txId, 'failed', executeResult);
126
+ order.status = 'failed';
127
+ this.saveOrders();
128
+ (0, reasoning_1.processUserInput)(`Limit order ${order.id} FAILED to execute. Price hit $${currentPrice} but execution failed: ${executeResult}. Please notify the user.`, 'system').catch(() => { });
129
+ }
130
+ }
131
+ }
132
+ catch (error) {
133
+ console.error(`[LimitOrderManager] Error checking order ${order.id}:`, error.message);
134
+ }
135
+ }
136
+ }
137
+ }
138
+ exports.LimitOrderManager = LimitOrderManager;
139
+ exports.limitOrderManager = new LimitOrderManager();
140
+ exports.createLimitOrderToolDefinition = {
141
+ type: "function",
142
+ function: {
143
+ name: "create_limit_order",
144
+ description: "Creates an automatic cut-loss or take-profit limit order. The system will automatically execute the swap when the price condition is met.",
145
+ parameters: {
146
+ type: "object",
147
+ properties: {
148
+ chainName: { type: "string", enum: config_1.SUPPORTED_CHAIN_NAMES },
149
+ fromToken: { type: "string", description: "Token to sell" },
150
+ toToken: { type: "string", description: "Token to buy" },
151
+ amountStr: { type: "string", description: "Amount to sell" },
152
+ targetPriceUsd: { type: "number", description: "Target price in USD for the fromToken" },
153
+ condition: { type: "string", enum: ["above", "below"], description: "Trigger when price goes above (take-profit) or below (cut-loss) target" }
154
+ },
155
+ required: ["chainName", "fromToken", "toToken", "amountStr", "targetPriceUsd", "condition"],
156
+ },
157
+ },
158
+ };
159
+ exports.listLimitOrdersToolDefinition = {
160
+ type: "function",
161
+ function: {
162
+ name: "list_limit_orders",
163
+ description: "Lists all active automated limit orders.",
164
+ parameters: { type: "object", properties: {}, required: [] },
165
+ },
166
+ };
167
+ exports.cancelLimitOrderToolDefinition = {
168
+ type: "function",
169
+ function: {
170
+ name: "cancel_limit_order",
171
+ description: "Cancels an active limit order by ID.",
172
+ parameters: {
173
+ type: "object",
174
+ properties: { id: { type: "string" } },
175
+ required: ["id"],
176
+ },
177
+ },
178
+ };