dexbot 1.6.11 → 1.6.13

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 (398) hide show
  1. package/CHANGELOG.md +67 -4
  2. package/README.md +2 -1
  3. package/analysis/README.md +11 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/analysis/tradingview/README.md +1 -1
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
  7. package/claw/README.md +1 -0
  8. package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
  9. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  10. package/claw/modules/chain_broadcast.ts +7 -1
  11. package/claw/modules/claw_bridge.ts +0 -3
  12. package/claw/modules/claw_launcher.ts +1 -1
  13. package/claw/modules/claw_skill_md.ts +1 -0
  14. package/claw/modules/launcher_mode_detector.ts +9 -2
  15. package/claw/package.json +3 -3
  16. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  17. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/account_resolver.d.ts +1 -1
  20. package/dist/analysis/account_resolver.js +2 -1
  21. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  22. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +3 -21
  23. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  24. package/dist/analysis/ama_fitting/fetch_lp_candles.js +55 -45
  25. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -8
  26. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +45 -24
  27. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +34 -78
  28. package/dist/analysis/analyze_args.d.ts +43 -0
  29. package/dist/analysis/analyze_args.js +61 -0
  30. package/dist/analysis/analyze_dynamic_weight.js +7 -17
  31. package/dist/analysis/analyze_kalman.js +7 -17
  32. package/dist/analysis/analyze_regime.js +7 -17
  33. package/dist/analysis/analyze_regime_windows.js +8 -18
  34. package/dist/analysis/analyze_risk_profile.js +8 -18
  35. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  36. package/dist/analysis/analyze_volatility.js +7 -17
  37. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +221 -28
  38. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +23 -103
  39. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  40. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +32 -150
  41. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  42. package/dist/analysis/bot_fitting/shared_utils.d.ts +77 -9
  43. package/dist/analysis/bot_fitting/shared_utils.js +125 -9
  44. package/dist/analysis/bot_key_utils.d.ts +18 -10
  45. package/dist/analysis/bot_key_utils.js +7 -4
  46. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  47. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  48. package/dist/analysis/chain_pool.d.ts +3 -1
  49. package/dist/analysis/chart_ui.d.ts +35 -3
  50. package/dist/analysis/chart_ui.js +43 -4
  51. package/dist/analysis/chart_utils.d.ts +5 -5
  52. package/dist/analysis/chart_utils.js +9 -0
  53. package/dist/analysis/fills_cache.d.ts +4 -24
  54. package/dist/analysis/fills_cache.js +3 -84
  55. package/dist/analysis/fills_source.d.ts +33 -3
  56. package/dist/analysis/fills_source.js +83 -13
  57. package/dist/analysis/grid_correction_check.d.ts +2 -24
  58. package/dist/analysis/grid_correction_check.js +27 -69
  59. package/dist/analysis/math_utils.d.ts +91 -6
  60. package/dist/analysis/math_utils.js +119 -7
  61. package/dist/analysis/pnl_report.js +29 -29
  62. package/dist/analysis/price_sources.d.ts +30 -9
  63. package/dist/analysis/price_sources.js +28 -4
  64. package/dist/analysis/resolve_bot_accounts.js +2 -2
  65. package/dist/analysis/resolve_source.d.ts +1 -1
  66. package/dist/analysis/resolve_source.js +31 -10
  67. package/dist/analysis/trade_profitability.d.ts +29 -2
  68. package/dist/analysis/trade_profitability.js +73 -147
  69. package/dist/analysis/tradingview/analyze_tradingview.d.ts +3 -8
  70. package/dist/analysis/tradingview/analyze_tradingview.js +7 -6
  71. package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
  72. package/dist/analysis/tradingview/grid_reset_config.js +23 -11
  73. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
  74. package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
  75. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  76. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -34
  77. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  78. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +26 -84
  79. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  80. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +16 -41
  81. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
  82. package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
  83. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  84. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  85. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  86. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  87. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  88. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  89. package/dist/analysis/worker_pool.d.ts +38 -0
  90. package/dist/analysis/worker_pool.js +67 -0
  91. package/dist/credential-daemon.js +34 -20
  92. package/dist/dexbot.js +78 -59
  93. package/dist/market_adapter/ama_signal_runner.js +21 -54
  94. package/dist/market_adapter/candle_utils.d.ts +29 -19
  95. package/dist/market_adapter/candle_utils.js +35 -21
  96. package/dist/market_adapter/cli_args.d.ts +22 -0
  97. package/dist/market_adapter/cli_args.js +30 -0
  98. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  99. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  100. package/dist/market_adapter/core/config_normalizers.js +11 -6
  101. package/dist/market_adapter/core/kibana_candles.d.ts +56 -19
  102. package/dist/market_adapter/core/kibana_candles.js +12 -9
  103. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  104. package/dist/market_adapter/core/kibana_client.js +8 -7
  105. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  106. package/dist/market_adapter/core/market_adapter_service.d.ts +320 -153
  107. package/dist/market_adapter/core/market_adapter_service.js +228 -269
  108. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  109. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  110. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  111. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  112. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  113. package/dist/market_adapter/core/strategies/ama.js +2 -4
  114. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  115. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  116. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  117. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  118. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  119. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  120. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
  121. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
  122. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  123. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  124. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  125. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  126. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  127. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  128. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  129. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  130. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  131. package/dist/market_adapter/inputs/fetch_book_data.js +3 -2
  132. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +160 -332
  133. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +50 -8
  134. package/dist/market_adapter/inputs/fetch_lp_data.js +47 -22
  135. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  136. package/dist/market_adapter/inputs/kibana_feed_source.js +26 -41
  137. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  138. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  139. package/dist/market_adapter/inputs/window_cache.d.ts +93 -156
  140. package/dist/market_adapter/inputs/window_cache.js +59 -184
  141. package/dist/market_adapter/interval_utils.d.ts +15 -5
  142. package/dist/market_adapter/interval_utils.js +16 -1
  143. package/dist/market_adapter/log_format.d.ts +6 -6
  144. package/dist/market_adapter/log_format.js +28 -21
  145. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  146. package/dist/market_adapter/lp_chart_core.js +26 -192
  147. package/dist/market_adapter/lp_chart_runner.d.ts +10 -7
  148. package/dist/market_adapter/lp_chart_runner.js +37 -19
  149. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  150. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  151. package/dist/market_adapter/market_adapter.d.ts +94 -32
  152. package/dist/market_adapter/market_adapter.js +94 -120
  153. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  154. package/dist/market_adapter/utils/adapter_client.js +2 -2
  155. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  156. package/dist/market_adapter/utils/chain.d.ts +50 -41
  157. package/dist/market_adapter/utils/chain.js +40 -46
  158. package/dist/market_adapter/utils/data_discovery.d.ts +49 -2
  159. package/dist/market_adapter/utils/data_discovery.js +220 -27
  160. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  161. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  162. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  163. package/dist/market_adapter/utils/file_lock.js +36 -32
  164. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  165. package/dist/market_adapter/utils/month_shards.js +237 -0
  166. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  167. package/dist/market_adapter/utils/native_history.js +35 -28
  168. package/dist/modules/account_bots.d.ts +578 -21
  169. package/dist/modules/account_bots.js +272 -267
  170. package/dist/modules/account_orders.d.ts +79 -30
  171. package/dist/modules/account_orders.js +60 -64
  172. package/dist/modules/authority_resolver.d.ts +12 -2
  173. package/dist/modules/authority_resolver.js +15 -8
  174. package/dist/modules/bitshares-native/chain_client.d.ts +39 -4
  175. package/dist/modules/bitshares-native/chain_client.js +59 -59
  176. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  177. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  178. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  179. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  180. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  181. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  182. package/dist/modules/bitshares-native/index.d.ts +1 -1
  183. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  184. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  185. package/dist/modules/bitshares-native/resolvers.js +22 -25
  186. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  187. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  188. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  189. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  190. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  191. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  192. package/dist/modules/bitshares-native/serial/types.js +73 -108
  193. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  194. package/dist/modules/bitshares-native/signing_client.js +19 -14
  195. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  196. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  197. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  198. package/dist/modules/bitshares-native/transport.js +5 -4
  199. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  200. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  201. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  202. package/dist/modules/bitshares_client.d.ts +45 -13
  203. package/dist/modules/bitshares_client.js +28 -19
  204. package/dist/modules/bot_defaults.d.ts +8 -16
  205. package/dist/modules/bot_defaults.js +1 -5
  206. package/dist/modules/bot_settings.d.ts +44 -10
  207. package/dist/modules/bot_settings.js +11 -8
  208. package/dist/modules/bots_file_lock.d.ts +6 -6
  209. package/dist/modules/bots_file_lock.js +16 -12
  210. package/dist/modules/broadcast_failure.d.ts +4 -3
  211. package/dist/modules/broadcast_failure.js +5 -4
  212. package/dist/modules/chain_keys.d.ts +42 -40
  213. package/dist/modules/chain_keys.js +53 -45
  214. package/dist/modules/chain_orders.d.ts +94 -60
  215. package/dist/modules/chain_orders.js +81 -118
  216. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  217. package/dist/modules/constants.d.ts +534 -32
  218. package/dist/modules/constants.js +35 -48
  219. package/dist/modules/cr_planner.d.ts +41 -3
  220. package/dist/modules/cr_planner.js +1 -5
  221. package/dist/modules/credential_policy.d.ts +68 -8
  222. package/dist/modules/credential_policy.js +37 -31
  223. package/dist/modules/credential_session_cache.d.ts +2 -2
  224. package/dist/modules/credit_pricing.d.ts +43 -6
  225. package/dist/modules/credit_pricing.js +70 -60
  226. package/dist/modules/credit_runtime.d.ts +283 -118
  227. package/dist/modules/credit_runtime.js +500 -231
  228. package/dist/modules/crypto/browser_provider.js +6 -4
  229. package/dist/modules/crypto/node_provider.js +1 -1
  230. package/dist/modules/crypto/pure_scrypt.js +35 -4
  231. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  232. package/dist/modules/crypto/sync.d.ts +9 -9
  233. package/dist/modules/crypto/sync.js +16 -9
  234. package/dist/modules/daemon_node_health.d.ts +4 -3
  235. package/dist/modules/dexbot_class.d.ts +213 -146
  236. package/dist/modules/dexbot_class.js +183 -86
  237. package/dist/modules/dexbot_cow_runtime.d.ts +160 -87
  238. package/dist/modules/dexbot_cow_runtime.js +302 -234
  239. package/dist/modules/dexbot_credential_client.d.ts +19 -18
  240. package/dist/modules/dexbot_credential_client.js +1 -2
  241. package/dist/modules/dexbot_fill_runtime.d.ts +63 -49
  242. package/dist/modules/dexbot_fill_runtime.js +53 -47
  243. package/dist/modules/dexbot_maintenance_runtime.d.ts +127 -71
  244. package/dist/modules/dexbot_maintenance_runtime.js +187 -147
  245. package/dist/modules/dexbot_startup_runtime.d.ts +11 -11
  246. package/dist/modules/dexbot_startup_runtime.js +56 -57
  247. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  248. package/dist/modules/dexbot_state_recovery.js +18 -13
  249. package/dist/modules/fund_registry.d.ts +4 -2
  250. package/dist/modules/fund_registry.js +10 -10
  251. package/dist/modules/general_settings.d.ts +30 -4
  252. package/dist/modules/graceful_shutdown.d.ts +3 -3
  253. package/dist/modules/graceful_shutdown.js +19 -13
  254. package/dist/modules/grid_price_source.d.ts +1 -1
  255. package/dist/modules/key_store.d.ts +14 -8
  256. package/dist/modules/key_store.js +7 -7
  257. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  258. package/dist/modules/launcher/adapter_requirement.js +5 -5
  259. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  260. package/dist/modules/launcher/bot_supervisor.js +12 -11
  261. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  262. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  263. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  264. package/dist/modules/launcher/credential_daemon.js +2 -2
  265. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  266. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  267. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  268. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  269. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  270. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  271. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  272. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  273. package/dist/modules/launcher/supervisor_control.js +4 -2
  274. package/dist/modules/lazy_shim.d.ts +11 -0
  275. package/dist/modules/lazy_shim.js +16 -0
  276. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  277. package/dist/modules/market_adapter_whitelist.js +15 -3
  278. package/dist/modules/node_connect_policy.d.ts +3 -2
  279. package/dist/modules/node_failure_ledger.d.ts +6 -5
  280. package/dist/modules/node_manager.d.ts +41 -11
  281. package/dist/modules/node_manager.js +5 -4
  282. package/dist/modules/order/accounting.d.ts +53 -24
  283. package/dist/modules/order/accounting.js +16 -15
  284. package/dist/modules/order/async_lock.d.ts +5 -2
  285. package/dist/modules/order/async_lock.js +1 -1
  286. package/dist/modules/order/export.d.ts +7 -6
  287. package/dist/modules/order/export.js +1 -7
  288. package/dist/modules/order/format.d.ts +16 -7
  289. package/dist/modules/order/format.js +15 -3
  290. package/dist/modules/order/genesis_policy.d.ts +24 -21
  291. package/dist/modules/order/genesis_policy.js +17 -10
  292. package/dist/modules/order/grid.d.ts +144 -36
  293. package/dist/modules/order/grid.js +226 -145
  294. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  295. package/dist/modules/order/grid_reconcile.js +13 -12
  296. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  297. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  298. package/dist/modules/order/index.d.ts +264 -1
  299. package/dist/modules/order/logger.d.ts +46 -19
  300. package/dist/modules/order/logger.js +38 -49
  301. package/dist/modules/order/logger_state.d.ts +4 -4
  302. package/dist/modules/order/manager.d.ts +232 -191
  303. package/dist/modules/order/manager.js +110 -130
  304. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  305. package/dist/modules/order/processed_fill_store.js +16 -27
  306. package/dist/modules/order/strategy.d.ts +21 -13
  307. package/dist/modules/order/strategy.js +5 -6
  308. package/dist/modules/order/sync_engine.d.ts +91 -33
  309. package/dist/modules/order/sync_engine.js +84 -53
  310. package/dist/modules/order/utils/math.d.ts +157 -102
  311. package/dist/modules/order/utils/math.js +77 -38
  312. package/dist/modules/order/utils/order.d.ts +310 -110
  313. package/dist/modules/order/utils/order.js +153 -126
  314. package/dist/modules/order/utils/slot.d.ts +1 -1
  315. package/dist/modules/order/utils/system.d.ts +156 -26
  316. package/dist/modules/order/utils/system.js +103 -71
  317. package/dist/modules/order/utils/validate.d.ts +89 -41
  318. package/dist/modules/order/utils/validate.js +26 -24
  319. package/dist/modules/order/utils/withPoolRef.d.ts +6 -4
  320. package/dist/modules/order/utils/withPoolRef.js +18 -12
  321. package/dist/modules/order/working_grid.d.ts +14 -13
  322. package/dist/modules/paths.d.ts +1 -4
  323. package/dist/modules/paths.js +33 -61
  324. package/dist/modules/process_discovery.d.ts +1 -1
  325. package/dist/modules/process_discovery.js +2 -1
  326. package/dist/modules/runtime.d.ts +7 -3
  327. package/dist/modules/runtime.js +4 -3
  328. package/dist/modules/runtime_settings.d.ts +14 -11
  329. package/dist/modules/runtime_settings.js +30 -24
  330. package/dist/modules/settings_merge.d.ts +29 -3
  331. package/dist/modules/settings_merge.js +56 -78
  332. package/dist/modules/socket_json_client.d.ts +9 -5
  333. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  334. package/dist/modules/storage/browser_adapter.js +7 -30
  335. package/dist/modules/storage/index.d.ts +1 -1
  336. package/dist/modules/storage/node_adapter.d.ts +45 -27
  337. package/dist/modules/storage/node_adapter.js +9 -9
  338. package/dist/modules/storage/types.d.ts +5 -4
  339. package/dist/modules/types.d.ts +1090 -6
  340. package/dist/modules/types.js +4 -1
  341. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  342. package/dist/modules/utils/asset_symbols.js +2 -1
  343. package/dist/modules/utils/errors.d.ts +9 -0
  344. package/dist/modules/utils/errors.js +24 -4
  345. package/dist/modules/utils/time_range.d.ts +1 -12
  346. package/dist/modules/utils/time_range.js +1 -1
  347. package/dist/modules/validate_profiles.js +53 -43
  348. package/dist/modules/version_notice.d.ts +23 -11
  349. package/dist/modules/version_notice.js +6 -4
  350. package/dist/pm2.d.ts +28 -27
  351. package/dist/pm2.js +61 -40
  352. package/dist/scripts/analyze-credit.d.ts +2 -1
  353. package/dist/scripts/analyze-credit.js +23 -24
  354. package/dist/scripts/analyze-git.js +2 -15
  355. package/dist/scripts/analyze-orders.d.ts +77 -9
  356. package/dist/scripts/analyze-orders.js +65 -40
  357. package/dist/scripts/chart_command.d.ts +27 -18
  358. package/dist/scripts/chart_command.js +15 -13
  359. package/dist/scripts/check_any.d.ts +22 -0
  360. package/dist/scripts/check_any.js +158 -0
  361. package/dist/scripts/diagnose-pool-history.js +13 -13
  362. package/dist/scripts/print_grid.js +0 -1
  363. package/dist/scripts/run-tests.js +39 -8
  364. package/dist/scripts/runner.js +1 -1
  365. package/dist/scripts/sync-version.js +0 -10
  366. package/dist/scripts/test-credit-renewal.js +30 -21
  367. package/dist/scripts/update.d.ts +10 -5
  368. package/dist/scripts/update.js +168 -103
  369. package/dist/scripts/update_dist_freshness.js +1 -0
  370. package/dist/scripts/update_layout.d.ts +61 -0
  371. package/dist/scripts/update_layout.js +180 -0
  372. package/dist/scripts/validate_bots.js +2 -1
  373. package/dist/scripts/verify-browser-bundle.js +8 -0
  374. package/dist/unlock.d.ts +28 -3
  375. package/dist/unlock.js +63 -35
  376. package/docs/BITSHARES_ONBOARDING.md +10 -12
  377. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -2
  378. package/docs/COW_INVARIANTS.md +13 -6
  379. package/docs/DEXBOT_COMPARISON.md +8 -8
  380. package/docs/EVOLUTION.md +10 -8
  381. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  382. package/docs/GRID_RECALCULATION.md +4 -2
  383. package/docs/GRID_RECONCILE.md +14 -3
  384. package/docs/LIFECYCLE.md +11 -11
  385. package/docs/MPA_CREDIT_USAGE.md +22 -3
  386. package/docs/README.md +14 -3
  387. package/docs/WORKFLOW.md +1 -0
  388. package/docs/architecture.md +31 -19
  389. package/docs/developer_guide.md +6 -6
  390. package/market_adapter/README.md +12 -5
  391. package/modules/README.md +4 -1
  392. package/package.json +9 -9
  393. package/scripts/README.md +43 -38
  394. package/tests/README.md +25 -10
  395. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  396. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  397. package/scripts/git-viewer.sh +0 -489
  398. package/scripts/postinstall.js +0 -16
@@ -5,7 +5,7 @@
5
5
  * Manages multi-bot configuration and metadata.
6
6
  *
7
7
  * ===============================================================================
8
- * EXPORTS (5 functions)
8
+ * EXPORTS (10 functions)
9
9
  * ===============================================================================
10
10
  *
11
11
  * MAIN ENTRY POINT:
@@ -16,11 +16,12 @@
16
16
  * normalizeBotDraft(base) - Normalize a bot configuration draft
17
17
  * Applies defaults and validation to raw bot config entries
18
18
  *
19
- * parseJsonWithComments(raw) - Parse JSON with comment stripping
20
- * (re-exported from ./order/utils/system.js)
19
+ * loadGeneralSettings() - Load profiles/general.settings.json
21
20
  *
22
- * parseCronToDelta(cronString) - Parse a cron expression to { days, time }
23
- * deltaToCron(days, time) - Convert { days, time } back to a cron expression
21
+ * SUPPORTING EXPORTS:
22
+ * ensureBotAccountId, parseJsonWithComments, parseBooleanInput,
23
+ * colorGridPriceValue, formatPoolRefLabel, isPoolStartPrice,
24
+ * isPoolRefClearInput
24
25
  *
25
26
  * INTERNAL HELPERS (not exported):
26
27
  * ask* prompt family (askString, askNumberWithBounds, askIntegerInRange,
@@ -29,11 +30,12 @@
29
30
  * askMaxPrice, askWeightDistribution, askWeightDistributionNoLegend,
30
31
  * askLogLevel, askUpdaterBranch, askCronSchedule, askBoolean),
31
32
  * loadBotsConfig, saveBotsConfig, listBots, selectBotIndex,
32
- * loadGeneralSettings, saveGeneralSettings, isMultiplierString,
33
+ * saveGeneralSettings, isMultiplierString,
33
34
  * colorPriceRangeValue, colorMultiplierInput,
34
35
  * isPercentageString, colorPercentageInput,
35
- * isDynamicPriceSource, colorStartPriceValue, colorGridPriceValue,
36
+ * isDynamicPriceSource, colorStartPriceValue,
36
37
  * colorBooleanFlag,
38
+ * parseCronToDelta, deltaToCron,
37
39
  * normalizePercentageInput, promptBotData, promptGeneralSettings
38
40
  *
39
41
  * ===============================================================================
@@ -95,10 +97,10 @@ import { PATHS } from './paths.js';
95
97
  import { SETTINGS_FILE, readGeneralSettings, writeGeneralSettings } from './general_settings.js';
96
98
  import { parseJsonWithComments } from './order/utils/system.js';
97
99
  import { assertNoDuplicateBotKeys, loadSettingsFile, normalizeBotEntry } from './bot_settings.js';
98
- import { getWhitelistFlags, setWhitelistFlags, renameWhitelistEntry, removeWhitelistEntry, whitelistFile } from './market_adapter_whitelist.js';
100
+ import { getWhitelistFlags, hasWhitelistEntry, setWhitelistFlags, renameWhitelistEntry, removeWhitelistEntry, whitelistFile, AMA_ONLY_WHITELIST_FLAGS } from './market_adapter_whitelist.js';
99
101
  import { BOT_LIVE_CONFIG_KEYS } from './runtime_settings.js';
100
102
  import { mergeSettings } from './settings_merge.js';
101
- import { getErrorMessage } from './utils/errors.js';
103
+ import { getErrorMessage, getErrorCode } from './utils/errors.js';
102
104
  import { normalizeAssetSymbol } from './utils/asset_symbols.js';
103
105
  import { roundToDecimals, parseRelativeMultiplier } from './order/utils/math.js';
104
106
  import { CLI_COLORS } from './cli_colors.js';
@@ -134,7 +136,7 @@ function loadBotsConfig() {
134
136
  return { config: { bots: [] }, filePath };
135
137
  if (!Array.isArray(config.bots))
136
138
  config.bots = [];
137
- return { config, filePath };
139
+ return { config: config, filePath };
138
140
  }
139
141
  /**
140
142
  * Saves the bots configuration to the specified file path.
@@ -145,7 +147,8 @@ function loadBotsConfig() {
145
147
  function saveBotsConfig(config, filePath) {
146
148
  try {
147
149
  ensureProfilesDirectory(PROFILES_DIR);
148
- const entries = Array.isArray(config?.bots) ? config.bots : Array.isArray(config) ? config : [];
150
+ const c = config;
151
+ const entries = Array.isArray(c?.bots) ? c.bots : Array.isArray(config) ? config : [];
149
152
  if (entries.length >= 2)
150
153
  assertNoDuplicateBotKeys(entries, 'account_bots');
151
154
  writeJSON(filePath, config);
@@ -300,7 +303,7 @@ async function askCronSchedule(_promptText, defaultValue) {
300
303
  const current = parseCronToDelta(defaultValue);
301
304
  // Interval Prompt
302
305
  const days = await askNumberWithBounds(' Interval (days)', current.days, 1, 31);
303
- if (days === '\x1b')
306
+ if (days === '\x1b' || typeof days !== 'number')
304
307
  return '\x1b';
305
308
  // Time Prompt
306
309
  let time = current.time;
@@ -308,7 +311,7 @@ async function askCronSchedule(_promptText, defaultValue) {
308
311
  const rawTime = await askString(' Time (HH:mm)', current.time);
309
312
  if (rawTime === '\x1b')
310
313
  return '\x1b';
311
- if (/^([01]\d|2[0-3]):([0-5]\d)$/.test(rawTime)) {
314
+ if (rawTime && /^([01]\d|2[0-3]):([0-5]\d)$/.test(rawTime)) {
312
315
  time = rawTime;
313
316
  break;
314
317
  }
@@ -328,7 +331,7 @@ async function askUpdaterBranch(promptText, defaultValue) {
328
331
  const value = await askString(promptText, defaultValue);
329
332
  if (value === '\x1b')
330
333
  return '\x1b';
331
- const lowered = value.toLowerCase().trim();
334
+ const lowered = (value ?? '').toLowerCase().trim();
332
335
  if (validBranches.includes(lowered))
333
336
  return lowered;
334
337
  console.log(`Invalid branch. Please choose from: ${validBranches.join(', ')}`);
@@ -347,19 +350,18 @@ async function askLogLevel(promptText, defaultValue) {
347
350
  const value = await askString(promptText, defaultValue);
348
351
  if (value === '\x1b')
349
352
  return '\x1b';
350
- const lowered = value.toLowerCase().trim();
353
+ const lowered = (value ?? '').toLowerCase().trim();
351
354
  if (validLevels.includes(lowered))
352
355
  return lowered;
353
356
  console.log(`Invalid log level. Please choose from: ${validLevels.join(', ')}`);
354
357
  }
355
358
  }
356
359
  /**
357
- * Prompts the user for an asset symbol.
358
- * @param {string} promptText - The prompt text to display.
359
- * @param {string} [defaultValue] - The default value to use if input is empty.
360
- * @returns {Promise<string>} The asset symbol in uppercase.
360
+ * Shared asset-symbol input loop: handles ESC, the empty-input default, and
361
+ * normalizeAssetSymbol. An optional `validate` callback may reject a
362
+ * normalized symbol by returning a message to print.
361
363
  */
362
- async function askAsset(promptText, defaultValue) {
364
+ async function askAssetSymbol(promptText, defaultValue, validate) {
363
365
  while (true) {
364
366
  const displayDefault = defaultValue ? normalizeAssetSymbol(defaultValue) : undefined;
365
367
  const suffix = displayDefault !== undefined && displayDefault !== null ? ` [${displayDefault}]` : '';
@@ -372,9 +374,24 @@ async function askAsset(promptText, defaultValue) {
372
374
  console.log('Asset name is required.');
373
375
  continue;
374
376
  }
375
- return normalizeAssetSymbol(answer);
377
+ const asset = normalizeAssetSymbol(answer);
378
+ const reason = validate ? validate(asset) : null;
379
+ if (reason) {
380
+ console.log(reason);
381
+ continue;
382
+ }
383
+ return asset;
376
384
  }
377
385
  }
386
+ /**
387
+ * Prompts the user for an asset symbol.
388
+ * @param {string} promptText - The prompt text to display.
389
+ * @param {string} [defaultValue] - The default value to use if input is empty.
390
+ * @returns {Promise<string>} The asset symbol in uppercase.
391
+ */
392
+ async function askAsset(promptText, defaultValue) {
393
+ return askAssetSymbol(promptText, defaultValue);
394
+ }
378
395
  /**
379
396
  * Prompts the user for Asset B, ensuring it's different from Asset A.
380
397
  * @param {string} promptText - The prompt text to display.
@@ -383,26 +400,7 @@ async function askAsset(promptText, defaultValue) {
383
400
  * @returns {Promise<string>} The asset symbol in uppercase.
384
401
  */
385
402
  async function askAssetB(promptText, defaultValue, assetA) {
386
- while (true) {
387
- const displayDefault = defaultValue ? normalizeAssetSymbol(defaultValue) : undefined;
388
- const suffix = displayDefault !== undefined && displayDefault !== null ? ` [${displayDefault}]` : '';
389
- const answer = await readInput(`${promptText}${suffix}: `);
390
- if (answer === '\x1b')
391
- return '\x1b';
392
- if (!answer) {
393
- if (displayDefault)
394
- return displayDefault;
395
- console.log('Asset name is required.');
396
- continue;
397
- }
398
- const assetB = normalizeAssetSymbol(answer);
399
- // Validate that Asset B is different from Asset A
400
- if (assetB === assetA) {
401
- console.log(`Invalid: Asset B cannot be the same as Asset A (${assetA})`);
402
- continue;
403
- }
404
- return assetB;
405
- }
403
+ return askAssetSymbol(promptText, defaultValue, (assetB) => assetB === assetA ? `Invalid: Asset B cannot be the same as Asset A (${assetA})` : null);
406
404
  }
407
405
  /**
408
406
  * Prompts the user for a weight distribution value with a legend.
@@ -410,26 +408,22 @@ async function askAssetB(promptText, defaultValue, assetA) {
410
408
  * @param {number} [defaultValue] - The default value to use if input is empty.
411
409
  * @returns {Promise<number|string>} The numeric value or '\x1b' if ESC.
412
410
  */
413
- async function askWeightDistribution(promptText, defaultValue) {
411
+ async function askWeightDistributionValue(promptText, defaultValue, showLegend) {
414
412
  const MIN_WEIGHT = -1;
415
413
  const MAX_WEIGHT = 2;
416
- console.log(` ${COLORS.cyan}-1=SuperValley${COLORS.reset} ←→ ${COLORS.blue}0=Valley${COLORS.reset} ←→ ${COLORS.gray}0.5=Neutral${COLORS.reset} ←→ ${COLORS.bold}${COLORS.orange}1=Mountain${COLORS.reset} ←→ ${COLORS.redStrong}2=SuperMountain${COLORS.reset}`);
417
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${defaultValue}]` : '';
418
- const raw = (await readInput(`${promptText}${suffix}: `)).trim();
419
- if (raw === '\x1b')
420
- return '\x1b';
421
- if (raw === '')
422
- return defaultValue;
423
- const parsed = Number(raw);
424
- if (Number.isNaN(parsed)) {
425
- console.log('Please enter a valid number.');
426
- return askWeightDistribution(promptText, defaultValue);
427
- }
428
- if (parsed < MIN_WEIGHT || parsed > MAX_WEIGHT) {
429
- console.log(`Weight distribution must be between ${MIN_WEIGHT} and ${MAX_WEIGHT}.`);
430
- return askWeightDistribution(promptText, defaultValue);
414
+ if (showLegend) {
415
+ console.log(` ${COLORS.cyan}-1=SuperValley${COLORS.reset} ←→ ${COLORS.blue}0=Valley${COLORS.reset} ←→ ${COLORS.gray}0.5=Neutral${COLORS.reset} ←→ ${COLORS.bold}${COLORS.orange}1=Mountain${COLORS.reset} ←→ ${COLORS.redStrong}2=SuperMountain${COLORS.reset}`);
431
416
  }
432
- return parsed;
417
+ return askNumeric(promptText, defaultValue, (parsed) => parsed < MIN_WEIGHT || parsed > MAX_WEIGHT ? `Weight distribution must be between ${MIN_WEIGHT} and ${MAX_WEIGHT}.` : null);
418
+ }
419
+ /**
420
+ * Prompts the user for a weight distribution value with a legend.
421
+ * @param {string} promptText - The prompt text to display.
422
+ * @param {number} [defaultValue] - The default value to use if input is empty.
423
+ * @returns {Promise<number|string>} The numeric value or '\x1b' if ESC.
424
+ */
425
+ async function askWeightDistribution(promptText, defaultValue) {
426
+ return askWeightDistributionValue(promptText, defaultValue, true);
433
427
  }
434
428
  /**
435
429
  * Prompts the user for a weight distribution value without a legend.
@@ -438,24 +432,7 @@ async function askWeightDistribution(promptText, defaultValue) {
438
432
  * @returns {Promise<number|string>} The numeric value or '\x1b' if ESC.
439
433
  */
440
434
  async function askWeightDistributionNoLegend(promptText, defaultValue) {
441
- const MIN_WEIGHT = -1;
442
- const MAX_WEIGHT = 2;
443
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${defaultValue}]` : '';
444
- const raw = (await readInput(`${promptText}${suffix}: `)).trim();
445
- if (raw === '\x1b')
446
- return '\x1b';
447
- if (raw === '')
448
- return defaultValue;
449
- const parsed = Number(raw);
450
- if (Number.isNaN(parsed)) {
451
- console.log('Please enter a valid number.');
452
- return askWeightDistributionNoLegend(promptText, defaultValue);
453
- }
454
- if (parsed < MIN_WEIGHT || parsed > MAX_WEIGHT) {
455
- console.log(`Weight distribution must be between ${MIN_WEIGHT} and ${MAX_WEIGHT}.`);
456
- return askWeightDistributionNoLegend(promptText, defaultValue);
457
- }
458
- return parsed;
435
+ return askWeightDistributionValue(promptText, defaultValue, false);
459
436
  }
460
437
  /**
461
438
  * Checks if a value is a multiplier string (e.g. "3x").
@@ -708,14 +685,11 @@ function deltaToCron(days, time) {
708
685
  return `${min} ${hour} ${dayPart} * *`;
709
686
  }
710
687
  /**
711
- * Prompts the user for a number within specified bounds.
712
- * @param {string} promptText - The prompt text to display.
713
- * @param {number} [defaultValue] - The default value to use if input is empty.
714
- * @param {number} minVal - The minimum allowed value.
715
- * @param {number} maxVal - The maximum allowed value.
716
- * @returns {Promise<number|string>} The numeric value or '\x1b' if ESC.
688
+ * Shared numeric-input loop: handles ESC and the empty-input default, then
689
+ * delegates domain validation to `validate`. `validate` returns an error
690
+ * message to print and retry, or null to accept the parsed value.
717
691
  */
718
- async function askNumberWithBounds(promptText, defaultValue, minVal = 0, maxVal = 100) {
692
+ async function askNumeric(promptText, defaultValue, validate) {
719
693
  const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${defaultValue}]` : '';
720
694
  const raw = (await readInput(`${promptText}${suffix}: `)).trim();
721
695
  if (raw === '\x1b')
@@ -725,24 +699,54 @@ async function askNumberWithBounds(promptText, defaultValue, minVal = 0, maxVal
725
699
  const parsed = Number(raw);
726
700
  if (Number.isNaN(parsed)) {
727
701
  console.log('Please enter a valid number.');
728
- return askNumberWithBounds(promptText, defaultValue, minVal, maxVal);
729
- }
730
- // Validate that number is finite (not Infinity, -Infinity, or NaN)
731
- if (!Number.isFinite(parsed)) {
732
- console.log('Please enter a valid finite number.');
733
- return askNumberWithBounds(promptText, defaultValue, minVal, maxVal);
734
- }
735
- // Validate bounds
736
- if (parsed < minVal) {
737
- console.log(`Invalid ${promptText}: ${parsed}. Must be >= ${minVal}`);
738
- return askNumberWithBounds(promptText, defaultValue, minVal, maxVal);
702
+ return askNumeric(promptText, defaultValue, validate);
739
703
  }
740
- if (parsed > maxVal) {
741
- console.log(`Invalid ${promptText}: ${parsed}. Must be <= ${maxVal}`);
742
- return askNumberWithBounds(promptText, defaultValue, minVal, maxVal);
704
+ const reason = validate(parsed);
705
+ if (reason) {
706
+ console.log(reason);
707
+ return askNumeric(promptText, defaultValue, validate);
743
708
  }
744
709
  return parsed;
745
710
  }
711
+ async function askTypedInput(options) {
712
+ options.onBeforePrompt?.();
713
+ const { promptText, defaultValue } = options;
714
+ const shown = defaultValue !== undefined && defaultValue !== null
715
+ ? ` [${options.formatDefault ? options.formatDefault(defaultValue) : String(defaultValue)}]`
716
+ : '';
717
+ const raw = (await readInput(`${promptText}${shown}: `, options.colorize ? { colorize: options.colorize } : {})).trim();
718
+ if (raw === '\x1b')
719
+ return '\x1b';
720
+ if (raw === '')
721
+ return defaultValue;
722
+ const result = options.parse(raw);
723
+ if ('error' in result) {
724
+ console.log(result.error);
725
+ return askTypedInput(options);
726
+ }
727
+ return result.value;
728
+ }
729
+ /**
730
+ * Prompts the user for a number within specified bounds.
731
+ * @param {string} promptText - The prompt text to display.
732
+ * @param {number} [defaultValue] - The default value to use if input is empty.
733
+ * @param {number} minVal - The minimum allowed value.
734
+ * @param {number} maxVal - The maximum allowed value.
735
+ * @returns {Promise<number|string>} The numeric value or '\x1b' if ESC.
736
+ */
737
+ async function askNumberWithBounds(promptText, defaultValue, minVal = 0, maxVal = 100) {
738
+ return askNumeric(promptText, defaultValue, (parsed) => {
739
+ // Validate that number is finite (not Infinity, -Infinity, or NaN)
740
+ if (!Number.isFinite(parsed))
741
+ return 'Please enter a valid finite number.';
742
+ // Validate bounds
743
+ if (parsed < minVal)
744
+ return `Invalid ${promptText}: ${parsed}. Must be >= ${minVal}`;
745
+ if (parsed > maxVal)
746
+ return `Invalid ${promptText}: ${parsed}. Must be <= ${maxVal}`;
747
+ return null;
748
+ });
749
+ }
746
750
  /**
747
751
  * Prompts the user for the target spread percentage.
748
752
  * Values are rounded to two decimal places: the displayed minimum, the
@@ -758,7 +762,7 @@ async function askTargetSpreadPercent(promptText, defaultValue, incrementPercent
758
762
  const safeMinSpreadFactor = Number.isFinite(minSpreadFactor) ? minSpreadFactor : GRID_LIMITS.MIN_SPREAD_FACTOR;
759
763
  const minRequired = roundToDecimals(safeIncrement * safeMinSpreadFactor, 2);
760
764
  const minRequiredLabel = minRequired.toFixed(2);
761
- const effectiveDefault = Number.isFinite(defaultValue) ? Math.max(roundToDecimals(defaultValue, 2), minRequired) : defaultValue;
765
+ const effectiveDefault = typeof defaultValue === 'number' && Number.isFinite(defaultValue) ? Math.max(roundToDecimals(defaultValue, 2), minRequired) : defaultValue;
762
766
  const suffix = effectiveDefault !== undefined && effectiveDefault !== null ? ` [${effectiveDefault.toFixed(2)}]` : '';
763
767
  const raw = (await readInput(`${promptText} (>= ${minRequiredLabel})${suffix}: `)).trim();
764
768
  if (raw === '\x1b')
@@ -796,28 +800,36 @@ async function askTargetSpreadPercent(promptText, defaultValue, incrementPercent
796
800
  * @returns {Promise<number|string>} The integer or '\x1b' if ESC.
797
801
  */
798
802
  async function askIntegerInRange(promptText, defaultValue, minVal = 0, maxVal = 100) {
799
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${defaultValue}]` : '';
800
- const raw = (await readInput(`${promptText}${suffix}: `)).trim();
801
- if (raw === '\x1b')
802
- return '\x1b';
803
- if (raw === '')
804
- return defaultValue;
805
- const parsed = Number(raw);
806
- if (Number.isNaN(parsed)) {
807
- console.log('Please enter a valid number.');
808
- return askIntegerInRange(promptText, defaultValue, minVal, maxVal);
809
- }
810
- // Validate that number is integer (not float)
811
- if (!Number.isInteger(parsed)) {
812
- console.log(`Invalid ${promptText}: ${parsed}. Must be an integer (no decimals)`);
813
- return askIntegerInRange(promptText, defaultValue, minVal, maxVal);
803
+ return askNumeric(promptText, defaultValue, (parsed) => {
804
+ // Validate that number is integer (not float)
805
+ if (!Number.isInteger(parsed))
806
+ return `Invalid ${promptText}: ${parsed}. Must be an integer (no decimals)`;
807
+ // Validate bounds
808
+ if (parsed < minVal || parsed > maxVal)
809
+ return `Invalid ${promptText}: ${parsed}. Must be between ${minVal} and ${maxVal}`;
810
+ return null;
811
+ });
812
+ }
813
+ /**
814
+ * Validate a relative-multiplier input ("1.5x") for the price-bound prompts.
815
+ * Returns the trimmed multiplier string when accepted, or the error message to
816
+ * print when rejected. Single source of truth for the min/max direction rule.
817
+ */
818
+ function validateMultiplierInput(promptText, raw) {
819
+ const trimmed = raw.trim();
820
+ const multiplier = parseFloat(trimmed);
821
+ if (multiplier <= 0) {
822
+ return { error: `Invalid ${promptText}: "${trimmed}". Multiplier must be > 0. No "0x" or negative values` };
814
823
  }
815
- // Validate bounds
816
- if (parsed < minVal || parsed > maxVal) {
817
- console.log(`Invalid ${promptText}: ${parsed}. Must be between ${minVal} and ${maxVal}`);
818
- return askIntegerInRange(promptText, defaultValue, minVal, maxVal);
824
+ if (multiplier < 1) {
825
+ // A sub-1x bound multiplier ("0.7x") resolves to the wrong side of the
826
+ // grid. Reject so the rail can't land across the book (issue #15).
827
+ const directionNote = /max/i.test(promptText)
828
+ ? 'For maxPrice, "Nx" means center*N, so a multiplier < 1 places the bound BELOW the center. Use a value > 1.'
829
+ : 'For minPrice, "Nx" means center/N, so a multiplier < 1 places the bound ABOVE the center. Use a value > 1 (e.g. "1.43x" for 70% of center).';
830
+ return { error: `Invalid ${promptText}: "${trimmed}". ${directionNote}` };
819
831
  }
820
- return parsed;
832
+ return { value: trimmed };
821
833
  }
822
834
  /**
823
835
  * Prompts the user for a numeric value or a multiplier. Used for price
@@ -828,44 +840,28 @@ async function askIntegerInRange(promptText, defaultValue, minVal = 0, maxVal =
828
840
  * @returns {Promise<number|string>} The value or '\x1b' if ESC.
829
841
  */
830
842
  async function askNumberOrMultiplier(promptText, defaultValue) {
831
- // Pre-entry legend for Range bounds (mirrors weight mountain legend)
832
- if (/^(minPrice|maxPrice)/i.test(promptText))
833
- printRangeQualityLegend();
834
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${colorPriceRangeValue(defaultValue)}]` : '';
835
- const raw = (await readInput(`${promptText}${suffix}: `, { colorize: (input) => colorRangeValueByQuality(input) })).trim();
836
- if (raw === '\x1b')
837
- return '\x1b';
838
- if (raw === '')
839
- return defaultValue;
840
- if (isMultiplierString(raw)) {
841
- const trimmed = raw.trim();
842
- const multiplier = parseFloat(trimmed);
843
- if (multiplier <= 0) {
844
- console.log(`Invalid ${promptText}: "${trimmed}". Multiplier must be > 0. No "0x" or negative values`);
845
- return askNumberOrMultiplier(promptText, defaultValue);
846
- }
847
- // A sub-1x bound multiplier ("0.7x") resolves to the wrong side of
848
- // the grid. Reject so the rail can't land across the book (issue #15).
849
- const directionNote = /max/i.test(promptText)
850
- ? 'For maxPrice, "Nx" means center*N, so a multiplier < 1 places the bound BELOW the center. Use a value > 1.'
851
- : 'For minPrice, "Nx" means center/N, so a multiplier < 1 places the bound ABOVE the center. Use a value > 1 (e.g. "1.43x" for 70% of center).';
852
- if (multiplier < 1) {
853
- console.log(`Invalid ${promptText}: "${trimmed}". ${directionNote}`);
854
- return askNumberOrMultiplier(promptText, defaultValue);
855
- }
856
- return trimmed;
857
- }
858
- const parsed = Number(raw);
859
- if (Number.isNaN(parsed)) {
860
- console.log('Please enter a valid number or multiplier (e.g. 5x).');
861
- return askNumberOrMultiplier(promptText, defaultValue);
862
- }
863
- // Validate that number is > 0 (for price inputs)
864
- if (parsed <= 0) {
865
- console.log(`Invalid ${promptText}: ${parsed}. Must be > 0 (positive number)`);
866
- return askNumberOrMultiplier(promptText, defaultValue);
867
- }
868
- return parsed;
843
+ return askTypedInput({
844
+ promptText,
845
+ defaultValue,
846
+ // Pre-entry legend for Range bounds (mirrors weight mountain legend)
847
+ onBeforePrompt: () => { if (/^(minPrice|maxPrice)/i.test(promptText))
848
+ printRangeQualityLegend(); },
849
+ formatDefault: colorPriceRangeValue,
850
+ colorize: colorRangeValueByQuality,
851
+ parse: (raw) => {
852
+ if (isMultiplierString(raw)) {
853
+ const result = validateMultiplierInput(promptText, raw);
854
+ return 'error' in result ? result : { value: result.value };
855
+ }
856
+ const parsed = Number(raw);
857
+ if (Number.isNaN(parsed))
858
+ return { error: 'Please enter a valid number or multiplier (e.g. 5x).' };
859
+ // Validate that number is > 0 (for price inputs)
860
+ if (parsed <= 0)
861
+ return { error: `Invalid ${promptText}: ${parsed}. Must be > 0 (positive number)` };
862
+ return { value: parsed };
863
+ },
864
+ });
869
865
  }
870
866
  /**
871
867
  * Prompts the user for the maximum price, ensuring it's greater than minimum price.
@@ -875,50 +871,36 @@ async function askNumberOrMultiplier(promptText, defaultValue) {
875
871
  * @returns {Promise<number|string>} The value or '\x1b' if ESC.
876
872
  */
877
873
  async function askMaxPrice(promptText, defaultValue, minPrice) {
878
- printRangeQualityLegend();
879
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${colorPriceRangeValue(defaultValue)}]` : '';
880
- const raw = (await readInput(`${promptText}${suffix}: `, { colorize: (input) => colorRangeValueByQuality(input) })).trim();
881
- if (raw === '\x1b')
882
- return '\x1b';
883
- if (raw === '')
884
- return defaultValue;
885
- if (isMultiplierString(raw)) {
886
- const trimmed = raw.trim();
887
- const multiplier = parseFloat(trimmed);
888
- if (multiplier <= 0) {
889
- console.log(`Invalid ${promptText}: "${trimmed}". Multiplier must be > 0. No "0x" or negative values`);
890
- return askMaxPrice(promptText, defaultValue, minPrice);
891
- }
892
- // For maxPrice a multiplier < 1 ("0.7x") resolves to center*0.7 — a
893
- // bound BELOW the center. Reject so the rail can't land across the book.
894
- if (multiplier < 1) {
895
- console.log(`Invalid ${promptText}: "${trimmed}". For maxPrice, "Nx" means center*N, so a multiplier < 1 places the bound BELOW the center. Use a value > 1.`);
896
- return askMaxPrice(promptText, defaultValue, minPrice);
897
- }
898
- return trimmed;
899
- }
900
- const parsed = Number(raw);
901
- if (Number.isNaN(parsed)) {
902
- console.log('Please enter a valid number or multiplier (e.g. 5x).');
903
- return askMaxPrice(promptText, defaultValue, minPrice);
904
- }
905
- // Validate that number is > 0 (for price inputs)
906
- if (parsed <= 0) {
907
- console.log(`Invalid ${promptText}: ${parsed}. Must be > 0 (positive number)`);
908
- return askMaxPrice(promptText, defaultValue, minPrice);
909
- }
910
- // Validate that maxPrice > minPrice. Only comparable when minPrice is an
911
- // absolute value: a relative min ("2x") needs the grid center to resolve,
912
- // so it can't be checked here — the runtime bound validation covers it
913
- // (previously parseFloat("2x") == 2 wrongly rejected any absolute price <= 2).
914
- if (!isMultiplierString(minPrice)) {
915
- const minPriceValue = typeof minPrice === 'string' ? parseFloat(minPrice) : minPrice;
916
- if (parsed <= minPriceValue) {
917
- console.log(`Invalid ${promptText}: ${parsed}. Must be > minPrice (${minPriceValue})`);
918
- return askMaxPrice(promptText, defaultValue, minPrice);
919
- }
920
- }
921
- return parsed;
874
+ return askTypedInput({
875
+ promptText,
876
+ defaultValue,
877
+ onBeforePrompt: printRangeQualityLegend,
878
+ formatDefault: colorPriceRangeValue,
879
+ colorize: colorRangeValueByQuality,
880
+ parse: (raw) => {
881
+ if (isMultiplierString(raw)) {
882
+ const result = validateMultiplierInput(promptText, raw);
883
+ return 'error' in result ? result : { value: result.value };
884
+ }
885
+ const parsed = Number(raw);
886
+ if (Number.isNaN(parsed))
887
+ return { error: 'Please enter a valid number or multiplier (e.g. 5x).' };
888
+ // Validate that number is > 0 (for price inputs)
889
+ if (parsed <= 0)
890
+ return { error: `Invalid ${promptText}: ${parsed}. Must be > 0 (positive number)` };
891
+ // Validate that maxPrice > minPrice. Only comparable when minPrice is an
892
+ // absolute value: a relative min ("2x") needs the grid center to resolve,
893
+ // so it can't be checked here — the runtime bound validation covers it
894
+ // (previously parseFloat("2x") == 2 wrongly rejected any absolute price <= 2).
895
+ if (!isMultiplierString(minPrice)) {
896
+ const minPriceValue = typeof minPrice === 'string' ? parseFloat(minPrice) : minPrice;
897
+ if (minPriceValue != null && parsed <= minPriceValue) {
898
+ return { error: `Invalid ${promptText}: ${parsed}. Must be > minPrice (${minPriceValue})` };
899
+ }
900
+ }
901
+ return { value: parsed };
902
+ },
903
+ });
922
904
  }
923
905
  /**
924
906
  * Normalizes a percentage string input.
@@ -943,21 +925,21 @@ function normalizePercentageInput(value) {
943
925
  * @returns {Promise<number|string>} The value or '\x1b' if ESC.
944
926
  */
945
927
  async function askNumberOrPercentage(promptText, defaultValue) {
946
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${colorPercentageInput(defaultValue)}]` : '';
947
- const raw = (await readInput(`${promptText}${suffix}: `, { colorize: (input) => colorPercentageInput(input) })).trim();
948
- if (raw === '\x1b')
949
- return '\x1b';
950
- if (raw === '')
951
- return defaultValue;
952
- const percent = normalizePercentageInput(raw);
953
- if (percent !== null)
954
- return percent;
955
- const parsed = Number(raw);
956
- if (Number.isNaN(parsed)) {
957
- console.log('Please enter a valid number or percentage (e.g. 100, 50%).');
958
- return askNumberOrPercentage(promptText, defaultValue);
959
- }
960
- return parsed;
928
+ return askTypedInput({
929
+ promptText,
930
+ defaultValue,
931
+ formatDefault: colorPercentageInput,
932
+ colorize: colorPercentageInput,
933
+ parse: (raw) => {
934
+ const percent = normalizePercentageInput(raw);
935
+ if (percent !== null)
936
+ return { value: percent };
937
+ const parsed = Number(raw);
938
+ if (Number.isNaN(parsed))
939
+ return { error: 'Please enter a valid number or percentage (e.g. 100, 50%).' };
940
+ return { value: parsed };
941
+ },
942
+ });
961
943
  }
962
944
  /**
963
945
  * Parses a raw boolean answer.
@@ -1007,31 +989,22 @@ async function askBoolean(promptText, defaultValue) {
1007
989
  * @returns {Promise<number|string>} The start price or '\x1b' if ESC.
1008
990
  */
1009
991
  async function askStartPrice(promptText, defaultValue) {
1010
- while (true) {
1011
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${colorStartPriceValue(defaultValue)}]` : '';
1012
- const raw = (await readInput(`${promptText}${suffix}: `, {
1013
- colorize: (input) => colorStartPriceValue(input)
1014
- })).trim();
1015
- if (raw === '\x1b')
1016
- return '\x1b';
1017
- if (!raw) {
1018
- if (defaultValue !== undefined && defaultValue !== null) {
1019
- return defaultValue;
1020
- }
1021
- return undefined;
1022
- }
1023
- const lower = raw.toLowerCase();
1024
- if (lower === 'pool')
1025
- return lower;
1026
- if (lower === 'book')
1027
- return 'book';
1028
- // Accept numeric values (including decimals)
1029
- const num = Number(raw);
1030
- if (!Number.isNaN(num) && Number.isFinite(num)) {
1031
- return num;
1032
- }
1033
- console.log('Please enter "pool", "book", or a numeric value.');
1034
- }
992
+ return askTypedInput({
993
+ promptText,
994
+ defaultValue,
995
+ formatDefault: colorStartPriceValue,
996
+ colorize: colorStartPriceValue,
997
+ parse: (raw) => {
998
+ const lower = raw.toLowerCase();
999
+ if (lower === 'pool' || lower === 'book')
1000
+ return { value: lower };
1001
+ // Accept numeric values (including decimals)
1002
+ const num = Number(raw);
1003
+ if (!Number.isNaN(num) && Number.isFinite(num))
1004
+ return { value: num };
1005
+ return { error: 'Please enter "pool", "book", or a numeric value.' };
1006
+ },
1007
+ });
1035
1008
  }
1036
1009
  /**
1037
1010
  * Spellings that clear a `poolRef` pin, leaving the runtime to auto-select
@@ -1129,12 +1102,6 @@ async function askGridPriceMode(promptText, defaultValue) {
1129
1102
  console.log(`${COLORS.red}Please enter: ama1, ama2, ama3 or ama4 — also allowed: pool, book, ama, a positive number, or none (s/start, n/no/false/0/f).${COLORS.reset}`);
1130
1103
  }
1131
1104
  }
1132
- /**
1133
- * Normalizes a bot draft for editing or saving.
1134
- * Preserves existing fields and strips unsupported runtime-managed fields.
1135
- * @param {Object} [base={}] - The initial bot data to edit.
1136
- * @returns {Object} A normalized bot draft.
1137
- */
1138
1105
  function normalizeBotDraft(base = {}) {
1139
1106
  // Seeding rules live in modules/bot_defaults.ts (single defaults source).
1140
1107
  // Return type stays `any`: the editor prompt-flow treats drafts as dynamic
@@ -1214,7 +1181,7 @@ async function ensureBotAccountId(data, timeoutMs = 15000, quiet = false, force
1214
1181
  ]);
1215
1182
  }
1216
1183
  catch (err) {
1217
- const reason = err && err.code === 'ACCOUNT_LOOKUP_TIMEOUT' ? 'timeout' : 'error';
1184
+ const reason = err && getErrorCode(err) === 'ACCOUNT_LOOKUP_TIMEOUT' ? 'timeout' : 'error';
1218
1185
  if (!quiet) {
1219
1186
  const hint = reason === 'timeout'
1220
1187
  ? `nodes unreachable (timed out after ${timeoutMs}ms). Continuing without accountId — it will be stored automatically once a lookup succeeds.`
@@ -1282,10 +1249,21 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1282
1249
  // together with the rest of the draft.
1283
1250
  const baseEntry = base && typeof base === 'object' && Object.keys(base).length > 0 ? base : null;
1284
1251
  const baseBotKey = baseEntry ? String(normalizeBotEntry(baseEntry, baseIndex).botKey || '') : '';
1252
+ const isNewBot = !baseEntry;
1285
1253
  let adapterStaged = null;
1286
1254
  const isAmaGridPriceDraft = () => /^ama(?:[1-4])?$/.test(String(data.gridPrice ?? '').trim().toLowerCase());
1287
- const adapterFlags = () => adapterStaged
1288
- || getWhitelistFlags(baseBotKey || String(normalizeBotEntry(data, index).botKey || ''));
1255
+ // Staged menu-6 edits win. Otherwise an existing bot uses its stored entry;
1256
+ // a brand-new bot uses that entry too if one already exists for its key,
1257
+ // and only falls back to AMA pricing ON when there is no record at all — so
1258
+ // re-creating a previously configured key never silently flips its flags.
1259
+ const adapterFlags = () => {
1260
+ if (adapterStaged)
1261
+ return adapterStaged;
1262
+ const key = baseBotKey || String(normalizeBotEntry(data, index).botKey || '');
1263
+ if (!isNewBot)
1264
+ return getWhitelistFlags(key);
1265
+ return hasWhitelistEntry(key) ? getWhitelistFlags(key) : { ...AMA_ONLY_WHITELIST_FLAGS };
1266
+ };
1289
1267
  let finished = false;
1290
1268
  let cancelled = false;
1291
1269
  let showMenu = true;
@@ -1367,10 +1345,10 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1367
1345
  data.accountId = draft.accountId;
1368
1346
  }
1369
1347
  const active = await askBoolean('Active', data.active);
1370
- if (active === '\x1b')
1348
+ if (typeof active !== 'boolean')
1371
1349
  break;
1372
1350
  const dryRun = await askBoolean('Dry run', data.dryRun);
1373
- if (dryRun === '\x1b')
1351
+ if (typeof dryRun !== 'boolean')
1374
1352
  break;
1375
1353
  data.name = name;
1376
1354
  data.preferredAccount = prefAcc;
@@ -1417,11 +1395,15 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1417
1395
  const incrP = await askNumberWithBounds('incrementPercent', data.incrementPercent, INCREMENT_BOUNDS.MIN_PERCENT, INCREMENT_BOUNDS.MAX_PERCENT);
1418
1396
  if (incrP === '\x1b')
1419
1397
  break;
1398
+ if (typeof incrP !== 'number')
1399
+ break;
1420
1400
  const defaultSpread = data.targetSpreadPercent || incrP * 4;
1421
1401
  // Use current general settings for the validation limit
1422
1402
  const currentSettings = loadGeneralSettings();
1423
1403
  const targetS = await askTargetSpreadPercent('targetSpread %', defaultSpread, incrP, currentSettings.GRID_LIMITS.MIN_SPREAD_FACTOR);
1424
- if (targetS === '\x1b')
1404
+ if (typeof targetS !== 'number')
1405
+ break;
1406
+ if (typeof wSell !== 'number' || typeof wBuy !== 'number')
1425
1407
  break;
1426
1408
  data.weightDistribution.sell = wSell;
1427
1409
  data.weightDistribution.buy = wBuy;
@@ -1431,22 +1413,22 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1431
1413
  break;
1432
1414
  case '5':
1433
1415
  const fSell = await askNumberOrPercentage('botFunds sell amount', data.botFunds.sell);
1434
- if (fSell === '\x1b')
1416
+ if (fSell === undefined || fSell === '\x1b')
1435
1417
  break;
1436
1418
  const fBuy = await askNumberOrPercentage('botFunds buy amount', data.botFunds.buy);
1437
- if (fBuy === '\x1b')
1419
+ if (fBuy === undefined || fBuy === '\x1b')
1438
1420
  break;
1439
1421
  const oSell = await askIntegerInRange('activeOrders sell count', data.activeOrders.sell, 1, 100);
1440
- if (oSell === '\x1b')
1422
+ if (typeof oSell !== 'number')
1441
1423
  break;
1442
1424
  const oBuy = await askIntegerInRange('activeOrders buy count', data.activeOrders.buy, 1, 100);
1443
- if (oBuy === '\x1b')
1425
+ if (typeof oBuy !== 'number')
1444
1426
  break;
1445
1427
  const rBuy = await askIntegerInRange('reserveOrders buy floor count (0 disables)', data.reserveOrders?.buy ?? 0, 0, 100);
1446
- if (rBuy === '\x1b')
1428
+ if (typeof rBuy !== 'number')
1447
1429
  break;
1448
1430
  const rSell = await askIntegerInRange('reserveOrders sell ceiling count (0 disables)', data.reserveOrders?.sell ?? 0, 0, 100);
1449
- if (rSell === '\x1b')
1431
+ if (typeof rSell !== 'number')
1450
1432
  break;
1451
1433
  data.botFunds.sell = fSell;
1452
1434
  data.botFunds.buy = fBuy;
@@ -1465,12 +1447,18 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1465
1447
  const price = await askBoolean('AMA pricing (Price)', flags.ama);
1466
1448
  if (price === '\x1b')
1467
1449
  break;
1450
+ if (typeof price !== 'boolean')
1451
+ break;
1468
1452
  const weight = await askBoolean('Dynamic weights (Weight)', flags.dynamicWeight);
1469
1453
  if (weight === '\x1b')
1470
1454
  break;
1455
+ if (typeof weight !== 'boolean')
1456
+ break;
1471
1457
  const range = await askBoolean('Range scaling (Range)', flags.asymmetricBounds);
1472
1458
  if (range === '\x1b')
1473
1459
  break;
1460
+ if (typeof range !== 'boolean')
1461
+ break;
1474
1462
  adapterStaged = { ama: price, dynamicWeight: weight, asymmetricBounds: range };
1475
1463
  if (!price && (weight || range)) {
1476
1464
  console.log(`${COLORS.yellow}Note: Weight/Range only take effect while Price (AMA) is enabled.${COLORS.reset}`);
@@ -1489,8 +1477,8 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1489
1477
  const spreadFactor = Number.isFinite(currentSettings.GRID_LIMITS.MIN_SPREAD_FACTOR)
1490
1478
  ? currentSettings.GRID_LIMITS.MIN_SPREAD_FACTOR
1491
1479
  : GRID_LIMITS.MIN_SPREAD_FACTOR;
1492
- const minRequiredSpread = roundToDecimals(data.incrementPercent * spreadFactor, 2);
1493
- if (data.targetSpreadPercent + Number.EPSILON < minRequiredSpread) {
1480
+ const minRequiredSpread = roundToDecimals((data.incrementPercent ?? 0) * spreadFactor, 2);
1481
+ if ((data.targetSpreadPercent ?? 0) + Number.EPSILON < minRequiredSpread) {
1494
1482
  console.log(`${COLORS.red}Error: targetSpreadPercent (${data.targetSpreadPercent}) must be >= ${spreadFactor}x incrementPercent (${minRequiredSpread.toFixed(2)}).${COLORS.reset}`);
1495
1483
  break;
1496
1484
  }
@@ -1517,13 +1505,18 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1517
1505
  // flags already match what is stored — an unchanged save never creates a
1518
1506
  // placeholder entry.
1519
1507
  const stagedFlags = adapterStaged;
1520
- const commitAdapter = stagedFlags ? () => {
1508
+ // A new bot also commits without an explicit menu-6 edit: its resolved
1509
+ // default (record if present, else AMA-on) must be persisted so the market
1510
+ // adapter sees the same value the editor displayed. An unchanged save still
1511
+ // writes nothing.
1512
+ const commitAdapter = (stagedFlags || isNewBot) ? () => {
1521
1513
  const newKey = String(normalizeBotEntry(data, index).botKey || '');
1522
1514
  const needRename = !!(baseBotKey && newKey && baseBotKey !== newKey);
1515
+ const desired = stagedFlags || adapterFlags();
1523
1516
  const current = getWhitelistFlags(baseBotKey || newKey);
1524
- const unchanged = stagedFlags.ama === current.ama
1525
- && stagedFlags.dynamicWeight === current.dynamicWeight
1526
- && stagedFlags.asymmetricBounds === current.asymmetricBounds;
1517
+ const unchanged = desired.ama === current.ama
1518
+ && desired.dynamicWeight === current.dynamicWeight
1519
+ && desired.asymmetricBounds === current.asymmetricBounds;
1527
1520
  if (needRename && !renameWhitelistEntry(baseBotKey, newKey)) {
1528
1521
  console.log(`${COLORS.yellow}Adapter flags not saved — see the warning above.${COLORS.reset}`);
1529
1522
  return;
@@ -1532,7 +1525,7 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1532
1525
  // migrated the entry under the new key.
1533
1526
  if (unchanged)
1534
1527
  return;
1535
- if (!setWhitelistFlags(newKey, stagedFlags)) {
1528
+ if (!setWhitelistFlags(newKey, desired)) {
1536
1529
  console.log(`${COLORS.yellow}Warning: adapter flags not saved — could not write ${whitelistFile()}.${COLORS.reset}`);
1537
1530
  }
1538
1531
  else {
@@ -1590,6 +1583,8 @@ async function promptGeneralSettings() {
1590
1583
  const amaSlopeDelta = await askNumberWithBounds('AMA-Slope Δ', settings.MARKET_ADAPTER.AMA_SLOPE_DELTA_THRESHOLD_PERCENT, 0.1, 100.0);
1591
1584
  if (amaSlopeDelta === '\x1b')
1592
1585
  break;
1586
+ if (typeof gRegen !== 'number' || typeof rms !== 'number' || typeof amaDelta !== 'number' || typeof amaSlopeDelta !== 'number')
1587
+ break;
1593
1588
  settings.GRID_LIMITS.GRID_REGENERATION_PERCENTAGE = gRegen;
1594
1589
  settings.GRID_LIMITS.GRID_COMPARISON.RMS_PERCENTAGE = rms;
1595
1590
  settings.MARKET_ADAPTER.AMA_DELTA_THRESHOLD_PERCENT = amaDelta;
@@ -1599,10 +1594,14 @@ async function promptGeneralSettings() {
1599
1594
  const dust = await askNumberWithBounds('Partial Dust Threshold %', settings.GRID_LIMITS.PARTIAL_DUST_THRESHOLD_PERCENTAGE, 0.1, 50);
1600
1595
  if (dust === '\x1b')
1601
1596
  break;
1597
+ if (typeof dust !== 'number')
1598
+ break;
1602
1599
  settings.GRID_LIMITS.PARTIAL_DUST_THRESHOLD_PERCENTAGE = dust;
1603
1600
  const hcInterval = await askIntegerInRange('Health Check Interval (min)', (settings.NODES.healthCheck?.intervalMs || NODE_MANAGEMENT.HEALTH_CHECK_INTERVAL_MS) / 60000, 1, 43200);
1604
1601
  if (hcInterval === '\x1b')
1605
1602
  break;
1603
+ if (typeof hcInterval !== 'number')
1604
+ break;
1606
1605
  if (!settings.NODES.healthCheck)
1607
1606
  settings.NODES.healthCheck = {};
1608
1607
  settings.NODES.healthCheck.intervalMs = hcInterval * 60000;
@@ -1645,6 +1644,8 @@ async function promptGeneralSettings() {
1645
1644
  const removeIdx = await askIntegerInRange(' Enter node number to remove', 1, 1, nodeList.length);
1646
1645
  if (removeIdx === '\x1b')
1647
1646
  continue;
1647
+ if (typeof removeIdx !== 'number')
1648
+ continue;
1648
1649
  const removed = nodeList.splice(removeIdx - 1, 1)[0];
1649
1650
  console.log(` ${COLORS.green}Removed:${COLORS.reset} ${removed}`);
1650
1651
  }
@@ -1661,7 +1662,7 @@ async function promptGeneralSettings() {
1661
1662
  break;
1662
1663
  if (!settings.NODES.selection)
1663
1664
  settings.NODES.selection = {};
1664
- settings.NODES.selection.preferredNode = prefNode.trim() || null;
1665
+ settings.NODES.selection.preferredNode = (prefNode ?? '').trim() || null;
1665
1666
  break;
1666
1667
  case '4':
1667
1668
  const newLevel = await askLogLevel('Enter log level', settings.LOG_LEVEL);
@@ -1673,6 +1674,8 @@ async function promptGeneralSettings() {
1673
1674
  const upActive = await askBoolean('Enable Automated Updater', settings.UPDATER.ACTIVE !== false);
1674
1675
  if (upActive === '\x1b')
1675
1676
  break;
1677
+ if (typeof upActive !== 'boolean')
1678
+ break;
1676
1679
  settings.UPDATER.ACTIVE = upActive;
1677
1680
  console.log(` ${COLORS.gray}Branch:${COLORS.reset} ${COLORS.green}main${COLORS.reset}, ${COLORS.orange}dev${COLORS.reset}, ${COLORS.red}test${COLORS.reset}, or ${COLORS.blue}auto${COLORS.reset} (detected current)`);
1678
1681
  const branch = await askUpdaterBranch('Branch', settings.UPDATER.BRANCH);
@@ -1690,6 +1693,8 @@ async function promptGeneralSettings() {
1690
1693
  const noticeOn = await askBoolean('Show "new version available" notice on startup', settings.UPDATER.NOTICE_ENABLED !== false);
1691
1694
  if (noticeOn === '\x1b')
1692
1695
  break;
1696
+ if (typeof noticeOn !== 'boolean')
1697
+ break;
1693
1698
  settings.UPDATER.NOTICE_ENABLED = noticeOn;
1694
1699
  break;
1695
1700
  case 's':
@@ -1833,5 +1838,5 @@ async function main() {
1833
1838
  }
1834
1839
  console.log('Botmanager closed!');
1835
1840
  }
1836
- export { main, normalizeBotDraft, ensureBotAccountId, parseJsonWithComments, parseBooleanInput, colorGridPriceValue, formatPoolRefLabel, isPoolStartPrice, isPoolRefClearInput, loadGeneralSettings, saveGeneralSettings };
1841
+ export { main, normalizeBotDraft, ensureBotAccountId, parseJsonWithComments, parseBooleanInput, colorGridPriceValue, formatPoolRefLabel, isPoolStartPrice, isPoolRefClearInput, loadGeneralSettings };
1837
1842
  //# sourceMappingURL=account_bots.js.map