@darksol/terminal 0.11.0 → 0.13.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.
@@ -0,0 +1,241 @@
1
+ # @darksol/terminal — Full Audit Report
2
+ **Version:** 0.12.0 | **Test run:** 130 pass / 0 fail | **Files reviewed:** 47
3
+ **Date:** 2026-03-14
4
+
5
+ ---
6
+
7
+ ## 1. Architecture Overview
8
+
9
+ **Entry point:** `bin/darksol.js` → `src/cli.js` (Commander.js, ESM, Node ≥18)
10
+
11
+ ```
12
+ src/
13
+ ├── cli.js ← 1500+ line monolith; all commands wired here
14
+ ├── agent/ ← LLM tool-calling loop (OpenAI/Anthropic function-calling)
15
+ │ ├── index.js, loop.js, autonomous.js, strategy-evaluator.js, tools.js
16
+ ├── config/
17
+ │ ├── store.js ← conf-backed typed config
18
+ │ └── keys.js ← AES-256-GCM encrypted API key vault
19
+ ├── daemon/ ← generic service registry (start/stop/status/PID)
20
+ ├── llm/
21
+ │ ├── engine.js ← multi-provider (OpenAI/Anthropic/OpenRouter/Ollama)
22
+ │ ├── intent.js ← NL → structured intent parser
23
+ │ └── models.js ← model catalog + capability metadata
24
+ ├── memory/index.js ← JSON append-log memory
25
+ ├── scripts/engine.js ← user script CRUD + new Function() executor
26
+ ├── services/ ← 14 service modules (casino, oracle, cards, facilitator,
27
+ │ gas, lifi, market, mail, builders, telegram, watch,
28
+ │ whale, whale-monitor, skills, browser)
29
+ ├── soul/index.js ← agent personality/tone
30
+ ├── trading/ ← swap.js, snipe.js, dca.js
31
+ ├── ui/ ← chalk, ora, cli-table3 wrappers
32
+ ├── utils/ ← fetch.js, helpers.js, x402.js
33
+ ├── wallet/ ← keystore, manager, agent-signer, portfolio, history
34
+ └── web/ ← embedded web terminal (http.createServer)
35
+ ```
36
+
37
+ **Dep graph:** cli.js imports from virtually every layer. Services are leaf nodes. x402.js is depended on by poker, oracle, casino. whale-monitor.js has a side-effect import (calls registerService at load).
38
+
39
+ ---
40
+
41
+ ## 2. Code Quality
42
+
43
+ ### ✅ Positives
44
+ - Consistent spinner → success/fail pattern across all services
45
+ - Good JSDoc on public functions
46
+ - Clean separation: config/store vs config/keys vs wallet/keystore
47
+ - Dependency injection on poker.js and whale.js makes them genuinely testable
48
+ - 130 tests passing, zero failures
49
+
50
+ ### ❌ Issues
51
+ - **`warn` not imported in cards.js** — will crash with ReferenceError on invalid denomination/provider
52
+ - **`formatCompact()` duplicated** in market.js (already exists in utils/helpers.js)
53
+ - **`topMovers()` makes unused HTTP call** — fetches trending endpoint, discards result
54
+ - **ERC-20 ABI fragments duplicated** across swap.js, portfolio.js, whale.js, scripts/engine.js
55
+ - **Explorer API URLs duplicated** between wallet/history.js and services/whale.js
56
+ - **ora + nanospinner both in deps** — redundant spinner libraries
57
+ - **cli.js is 1500+ lines** — should split into command modules
58
+ - **Error handling inconsistent** — most use spin.fail(), but watch.js and market.js use raw console.log
59
+
60
+ ---
61
+
62
+ ## 3. Security Review
63
+
64
+ ### 🔴 CRITICAL — x402 nonce uses Math.random()
65
+
66
+ **File:** `src/utils/x402.js`
67
+
68
+ EIP-3009 nonce is generated with Math.random() — NOT cryptographically secure. This nonce authorizes USDC transfers on mainnet. A compromised PRNG seed allows replay attacks.
69
+
70
+ **Fix:** `import { randomBytes } from 'crypto'; const nonce = '0x' + randomBytes(32).toString('hex');`
71
+
72
+ ### 🟠 HIGH — Key vault uses machine-derived password
73
+
74
+ **File:** `src/config/keys.js`
75
+
76
+ API keys stored via wizard are encrypted with `darksol-vault-${hostname()}-${username}` — predictable, derivable by any process running as the same user. Users aren't warned.
77
+
78
+ **Fix:** Document weak vs strong protection clearly. Better: OS keychain or prompted master password.
79
+
80
+ ### 🟠 HIGH — Script execution is not sandboxed
81
+
82
+ **File:** `src/scripts/engine.js`
83
+
84
+ `new Function()` executes in global scope with full Node.js access. The unlocked private key signer is passed into script context. This is correct for user scripts, but needs a bold warning before execution.
85
+
86
+ ### 🟡 MEDIUM — node-fetch `timeout` silently ignored
87
+
88
+ **Files:** `src/utils/x402.js`, `src/services/browser.js`
89
+
90
+ node-fetch v3 dropped the timeout option. Calls with `{ timeout: 2000 }` will block indefinitely on hung connections.
91
+
92
+ **Fix:** Use `AbortSignal.timeout(2000)` or manual AbortController.
93
+
94
+ ### 🟡 MEDIUM — Etherscan API key not applied in history.js
95
+
96
+ `wallet/history.js` builds URLs without auth, unlike `services/whale.js` which uses `getApiKey('etherscan')`. Rate limited to 5 req/s unauthenticated.
97
+
98
+ ### 🟢 LOW — ETH price hardcoded fallback $3000
99
+
100
+ `gas.js` and `portfolio.js` silently fall back to $3000 if CoinGecko is unreachable. No warning shown.
101
+
102
+ ### 🟢 LOW — Web server binds 0.0.0.0
103
+
104
+ `src/web/server.js` binds all interfaces. Anyone on LAN can interact with the web terminal. Should default to 127.0.0.1.
105
+
106
+ ---
107
+
108
+ ## 4. Bug Hunt
109
+
110
+ ### 🔴 BUG — `warn` not imported in cards.js
111
+ Any call to `cardsOrder()` with invalid denomination/provider throws `ReferenceError: warn is not defined`. Quick fix: add `warn` to the import.
112
+
113
+ ### 🔴 BUG — DCA `runDCA()` never executes actual swaps
114
+ `src/trading/dca.js` — the executor marks orders as complete without calling `executeSwap`. Users see "DCA execution complete" for orders that were never traded. No "simulation mode" warning.
115
+
116
+ ### 🟠 BUG — `watchSnipe` auto-snipe logic is absent
117
+ `src/trading/snipe.js` — subscribes to newBlockHeaders and logs block numbers, but never calls `snipeToken()`. The feature is a skeleton.
118
+
119
+ ### 🟠 BUG — Race condition in autonomous strategy loop
120
+ `src/agent/autonomous.js` — `setInterval(runStrategyCycle, interval)` can fire overlapping cycles if one takes longer than the interval, risking duplicate trades. Should use setTimeout with re-scheduling.
121
+
122
+ ### 🟡 BUG — Silent error swallowing in whale monitor
123
+ `src/services/whale-monitor.js` — `pollTrackedWallets().catch(() => {})` swallows all errors silently. No visibility into whether monitoring is working or failing.
124
+
125
+ ### 🟡 BUG — topMovers() wasted HTTP call
126
+ `src/services/market.js` — fetches trending endpoint, result is completely discarded.
127
+
128
+ ### 🟡 BUG — Snipe slippage BigInt conversion
129
+ `src/trading/snipe.js` — potential precision issues in slippage math with BigInt conversions.
130
+
131
+ ---
132
+
133
+ ## 5. Test Coverage
134
+
135
+ ### ✅ Well-tested
136
+ - CLI command structure (cli.test.js)
137
+ - Config store (config.test.js)
138
+ - Keystore encryption (keystore.test.js)
139
+ - Agent loop + tools (agent-loop.test.js, agent-tools.test.js)
140
+ - Autonomous strategy (autonomous.test.js)
141
+ - DCA CRUD (dca.test.js)
142
+ - Trading validation (trading.test.js)
143
+ - Poker logic (poker.test.js)
144
+ - Script engine (scripts.test.js)
145
+ - LLM providers (llm-providers.test.js)
146
+ - Telegram bot (telegram.test.js)
147
+ - UI components (ui.test.js)
148
+ - Daemon management (daemon.test.js)
149
+ - Helpers (helpers.test.js)
150
+
151
+ ### ❌ Not tested
152
+ - x402 payment flow (critical path, no tests)
153
+ - Casino service (real payment flow, no tests)
154
+ - Oracle service (no tests)
155
+ - Cards service (no tests — has the warn bug)
156
+ - LI.FI bridge integration (no tests)
157
+ - Web server/terminal (no tests)
158
+ - Wallet portfolio scanning (no tests)
159
+ - Whale monitor polling (no tests)
160
+ - Agent signer HTTP daemon (no tests)
161
+ - Facilitator service (no tests)
162
+
163
+ ### Assessment
164
+ 130 tests at 0 failures is solid. But the most dangerous code paths (x402 payments, casino bets, agent signer) have zero coverage. The things that move money are untested.
165
+
166
+ ---
167
+
168
+ ## 6. Dependency Health
169
+
170
+ **19 runtime deps** — reasonable for scope, but:
171
+ - **ora + nanospinner** — duplicate spinners, pick one
172
+ - **blessed + blessed-contrib** — only used in dashboard.js, heavyweight for optional UI
173
+ - **node-fetch** — Node 18+ has native fetch; could eliminate this dep entirely
174
+ - **agentmail** — external dependency for mail service, review update frequency
175
+ - **ethers v6** — correct and current
176
+ - **ws** — needed for WebSocket (snipe block watcher, web terminal)
177
+
178
+ No known CVEs in current dep tree. Supply chain risk is low — all deps are well-maintained mainstream packages.
179
+
180
+ ---
181
+
182
+ ## 7. UX Issues
183
+
184
+ - **DCA "complete" messages are lies** — users think trades executed when they didn't
185
+ - **Snipe watcher gives false confidence** — shows "watching..." but never snipes
186
+ - **Key vault setup doesn't warn about protection level** — users assume their keys are safe
187
+ - **Web terminal on 0.0.0.0 with no auth** — anyone on LAN gets full CLI access
188
+ - **`hasSoul()` OLLAMA_HOST validation** — rejects bare hostnames without telling user to add http://
189
+ - **cli.js is massive** — `darksol --help` works but finding specific subcommand help requires digging
190
+
191
+ ---
192
+
193
+ ## 8. Performance
194
+
195
+ - **Startup:** Importing all 14 services on CLI boot regardless of which command runs. Lazy imports would cut cold start significantly.
196
+ - **whale-monitor processed Set:** Grows unbounded, trims at 1000→500 but could accumulate over days
197
+ - **node-fetch timeouts broken** — hung connections block indefinitely (see security section)
198
+ - **topMovers double fetch** — wasted HTTP request on every call
199
+
200
+ ---
201
+
202
+ ## 9. Missing Features / Incomplete Code
203
+
204
+ - **DCA execution** — CRUD works, execution is a stub
205
+ - **Snipe auto-buy** — block watcher works, token detection is absent
206
+ - **Whale mirror trading** — detected but not acted on
207
+ - **Desktop app** — Electron scaffold at desktop/, not packaged
208
+ - **MCP integration** — referenced in memory but not in current source
209
+
210
+ ---
211
+
212
+ ## 10. Prioritized Recommendations
213
+
214
+ ### 🔴 Critical (fix before next release)
215
+ 1. **x402 nonce: replace Math.random() with crypto.randomBytes()** — replay attack vector on mainnet USDC
216
+ 2. **cards.js: add `warn` to import** — crashes on invalid input
217
+ 3. **DCA: add clear "SIMULATION ONLY" warning or wire up real swaps** — users think trades execute
218
+
219
+ ### 🟠 High (fix soon)
220
+ 4. **node-fetch timeout: use AbortController** — prevents indefinite hangs
221
+ 5. **Web server: default to 127.0.0.1** — close LAN exposure
222
+ 6. **Autonomous strategy: replace setInterval with setTimeout chain** — prevent duplicate trades
223
+ 7. **Add tests for x402, casino, agent-signer** — the money-moving code needs coverage
224
+
225
+ ### 🟡 Medium (next sprint)
226
+ 8. **Deduplicate ERC-20 ABI, Explorer URLs, formatCompact** — DRY cleanup
227
+ 9. **Remove unused topMovers trending fetch**
228
+ 10. **Etherscan API key in history.js**
229
+ 11. **Lazy-load service imports in cli.js**
230
+ 12. **Split cli.js into command modules**
231
+
232
+ ### 🟢 Nice-to-have
233
+ 13. Remove ora (keep nanospinner) or vice versa
234
+ 14. Drop node-fetch, use native fetch
235
+ 15. ETH price fallback warning
236
+ 16. Script execution safety warning UI
237
+ 17. Key vault protection level documentation
238
+
239
+ ---
240
+
241
+ **Bottom line:** The architecture is solid and well-organized for its scope. 130 passing tests is strong. The critical issues are concentrated in the financial paths — x402 nonce security, DCA phantom execution, and untested payment flows. Fix those three and this is a genuinely impressive CLI platform.
package/README.md CHANGED
@@ -15,7 +15,7 @@ A unified CLI for market intel, trading, AI-powered analysis, on-chain oracle, c
15
15
  [![License: GPL-3.0](https://img.shields.io/badge/License-GPL--3.0-gold.svg)](https://www.gnu.org/licenses/gpl-3.0)
16
16
  [![Node](https://img.shields.io/badge/node-%3E%3D18.0.0-green.svg)](https://nodejs.org/)
17
17
 
18
- - Current release: **0.11.0**
18
+ - Current release: **0.12.0**
19
19
  - Changelog: `CHANGELOG.md`
20
20
 
21
21
  ## Install
@@ -56,6 +56,15 @@ darksol bridge send --from base --to arbitrum --token ETH -a 0.1
56
56
  darksol bridge status 0xTxHash...
57
57
  darksol bridge chains
58
58
 
59
+ # Cross-DEX arbitrage
60
+ darksol arb scan --chain base # one-shot price comparison
61
+ darksol arb monitor --chain base --execute # real-time block-by-block scanning
62
+ darksol arb config # set thresholds, dry-run, DEXes
63
+ darksol arb add-endpoint base wss://your-quicknode # faster with WSS endpoints
64
+ darksol arb add-pair WETH AERO # add pairs to scan
65
+ darksol arb stats --days 7 # PnL history
66
+ darksol arb info # setup guide + risk warnings
67
+
59
68
  # Set up your agent identity
60
69
  darksol soul
61
70
 
@@ -128,6 +137,7 @@ Useful web-shell commands:
128
137
  ```bash
129
138
  help # clickable command menu (arrow keys + Enter)
130
139
  trade # interactive swap / snipe / bridge menu
140
+ arb # cross-DEX arbitrage scanner
131
141
  bridge # cross-chain bridge (LI.FI)
132
142
  send # interactive token transfer
133
143
  wallet # interactive wallet picker and actions
@@ -150,6 +160,9 @@ ai <prompt> # chat with trading assistant
150
160
  | `dca` | Dollar-cost averaging engine | Gas only |
151
161
  | `soul` | Agent identity & personality configuration | Free |
152
162
  | `memory` | Persistent cross-session memory store | Free |
163
+ | `whale` | Whale Radar — track wallets, copy-trade, live feed | Free |
164
+ | `dash` | Live TUI dashboard — portfolio, prices, gas, whale feed | Free |
165
+ | `auto` | Autonomous Trader — goal-based automated execution | Provider dependent |
153
166
  | `agent task` | Autonomous ReAct agent loop with tool use | Provider dependent |
154
167
  | `ai` | LLM-powered trading assistant & intent execution | Provider dependent |
155
168
  | `agent` | Secure agent signer (PK-isolated proxy) | Free |
@@ -176,6 +189,98 @@ ai <prompt> # chat with trading assistant
176
189
 
177
190
  ---
178
191
 
192
+ ## 🐋 Whale Radar
193
+
194
+ Track any wallet across 5 chains. Get alerts on swaps, transfers, new tokens. Enable copy-trading to mirror a whale's moves automatically.
195
+
196
+ ```bash
197
+ # Track a wallet
198
+ darksol whale track 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045 --label "vitalik" --chain ethereum
199
+
200
+ # List all tracked wallets
201
+ darksol whale list
202
+
203
+ # View recent activity
204
+ darksol whale activity 0xd8dA... --limit 20
205
+
206
+ # Enable copy-trading (mirrors swaps with your own limits)
207
+ darksol whale mirror 0xd8dA... --max 50 --slippage 2 --dry-run
208
+
209
+ # Open the live feed (blessed TUI)
210
+ darksol whale feed
211
+
212
+ # Stop tracking
213
+ darksol whale stop 0xd8dA...
214
+ ```
215
+
216
+ - **5-chain support:** Base, Ethereum, Arbitrum, Polygon, Optimism
217
+ - **Swap decoding:** Uniswap V2 + V3 router signatures automatically parsed
218
+ - **Copy-trading:** Mirror whale swaps with budget caps, slippage limits, dry-run mode
219
+ - **Live feed:** Real-time blessed terminal UI with whale events streaming
220
+ - **Daemon integration:** Runs as a background service, feeds alerts to Telegram bot
221
+ - **Event system:** Subscribe to `whale:swap`, `whale:transfer`, `whale:newtoken`, `whale:mirror-executed`
222
+
223
+ ---
224
+
225
+ ## 📊 Live Dashboard
226
+
227
+ Full-screen terminal dashboard. Portfolio, prices, gas, transactions, whale alerts — all updating in real-time.
228
+
229
+ ```bash
230
+ # Launch the dashboard
231
+ darksol dash
232
+
233
+ # Custom refresh interval
234
+ darksol dash --refresh 15
235
+
236
+ # Compact mode (portfolio + prices only)
237
+ darksol dash --compact
238
+ ```
239
+
240
+ - **Portfolio summary** — total value, token balances, chain breakdown
241
+ - **Price ticker** — sparkline micro-charts for tracked tokens
242
+ - **Gas gauge** — current gas prices across all 5 chains
243
+ - **Recent transactions** — last 10 txs from wallet history
244
+ - **Whale feed** — live alerts when whale monitor is running
245
+ - **Keyboard shortcuts:** `q` quit, `r` refresh, `tab` cycle focus, `w` toggle whales, `1-5` switch chains
246
+ - **DARKSOL gold/dark theme** throughout
247
+
248
+ ---
249
+
250
+ ## 🤖 Autonomous Trader
251
+
252
+ Set a goal in plain English. The AI builds a strategy, monitors the market, and executes trades within your budget and risk limits. Full audit trail on every decision.
253
+
254
+ ```bash
255
+ # Start an autonomous strategy
256
+ darksol auto start "accumulate ETH under 2400" --budget 500 --max-per-trade 50 --risk moderate
257
+
258
+ # DCA into memecoins
259
+ darksol auto start "DCA into BASE memecoins with >1M liquidity" --budget 200 --interval 15 --dry-run
260
+
261
+ # Check status
262
+ darksol auto status
263
+ darksol auto status auto_1741...
264
+
265
+ # View audit trail
266
+ darksol auto log auto_1741... --limit 20
267
+
268
+ # Stop a strategy
269
+ darksol auto stop auto_1741...
270
+
271
+ # List all strategies
272
+ darksol auto list
273
+ ```
274
+
275
+ - **Natural language goals** — parsed by LLM intent system into executable strategies
276
+ - **Three risk levels:** conservative (5% stop-loss), moderate (10%), aggressive (20%)
277
+ - **Kill switches:** budget exhaustion, max loss, error threshold — auto-stops immediately
278
+ - **Dry-run mode** — test strategies without executing real trades
279
+ - **Full audit log** — every decision, trade, and skip logged to `~/.darksol/autonomous/<id>/audit.json`
280
+ - **Event system:** `auto:started`, `auto:trade`, `auto:skipped`, `auto:stopped`, `auto:budget-hit`, `auto:error`
281
+
282
+ ---
283
+
179
284
  ## 📱 Telegram Bot
180
285
 
181
286
  Turn your terminal into a Telegram AI agent. Same brain (LLM + soul + memory), different mouth.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@darksol/terminal",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "DARKSOL Terminal — unified CLI for all DARKSOL services. Market intel, trading, oracle, casino, and more.",
5
5
  "type": "module",
6
6
  "bin": {