dexbot 1.6.10 → 1.6.12

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 (365) hide show
  1. package/CHANGELOG.md +50 -3
  2. package/README.md +3 -1
  3. package/analysis/README.md +51 -11
  4. package/analysis/bot_fitting/README.md +12 -0
  5. package/analysis/tradingview/README.md +3 -3
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +11 -37
  7. package/analysis/trend_detection/README.md +31 -0
  8. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  9. package/claw/modules/chain_broadcast.ts +7 -1
  10. package/claw/modules/claw_launcher.ts +1 -1
  11. package/claw/modules/launcher_mode_detector.ts +9 -2
  12. package/claw/package.json +1 -1
  13. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  14. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  15. package/dist/analysis/account_resolver.d.ts +1 -1
  16. package/dist/analysis/account_resolver.js +15 -2
  17. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  18. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -7
  19. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  20. package/dist/analysis/ama_fitting/fetch_lp_candles.js +4 -4
  21. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +20 -4
  22. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +9 -6
  23. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +16 -12
  24. package/dist/analysis/analyze_args.d.ts +31 -0
  25. package/dist/analysis/analyze_args.js +41 -0
  26. package/dist/analysis/analyze_dynamic_weight.js +7 -20
  27. package/dist/analysis/analyze_kalman.js +7 -17
  28. package/dist/analysis/analyze_regime.js +7 -17
  29. package/dist/analysis/analyze_regime_windows.js +8 -18
  30. package/dist/analysis/analyze_risk_profile.js +8 -18
  31. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  32. package/dist/analysis/analyze_volatility.js +7 -17
  33. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +220 -12
  34. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +55 -10
  35. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  36. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +72 -66
  37. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.d.ts +21 -0
  38. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +315 -0
  39. package/dist/analysis/bot_fitting/shared_utils.d.ts +7 -7
  40. package/dist/analysis/bot_fitting/shared_utils.js +2 -2
  41. package/dist/analysis/bot_key_utils.d.ts +18 -10
  42. package/dist/analysis/bot_key_utils.js +10 -17
  43. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  44. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  45. package/dist/analysis/chain_pool.d.ts +3 -1
  46. package/dist/analysis/chart_ui.d.ts +5 -2
  47. package/dist/analysis/chart_ui.js +6 -3
  48. package/dist/analysis/chart_utils.d.ts +5 -5
  49. package/dist/analysis/chart_utils.js +9 -0
  50. package/dist/analysis/fills_cache.d.ts +64 -0
  51. package/dist/analysis/fills_cache.js +254 -0
  52. package/dist/analysis/fills_source.d.ts +2 -2
  53. package/dist/analysis/fills_source.js +19 -14
  54. package/dist/analysis/grid_correction_check.d.ts +1 -1
  55. package/dist/analysis/grid_correction_check.js +12 -11
  56. package/dist/analysis/math_utils.d.ts +7 -6
  57. package/dist/analysis/math_utils.js +5 -8
  58. package/dist/analysis/pnl_report.d.ts +39 -0
  59. package/dist/analysis/pnl_report.js +325 -0
  60. package/dist/analysis/price_sources.d.ts +8 -8
  61. package/dist/analysis/price_sources.js +5 -4
  62. package/dist/analysis/resolve_bot_accounts.js +2 -2
  63. package/dist/analysis/resolve_source.d.ts +1 -2
  64. package/dist/analysis/trade_profitability.d.ts +32 -2
  65. package/dist/analysis/trade_profitability.js +232 -106
  66. package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
  67. package/dist/analysis/tradingview/analyze_tradingview.js +9 -10
  68. package/dist/analysis/tradingview/grid_reset_config.d.ts +42 -31
  69. package/dist/analysis/tradingview/grid_reset_config.js +35 -6
  70. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -8
  71. package/dist/analysis/tradingview/grid_reset_sim.js +42 -5
  72. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  73. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -20
  74. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +102 -0
  75. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +725 -0
  76. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  77. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +27 -112
  78. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +40 -0
  79. package/dist/analysis/trend_detection/huber_scale_variants.js +176 -0
  80. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  81. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  82. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  83. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  84. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  85. package/dist/credential-daemon.js +34 -20
  86. package/dist/dexbot.js +17 -14
  87. package/dist/market_adapter/candle_utils.d.ts +22 -18
  88. package/dist/market_adapter/candle_utils.js +24 -20
  89. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  90. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  91. package/dist/market_adapter/core/kibana_candles.d.ts +53 -18
  92. package/dist/market_adapter/core/kibana_candles.js +9 -7
  93. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  94. package/dist/market_adapter/core/kibana_client.js +8 -7
  95. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  96. package/dist/market_adapter/core/market_adapter_service.d.ts +297 -115
  97. package/dist/market_adapter/core/market_adapter_service.js +184 -101
  98. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  99. package/dist/market_adapter/core/strategies/ama.js +7 -32
  100. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  101. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  102. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  103. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  104. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  105. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  106. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +36 -8
  107. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +9 -9
  108. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  109. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  110. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  111. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  112. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  113. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  114. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  115. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  116. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  117. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  118. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +97 -226
  119. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +42 -7
  120. package/dist/market_adapter/inputs/fetch_lp_data.js +22 -15
  121. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  122. package/dist/market_adapter/inputs/kibana_feed_source.js +29 -22
  123. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  124. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  125. package/dist/market_adapter/inputs/window_cache.d.ts +99 -94
  126. package/dist/market_adapter/inputs/window_cache.js +8 -8
  127. package/dist/market_adapter/interval_utils.d.ts +4 -4
  128. package/dist/market_adapter/log_format.d.ts +6 -6
  129. package/dist/market_adapter/log_format.js +28 -22
  130. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  131. package/dist/market_adapter/lp_chart_core.js +26 -192
  132. package/dist/market_adapter/lp_chart_runner.d.ts +7 -7
  133. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  134. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  135. package/dist/market_adapter/market_adapter.d.ts +94 -33
  136. package/dist/market_adapter/market_adapter.js +69 -75
  137. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  138. package/dist/market_adapter/utils/adapter_client.js +2 -2
  139. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  140. package/dist/market_adapter/utils/chain.d.ts +50 -41
  141. package/dist/market_adapter/utils/chain.js +40 -46
  142. package/dist/market_adapter/utils/data_discovery.d.ts +4 -1
  143. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  144. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  145. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  146. package/dist/market_adapter/utils/file_lock.js +36 -32
  147. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  148. package/dist/market_adapter/utils/native_history.js +35 -28
  149. package/dist/modules/account_bots.d.ts +577 -21
  150. package/dist/modules/account_bots.js +182 -158
  151. package/dist/modules/account_orders.d.ts +66 -30
  152. package/dist/modules/account_orders.js +22 -20
  153. package/dist/modules/authority_resolver.d.ts +12 -2
  154. package/dist/modules/authority_resolver.js +15 -8
  155. package/dist/modules/bitshares-native/chain_client.d.ts +38 -3
  156. package/dist/modules/bitshares-native/chain_client.js +45 -46
  157. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  158. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  159. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  160. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  161. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  162. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  163. package/dist/modules/bitshares-native/index.d.ts +1 -1
  164. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  165. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  166. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  167. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  168. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  169. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  170. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  171. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  172. package/dist/modules/bitshares-native/serial/types.js +55 -62
  173. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  174. package/dist/modules/bitshares-native/signing_client.js +19 -14
  175. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  176. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  177. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  178. package/dist/modules/bitshares-native/transport.js +5 -4
  179. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  180. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  181. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  182. package/dist/modules/bitshares_client.d.ts +45 -13
  183. package/dist/modules/bitshares_client.js +28 -19
  184. package/dist/modules/bot_defaults.d.ts +6 -15
  185. package/dist/modules/bot_defaults.js +1 -5
  186. package/dist/modules/bot_settings.d.ts +44 -10
  187. package/dist/modules/bot_settings.js +11 -8
  188. package/dist/modules/bots_file_lock.d.ts +6 -6
  189. package/dist/modules/bots_file_lock.js +16 -12
  190. package/dist/modules/broadcast_failure.d.ts +2 -2
  191. package/dist/modules/broadcast_failure.js +5 -4
  192. package/dist/modules/chain_keys.d.ts +42 -40
  193. package/dist/modules/chain_keys.js +53 -45
  194. package/dist/modules/chain_orders.d.ts +93 -59
  195. package/dist/modules/chain_orders.js +31 -23
  196. package/dist/modules/constants.d.ts +530 -32
  197. package/dist/modules/constants.js +52 -60
  198. package/dist/modules/cr_planner.d.ts +40 -2
  199. package/dist/modules/credential_policy.d.ts +68 -8
  200. package/dist/modules/credential_policy.js +37 -31
  201. package/dist/modules/credential_session_cache.d.ts +2 -2
  202. package/dist/modules/credit_pricing.d.ts +42 -6
  203. package/dist/modules/credit_pricing.js +44 -30
  204. package/dist/modules/credit_runtime.d.ts +276 -118
  205. package/dist/modules/credit_runtime.js +462 -165
  206. package/dist/modules/crypto/browser_provider.js +6 -4
  207. package/dist/modules/crypto/node_provider.js +1 -1
  208. package/dist/modules/crypto/pure_scrypt.js +35 -4
  209. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  210. package/dist/modules/crypto/sync.d.ts +9 -9
  211. package/dist/modules/crypto/sync.js +16 -9
  212. package/dist/modules/dexbot_class.d.ts +195 -139
  213. package/dist/modules/dexbot_class.js +78 -28
  214. package/dist/modules/dexbot_cow_runtime.d.ts +167 -87
  215. package/dist/modules/dexbot_cow_runtime.js +248 -206
  216. package/dist/modules/dexbot_credential_client.d.ts +19 -11
  217. package/dist/modules/dexbot_fill_runtime.d.ts +63 -48
  218. package/dist/modules/dexbot_fill_runtime.js +48 -41
  219. package/dist/modules/dexbot_maintenance_runtime.d.ts +109 -70
  220. package/dist/modules/dexbot_maintenance_runtime.js +117 -80
  221. package/dist/modules/dexbot_startup_runtime.d.ts +11 -10
  222. package/dist/modules/dexbot_startup_runtime.js +43 -43
  223. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  224. package/dist/modules/dexbot_state_recovery.js +18 -13
  225. package/dist/modules/fund_registry.d.ts +4 -2
  226. package/dist/modules/fund_registry.js +10 -10
  227. package/dist/modules/general_settings.d.ts +30 -4
  228. package/dist/modules/graceful_shutdown.d.ts +3 -3
  229. package/dist/modules/graceful_shutdown.js +2 -2
  230. package/dist/modules/grid_price_source.d.ts +1 -1
  231. package/dist/modules/key_store.d.ts +14 -8
  232. package/dist/modules/key_store.js +7 -6
  233. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  234. package/dist/modules/launcher/adapter_requirement.js +5 -5
  235. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  236. package/dist/modules/launcher/bot_supervisor.js +12 -11
  237. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  238. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  239. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  240. package/dist/modules/launcher/credential_daemon.js +2 -2
  241. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  242. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  243. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  244. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  245. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  246. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  247. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  248. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  249. package/dist/modules/launcher/supervisor_control.js +4 -2
  250. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  251. package/dist/modules/market_adapter_whitelist.js +15 -3
  252. package/dist/modules/node_manager.d.ts +41 -11
  253. package/dist/modules/node_manager.js +5 -4
  254. package/dist/modules/order/accounting.d.ts +53 -24
  255. package/dist/modules/order/accounting.js +40 -14
  256. package/dist/modules/order/async_lock.d.ts +5 -2
  257. package/dist/modules/order/async_lock.js +1 -1
  258. package/dist/modules/order/export.d.ts +7 -6
  259. package/dist/modules/order/export.js +1 -7
  260. package/dist/modules/order/format.d.ts +39 -19
  261. package/dist/modules/order/format.js +62 -16
  262. package/dist/modules/order/genesis_policy.d.ts +21 -18
  263. package/dist/modules/order/genesis_policy.js +12 -8
  264. package/dist/modules/order/grid.d.ts +142 -36
  265. package/dist/modules/order/grid.js +148 -123
  266. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  267. package/dist/modules/order/grid_reconcile.js +13 -12
  268. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  269. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  270. package/dist/modules/order/index.d.ts +263 -1
  271. package/dist/modules/order/logger.d.ts +45 -11
  272. package/dist/modules/order/logger.js +38 -40
  273. package/dist/modules/order/logger_state.d.ts +4 -4
  274. package/dist/modules/order/manager.d.ts +226 -180
  275. package/dist/modules/order/manager.js +101 -83
  276. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  277. package/dist/modules/order/processed_fill_store.js +16 -27
  278. package/dist/modules/order/strategy.d.ts +21 -13
  279. package/dist/modules/order/strategy.js +5 -6
  280. package/dist/modules/order/sync_engine.d.ts +91 -33
  281. package/dist/modules/order/sync_engine.js +99 -54
  282. package/dist/modules/order/utils/math.d.ts +157 -102
  283. package/dist/modules/order/utils/math.js +77 -38
  284. package/dist/modules/order/utils/order.d.ts +326 -106
  285. package/dist/modules/order/utils/order.js +200 -99
  286. package/dist/modules/order/utils/slot.d.ts +1 -1
  287. package/dist/modules/order/utils/system.d.ts +176 -26
  288. package/dist/modules/order/utils/system.js +86 -69
  289. package/dist/modules/order/utils/validate.d.ts +89 -41
  290. package/dist/modules/order/utils/validate.js +24 -22
  291. package/dist/modules/order/utils/withPoolRef.d.ts +4 -3
  292. package/dist/modules/order/utils/withPoolRef.js +18 -12
  293. package/dist/modules/order/working_grid.d.ts +14 -13
  294. package/dist/modules/paths.d.ts +3 -4
  295. package/dist/modules/paths.js +3 -27
  296. package/dist/modules/process_discovery.d.ts +1 -1
  297. package/dist/modules/process_discovery.js +2 -1
  298. package/dist/modules/runtime.d.ts +7 -3
  299. package/dist/modules/runtime.js +4 -3
  300. package/dist/modules/runtime_settings.d.ts +15 -10
  301. package/dist/modules/runtime_settings.js +30 -24
  302. package/dist/modules/settings_merge.d.ts +29 -3
  303. package/dist/modules/settings_merge.js +56 -78
  304. package/dist/modules/socket_json_client.d.ts +7 -4
  305. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  306. package/dist/modules/storage/browser_adapter.js +7 -30
  307. package/dist/modules/storage/index.d.ts +1 -1
  308. package/dist/modules/storage/node_adapter.d.ts +45 -27
  309. package/dist/modules/storage/node_adapter.js +9 -9
  310. package/dist/modules/storage/types.d.ts +5 -4
  311. package/dist/modules/types.d.ts +1071 -2
  312. package/dist/modules/types.js +4 -1
  313. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  314. package/dist/modules/utils/asset_symbols.js +2 -1
  315. package/dist/modules/utils/errors.d.ts +9 -0
  316. package/dist/modules/utils/errors.js +23 -1
  317. package/dist/modules/utils/time_range.d.ts +4 -0
  318. package/dist/modules/utils/time_range.js +18 -0
  319. package/dist/modules/validate_profiles.js +53 -43
  320. package/dist/modules/version_notice.d.ts +14 -3
  321. package/dist/modules/version_notice.js +6 -4
  322. package/dist/pm2.d.ts +29 -27
  323. package/dist/pm2.js +5 -5
  324. package/dist/scripts/analyze-credit.d.ts +2 -1
  325. package/dist/scripts/analyze-credit.js +23 -24
  326. package/dist/scripts/analyze-orders.d.ts +77 -9
  327. package/dist/scripts/analyze-orders.js +66 -84
  328. package/dist/scripts/chart_command.d.ts +27 -18
  329. package/dist/scripts/chart_command.js +16 -15
  330. package/dist/scripts/check_any.d.ts +18 -0
  331. package/dist/scripts/check_any.js +126 -0
  332. package/dist/scripts/diagnose-pool-history.js +12 -7
  333. package/dist/scripts/pnl.d.ts +3 -0
  334. package/dist/scripts/pnl.js +40 -0
  335. package/dist/scripts/print_grid.js +0 -1
  336. package/dist/scripts/run-tests.js +39 -7
  337. package/dist/scripts/runner.js +1 -1
  338. package/dist/scripts/test-credit-renewal.js +30 -21
  339. package/dist/scripts/update.d.ts +10 -5
  340. package/dist/scripts/update.js +168 -103
  341. package/dist/scripts/update_dist_freshness.js +1 -0
  342. package/dist/scripts/update_layout.d.ts +61 -0
  343. package/dist/scripts/update_layout.js +180 -0
  344. package/dist/scripts/validate_bots.js +2 -1
  345. package/dist/scripts/verify-browser-bundle.js +8 -0
  346. package/dist/unlock.d.ts +28 -3
  347. package/dist/unlock.js +72 -10
  348. package/docs/BITSHARES_ONBOARDING.md +2 -0
  349. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  350. package/docs/COW_INVARIANTS.md +13 -6
  351. package/docs/DEXBOT_COMPARISON.md +8 -8
  352. package/docs/EVOLUTION.md +12 -10
  353. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  354. package/docs/GRID_RECALCULATION.md +15 -16
  355. package/docs/GRID_RECONCILE.md +14 -3
  356. package/docs/LIFECYCLE.md +11 -11
  357. package/docs/MPA_CREDIT_USAGE.md +22 -3
  358. package/docs/README.md +15 -4
  359. package/docs/WORKFLOW.md +1 -0
  360. package/docs/architecture.md +12 -9
  361. package/docs/developer_guide.md +6 -6
  362. package/market_adapter/README.md +9 -26
  363. package/modules/README.md +4 -1
  364. package/package.json +4 -1
  365. package/scripts/README.md +14 -0
@@ -3,7 +3,7 @@ import { createRequire } from 'node:module';
3
3
  const require = createRequire(import.meta.url);
4
4
  import { NATIVE_CLIENT } from '../constants.js';
5
5
  import Logger from '../order/logger.js';
6
- import { getErrorMessage } from '../utils/errors.js';
6
+ import { getErrorMessage, getErrorField } from '../utils/errors.js';
7
7
  let _WebSocketCtor = null;
8
8
  function getWebSocketConstructor() {
9
9
  if (!_WebSocketCtor) {
@@ -62,7 +62,7 @@ class RpcError extends Error {
62
62
  }
63
63
  }
64
64
  function createTransport(config = {}) {
65
- const { connectTimeoutMs = CONNECT_TIMEOUT_MS, rpcTimeoutMs = RPC_TIMEOUT_MS, onStatusChange = null, onReconnect = null, onNodeFailure = null, shouldSkipNode = null, validateNode = null, keepAliveIntervalMs = KEEPALIVE_INTERVAL_MS, } = config;
65
+ const { connectTimeoutMs = CONNECT_TIMEOUT_MS, rpcTimeoutMs = RPC_TIMEOUT_MS, onStatusChange = null, onReconnect = null, onNodeFailure = null, shouldSkipNode = null, validateNode = null, keepAliveIntervalMs = KEEPALIVE_INTERVAL_MS, reconnectBaseDelayMs = 1000, } = config;
66
66
  let ws = null;
67
67
  let nodeUrl = null;
68
68
  let reconnectTimer = null;
@@ -188,7 +188,7 @@ function createTransport(config = {}) {
188
188
  }, SLOW_RECONNECT_INTERVAL_MS);
189
189
  return;
190
190
  }
191
- const delay = Math.min(1000 * Math.pow(2, reconnectAttempts) + Math.random() * 1000, 30000);
191
+ const delay = Math.min(reconnectBaseDelayMs * Math.pow(2, reconnectAttempts) + Math.random() * reconnectBaseDelayMs, 30000);
192
192
  reconnectAttempts++;
193
193
  reconnectTimer = setTimeout(() => {
194
194
  reconnectTimer = null;
@@ -424,7 +424,8 @@ function createTransport(config = {}) {
424
424
  catch (firstErr) {
425
425
  // All parallel attempts failed. Fall back to sequential retry for
426
426
  // environments where parallel connection floods are problematic.
427
- const errMsg = firstErr?.errors ? firstErr.errors.map((e) => e?.message || e).join('; ') : (firstErr?.message || firstErr);
427
+ const firstErrErrors = getErrorField(firstErr, 'errors');
428
+ const errMsg = firstErrErrors ? firstErrErrors.map((e) => getErrorMessage(e)).join('; ') : (getErrorMessage(firstErr));
428
429
  transportLogger.warn(`Parallel connect failed (${candidates.length} nodes), falling back to sequential: ${errMsg}`);
429
430
  }
430
431
  // Sequential fallback pass.
@@ -4,6 +4,7 @@ declare class TransactionTooLargeError extends Error {
4
4
  code: string;
5
5
  constructor(message: string);
6
6
  }
7
+ type OpParams = Record<string, unknown>;
7
8
  interface ChainClientRef {
8
9
  getConfig?(): {
9
10
  chainId: string;
@@ -13,12 +14,46 @@ interface ChainClientRef {
13
14
  };
14
15
  reportNodeFailure?(nodeUrl: string, errorMessage?: string, source?: string): void;
15
16
  db: {
16
- call(method: string, args: any[]): Promise<any>;
17
- get_objects(ids: string[]): Promise<any[]>;
18
- get_dynamic_global_properties(): Promise<any>;
19
- [key: string]: (...args: any[]) => Promise<any>;
17
+ call(method: string, args: unknown[]): Promise<unknown>;
18
+ get_objects(ids: string[]): Promise<unknown[]>;
19
+ get_dynamic_global_properties(): Promise<unknown>;
20
+ [key: string]: (...args: never[]) => Promise<unknown>;
20
21
  };
21
22
  }
22
- declare function createTransactionBuilder(chainClient: ChainClientRef): any;
23
+ interface SignedTxResult {
24
+ signedTx: Buffer;
25
+ signedTxObject: Record<string, unknown>;
26
+ digest: Buffer;
27
+ signature: Buffer;
28
+ }
29
+ interface TransactionBuilder {
30
+ addOperation(type: string, params: OpParams): this;
31
+ limit_order_create(data: OpParams): this;
32
+ limit_order_cancel(data: OpParams): this;
33
+ limit_order_update(data: OpParams): this;
34
+ call_order_update(data: OpParams): this;
35
+ asset_settle(data: OpParams): this;
36
+ transfer(data: OpParams): this;
37
+ credit_offer_accept(data: OpParams): this;
38
+ credit_deal_repay(data: OpParams): this;
39
+ credit_deal_update(data: OpParams): this;
40
+ liquidity_pool_exchange(data: OpParams): this;
41
+ setRequiredFees(feeAssetId?: string): Promise<void>;
42
+ fetchRefBlock(): Promise<void>;
43
+ setExpiration(seconds?: number): void;
44
+ prepare(feeAssetId?: string): Promise<Buffer>;
45
+ _serializeUnsigned(): Buffer;
46
+ _buildSerializedOp(type: string, params: OpParams): [number, unknown];
47
+ _castParamsToSerializable(type: string, params: OpParams): OpParams;
48
+ sign(privateKey: Buffer): SignedTxResult;
49
+ broadcast(): Promise<never>;
50
+ _getSerializedOps(): Array<[number, unknown]>;
51
+ getOperationCount(): number;
52
+ getOperations(): Array<{
53
+ type: string;
54
+ params: OpParams;
55
+ }>;
56
+ }
57
+ declare function createTransactionBuilder(chainClient: ChainClientRef): TransactionBuilder & Record<string, unknown>;
23
58
  export { createTransactionBuilder, TransactionTooLargeError, MAX_TX_SIZE, MAX_OPS_PER_TX };
24
59
  //# sourceMappingURL=builder.d.ts.map
@@ -209,10 +209,11 @@ function createTransactionBuilder(chainClient) {
209
209
  }
210
210
  if (type === 'limit_order_update') {
211
211
  if (result.new_price) {
212
+ const np = result.new_price;
212
213
  result.new_price = {
213
- ...result.new_price,
214
- base: { ...result.new_price.base },
215
- quote: { ...result.new_price.quote },
214
+ ...np,
215
+ base: { ...np.base },
216
+ quote: { ...np.quote },
216
217
  };
217
218
  }
218
219
  }
@@ -4,15 +4,15 @@
4
4
  * setRequiredFees writes back onto the ops) to avoid stale fees when the
5
5
  * same op type has different parameters (e.g. different amounts or extensions).
6
6
  */
7
- declare function buildFeeCacheKey(opList: Array<[number, any]>, feeAssetId: string): string;
8
- declare function getFees(cacheKey: string): any[] | undefined;
9
- declare function setFees(cacheKey: string, fees: any[]): void;
7
+ declare function buildFeeCacheKey(opList: Array<[number, unknown]>, feeAssetId: string): string;
8
+ declare function getFees(cacheKey: string): unknown[] | undefined;
9
+ declare function setFees(cacheKey: string, fees: unknown[]): void;
10
10
  /**
11
11
  * Peek at cached fees without expiry-based deletion.
12
12
  * Returns the fee array even if stale (expired), or undefined if absent.
13
13
  * Useful as a fallback when a chain re-fetch fails.
14
14
  */
15
- declare function peekFees(cacheKey: string): any[] | undefined;
15
+ declare function peekFees(cacheKey: string): unknown[] | undefined;
16
16
  declare function invalidateFees(): void;
17
17
  export { buildFeeCacheKey, getFees, setFees, peekFees, invalidateFees };
18
18
  //# sourceMappingURL=tx_cache.d.ts.map
@@ -34,13 +34,16 @@
34
34
  * 16. _internal - @internal Internal state (connected flag) — test-only, do not rely on in production
35
35
  * ===============================================================================
36
36
  */
37
+ import NodeManager from './node_manager.js';
37
38
  import { withTimeout } from './order/utils/timeout.js';
39
+ import { createSigningClient } from './bitshares-native/index.js';
40
+ type NativeSigningClient = ReturnType<typeof createSigningClient>['client'];
38
41
  /**
39
42
  * Register a callback to be called after a successful reconnection.
40
43
  * @param {Function} callback - Called with no arguments after subscription re-establishment
41
44
  * @returns {Function} Unregister function
42
45
  */
43
- declare function onReconnect(callback: any): () => void;
46
+ declare function onReconnect(callback: unknown): () => void;
44
47
  /**
45
48
  * Whether a transport-reported node failure should count as a persistent strike
46
49
  * in the NodeManager ledger.
@@ -61,13 +64,30 @@ declare function onReconnect(callback: any): () => void;
61
64
  * rather than mere attempts.
62
65
  */
63
66
  export declare function shouldCountNodeStrike(source?: string): boolean;
64
- declare const _lazyBitShares: any;
67
+ interface LazyBitShares {
68
+ db: Record<string, (...args: unknown[]) => Promise<unknown>>;
69
+ history: Record<string, (...args: unknown[]) => Promise<unknown>>;
70
+ assets: Record<string, unknown>;
71
+ accounts: Record<string, unknown>;
72
+ chain: {
73
+ coreAsset: unknown;
74
+ };
75
+ connect(...args: unknown[]): unknown;
76
+ disconnect(...args: unknown[]): unknown;
77
+ subscribe(...args: unknown[]): Promise<unknown>;
78
+ unsubscribe(...args: unknown[]): Promise<unknown>;
79
+ node: unknown;
80
+ autoreconnect: boolean;
81
+ connectPromise: unknown;
82
+ [key: string]: unknown;
83
+ }
84
+ declare const _lazyBitShares: LazyBitShares;
65
85
  /**
66
86
  * Suppress or restore connection log output.
67
87
  * @param {boolean} suppress - Whether to suppress connection logs
68
88
  * @returns {void}
69
89
  */
70
- declare function setSuppressConnectionLog(suppress: any): void;
90
+ declare function setSuppressConnectionLog(suppress: boolean): void;
71
91
  /** Whether connection log output is currently suppressed. */
72
92
  declare function isSuppressConnectionLog(): boolean;
73
93
  /**
@@ -76,7 +96,7 @@ declare function isSuppressConnectionLog(): boolean;
76
96
  * @returns {Promise<boolean>} True if failover reconnect succeeded
77
97
  * @private
78
98
  */
79
- declare function assessFailover(reason?: any): Promise<any>;
99
+ declare function assessFailover(reason?: string): Promise<boolean>;
80
100
  /**
81
101
  * Wait for the BitShares connection to become ready.
82
102
  * @param {number} [timeoutMs=TIMING.CONNECTION_TIMEOUT_MS] - Max time to wait in ms
@@ -87,7 +107,7 @@ declare function assessFailover(reason?: any): Promise<any>;
87
107
  * @returns {Promise<boolean>} True when connected
88
108
  * @throws {Error} If connection times out
89
109
  */
90
- declare function waitForConnected(timeoutMs?: any, options?: {
110
+ declare function waitForConnected(timeoutMs?: number, options?: {
91
111
  retryDelayMs?: number;
92
112
  maxRetryDelayMs?: number;
93
113
  refreshNodesEveryMs?: number;
@@ -98,12 +118,12 @@ declare function waitForConnected(timeoutMs?: any, options?: {
98
118
  * @param {string|Object} privateKey - Private key or daemon signing token
99
119
  * @returns {Promise<Object>} Account client with initPromise, newTx(), broadcast()
100
120
  */
101
- declare function createAccountClient(accountName: any, privateKey: any): Promise<any>;
121
+ declare function createAccountClient(accountName: unknown, privateKey: unknown): Promise<NativeSigningClient>;
102
122
  /**
103
123
  * Get the current connection status.
104
124
  * @returns {string} Status string from native client
105
125
  */
106
- declare function getConnectionStatus(): any;
126
+ declare function getConnectionStatus(): string;
107
127
  /**
108
128
  * Disconnect the BitShares client.
109
129
  * @returns {Promise<void>}
@@ -114,17 +134,29 @@ declare function disconnectClient(): Promise<void>;
114
134
  * @param {string} [reason='adapter-cycle'] - Reason for reconnection
115
135
  * @returns {Promise<boolean>} True if reconnection succeeded
116
136
  */
117
- declare function reconnectForCycle(reason?: any): Promise<boolean>;
118
- declare function getNodeManager(): any;
119
- declare function getNodeStats(): any;
120
- declare function getNodeSummary(): any;
121
- declare function getConnectionError(): any;
137
+ declare function reconnectForCycle(reason?: string): Promise<boolean>;
138
+ declare function getNodeManager(): NodeManager | null;
139
+ declare function getNodeStats(): {
140
+ url: string;
141
+ status: string;
142
+ latencyMs: number | null;
143
+ failureCount: number;
144
+ lastCheckTime: string | null;
145
+ lastErrorMessage: string | null;
146
+ }[] | undefined;
147
+ declare function getNodeSummary(): {
148
+ monitoring: boolean;
149
+ counts: Record<string, number>;
150
+ bestNode: string | null;
151
+ avgLatency: number | null;
152
+ } | undefined;
153
+ declare function getConnectionError(): unknown;
122
154
  /** @internal Exposed for unit tests only — do not rely on in production code. */
123
155
  declare const _internal: {
124
156
  readonly connected: boolean;
125
157
  };
126
158
  declare const _default: {
127
- BitShares: any;
159
+ BitShares: LazyBitShares;
128
160
  createAccountClient: typeof createAccountClient;
129
161
  waitForConnected: typeof waitForConnected;
130
162
  getConnectionStatus: typeof getConnectionStatus;
@@ -70,8 +70,9 @@ function onReconnect(callback) {
70
70
  logger.warn(`onReconnect requires a function, got ${typeof callback}`);
71
71
  return () => { };
72
72
  }
73
- _reconnectCallbacks.add(callback);
74
- return () => { _reconnectCallbacks.delete(callback); };
73
+ const reconnectFn = callback;
74
+ _reconnectCallbacks.add(reconnectFn);
75
+ return () => { _reconnectCallbacks.delete(reconnectFn); };
75
76
  }
76
77
  async function notifyReconnectCallbacks() {
77
78
  if (_reconnectCallbacks.size === 0)
@@ -81,17 +82,17 @@ async function notifyReconnectCallbacks() {
81
82
  await Promise.resolve(cb());
82
83
  }
83
84
  catch (err) {
84
- logger.warn(`Reconnect callback error: ${err?.message || err}`);
85
+ logger.warn(`Reconnect callback error: ${getErrorMessage(err)}`);
85
86
  }
86
87
  }
87
88
  }
88
89
  // Lazy initialization guard
89
90
  let _initialized = false;
90
91
  // Native client references (lazily initialized)
91
- let _nativeClient = null;
92
- let _subscriptionManager = null;
93
- let _nativeBitSharesProxy = null;
94
- let _resolvers = null;
92
+ let _nativeClient;
93
+ let _subscriptionManager;
94
+ let _nativeBitSharesProxy;
95
+ let _resolvers;
95
96
  // Monotonic generation counter for native _nativeClient.connect() calls.
96
97
  // The native transport's connect() sweep cannot be cancelled, so a timeout
97
98
  // in the outer withTimeout wrapper only stops the *awaiter* — the sweep
@@ -230,22 +231,26 @@ function ensureInitialized() {
230
231
  // (15s) on every call(). An additional wrapper here would only add
231
232
  // dead slack past the native rejection and produce misleading
232
233
  // error messages. Pass through directly.
233
- return new Proxy(_nativeClient.db, {
234
+ const source = _nativeClient.db;
235
+ return new Proxy(source, {
234
236
  get(target, prop) {
235
- if (typeof target[prop] === 'function') {
236
- return (...args) => target[prop](...args);
237
+ const key = String(prop);
238
+ if (typeof target[key] === 'function') {
239
+ return (...args) => target[key](...args);
237
240
  }
238
- return (...args) => target.call(prop, args);
241
+ return (...args) => target.call(key, args);
239
242
  },
240
243
  });
241
244
  },
242
245
  get history() {
243
- return new Proxy(_nativeClient.history, {
246
+ const source = _nativeClient.history;
247
+ return new Proxy(source, {
244
248
  get(target, prop) {
245
- if (typeof target[prop] === 'function') {
246
- return (...args) => target[prop](...args);
249
+ const key = String(prop);
250
+ if (typeof target[key] === 'function') {
251
+ return (...args) => target[key](...args);
247
252
  }
248
- return (...args) => target.call(prop, args);
253
+ return (...args) => target.call(key, args);
249
254
  },
250
255
  });
251
256
  },
@@ -258,7 +263,7 @@ function ensureInitialized() {
258
263
  });
259
264
  const nodeSettings = settings?.NODES;
260
265
  const configuredNodes = Array.isArray(nodeSettings?.list)
261
- ? nodeSettings.list.filter((node) => typeof node === 'string' && node.trim())
266
+ ? nodeSettings.list.filter((node) => typeof node === 'string' && Boolean(node.trim()))
262
267
  : [];
263
268
  nodeManagerEnabled = nodeSettings?.enabled ?? NODE_MANAGEMENT.DEFAULT_ENABLED;
264
269
  const effectiveNodes = configuredNodes.length > 0 ? configuredNodes : NODE_MANAGEMENT.DEFAULT_NODES;
@@ -284,10 +289,14 @@ function ensureInitialized() {
284
289
  const _lazyBitShares = new Proxy({}, {
285
290
  get(_target, prop) {
286
291
  ensureInitialized();
292
+ if (typeof prop !== 'string')
293
+ return undefined;
287
294
  return _nativeBitSharesProxy[prop];
288
295
  },
289
296
  set(_target, prop, value) {
290
297
  ensureInitialized();
298
+ if (typeof prop !== 'string')
299
+ return false;
291
300
  _nativeBitSharesProxy[prop] = value;
292
301
  return true;
293
302
  },
@@ -364,7 +373,7 @@ async function restartBitsharesConnection(serverList, reason = 'startup') {
364
373
  await _subscriptionManager.onReconnect();
365
374
  }
366
375
  catch (err) {
367
- logger.warn(`Subscription re-establishment after reconnect failed: ${err?.message || err}`);
376
+ logger.warn(`Subscription re-establishment after reconnect failed: ${getErrorMessage(err)}`);
368
377
  }
369
378
  }
370
379
  // Notify registered reconnection callbacks (e.g. DEXBot safety-net sync)
@@ -613,7 +622,7 @@ async function waitForConnected(timeoutMs = TIMING.CONNECTION_TIMEOUT_MS, option
613
622
  retryDelayMs = Math.min(maxDelayMs, retryDelayMs > 0 ? retryDelayMs * 2 : maxDelayMs);
614
623
  }
615
624
  if (!connected) {
616
- const suffix = lastConnectionError?.message ? ` Last error: ${lastConnectionError.message}` : '';
625
+ const suffix = lastConnectionError?.message ? ` Last error: ${getErrorMessage(lastConnectionError)}` : '';
617
626
  throw new Error(`Timed out waiting for BitShares connection after ${timeoutMs}ms.${suffix}`);
618
627
  }
619
628
  return true;
@@ -627,7 +636,7 @@ async function waitForConnected(timeoutMs = TIMING.CONNECTION_TIMEOUT_MS, option
627
636
  async function createAccountClient(accountName, privateKey) {
628
637
  ensureInitialized();
629
638
  await waitForConnected(TIMING.CONNECTION_TIMEOUT_MS);
630
- const signingClient = createSigningClient(_nativeClient, accountName, privateKey);
639
+ const signingClient = createSigningClient(_nativeClient, String(accountName), privateKey);
631
640
  return signingClient.client;
632
641
  }
633
642
  /**
@@ -18,9 +18,10 @@
18
18
  * Mode rules are pinned by tests/test_bot_defaults_characterization.ts and
19
19
  * tests/test_bot_defaults_parity.ts — update them together with this file.
20
20
  */
21
+ import type { UnknownRecord } from './types.js';
21
22
  export interface SeedOptions {
22
23
  /** Defaults source; omit to use the merged DEFAULT_CONFIG. */
23
- defaults?: Record<string, any>;
24
+ defaults?: UnknownRecord;
24
25
  }
25
26
  /**
26
27
  * DEFAULT_CONFIG keys the draft seed must NEVER add. Seeding these would change
@@ -36,16 +37,6 @@ export declare const DRAFT_EXCLUDED_KEYS: string[];
36
37
  * fails when a new DEFAULT_CONFIG key is added without classifying it here.
37
38
  */
38
39
  export declare const DRAFT_SEED_ORDER: string[];
39
- /** Fields with no meaning since the grid-price offset was removed; stripped from drafts. */
40
- export declare const LEGACY_DRAFT_KEYS: string[];
41
- /**
42
- * Spellings that mean "no explicit grid price" — delegate to startPrice.
43
- * `none`/`null`/`start`/`startprice` are the editor's documented aliases;
44
- * `n`/`no`/`false`/`0`/`f` are the boolean-style deactivating answers accepted
45
- * elsewhere in the editor, `s` is shorthand for `startPrice`, and the boolean
46
- * `false` covers a hand-edited `gridPrice: false`.
47
- */
48
- export declare const GRID_PRICE_UNSET_INPUTS: Set<string>;
49
40
  /**
50
41
  * True when a grid-price value carries no reference and must degrade to the
51
42
  * startPrice fallback. Keeps `null`/`undefined`/`false`, empty/whitespace
@@ -55,7 +46,7 @@ export declare const GRID_PRICE_UNSET_INPUTS: Set<string>;
55
46
  * @param {*} value - Candidate grid-price value.
56
47
  * @returns {boolean}
57
48
  */
58
- export declare function isUnsetGridPrice(value: any): boolean;
49
+ export declare function isUnsetGridPrice(value: unknown): boolean;
59
50
  /**
60
51
  * Editor draft seed (formerly the `normalizeBotDraft` if-chain in
61
52
  * modules/account_bots.ts). Deep-clones the input, then applies defaults:
@@ -70,7 +61,7 @@ export declare function isUnsetGridPrice(value: any): boolean;
70
61
  * was a hardcoded null that ignored DEFAULT_CONFIG.gridPrice overrides);
71
62
  * * other scalars: filled only when `=== undefined` — explicit nulls survive.
72
63
  */
73
- export declare function seedBotDraft(base?: Record<string, any> | null, options?: SeedOptions): Record<string, any>;
64
+ export declare function seedBotDraft(base?: UnknownRecord | null, options?: SeedOptions): UnknownRecord;
74
65
  /**
75
66
  * Runtime entry default (formerly duplicated in `modules/bot_settings.ts` and
76
67
  * `claw/modules/dexbot_profiles.ts`). Only `active` is defaulted:
@@ -85,7 +76,7 @@ export declare function seedBotDraft(base?: Record<string, any> | null, options?
85
76
  * missing keys as mistakes (assetA/assetB must be genuinely absent when
86
77
  * unconfigured).
87
78
  */
88
- export declare function seedBotEntry<T extends Record<string, any>>(entry: T, options?: SeedOptions): T;
79
+ export declare function seedBotEntry<T extends UnknownRecord>(entry: T, options?: SeedOptions): T;
89
80
  /**
90
81
  * Runtime config seed (formerly `{ ...DEFAULT_CONFIG, ...config }` in the
91
82
  * OrderManager constructor). Produces exactly the spread result — same key
@@ -94,5 +85,5 @@ export declare function seedBotEntry<T extends Record<string, any>>(entry: T, op
94
85
  * `manager.config.botFunds` can no longer corrupt the global DEFAULT_CONFIG
95
86
  * (the historical shallow spread aliased every nested default object).
96
87
  */
97
- export declare function seedBotRuntimeConfig(config?: Record<string, any>, options?: SeedOptions): Record<string, any>;
88
+ export declare function seedBotRuntimeConfig(config?: UnknownRecord, options?: SeedOptions): UnknownRecord;
98
89
  //# sourceMappingURL=bot_defaults.d.ts.map
@@ -37,8 +37,6 @@ export const DRAFT_SEED_ORDER = [
37
37
  'active', 'dryRun', 'minPrice', 'maxPrice', 'incrementPercent',
38
38
  'targetSpreadPercent', 'startPrice', 'gridPrice',
39
39
  ];
40
- /** Fields with no meaning since the grid-price offset was removed; stripped from drafts. */
41
- export const LEGACY_DRAFT_KEYS = ['gridPriceOffsetPct', 'gridPriceOffsetClampToBounds'];
42
40
  /**
43
41
  * Spellings that mean "no explicit grid price" — delegate to startPrice.
44
42
  * `none`/`null`/`start`/`startprice` are the editor's documented aliases;
@@ -46,7 +44,7 @@ export const LEGACY_DRAFT_KEYS = ['gridPriceOffsetPct', 'gridPriceOffsetClampToB
46
44
  * elsewhere in the editor, `s` is shorthand for `startPrice`, and the boolean
47
45
  * `false` covers a hand-edited `gridPrice: false`.
48
46
  */
49
- export const GRID_PRICE_UNSET_INPUTS = new Set(['none', 'null', 'start', 'startprice', 's', 'n', 'no', 'false', '0', 'f']);
47
+ const GRID_PRICE_UNSET_INPUTS = new Set(['none', 'null', 'start', 'startprice', 's', 'n', 'no', 'false', '0', 'f']);
50
48
  /**
51
49
  * True when a grid-price value carries no reference and must degrade to the
52
50
  * startPrice fallback. Keeps `null`/`undefined`/`false`, empty/whitespace
@@ -123,8 +121,6 @@ export function seedBotDraft(base, options = {}) {
123
121
  data[key] = def;
124
122
  }
125
123
  }
126
- for (const key of LEGACY_DRAFT_KEYS)
127
- delete data[key];
128
124
  return data;
129
125
  }
130
126
  /**
@@ -1,21 +1,55 @@
1
+ import type { UnknownRecord } from './types.js';
2
+ /** A single `debtPolicy.lending[]` entry (loosely typed: validated at runtime). */
3
+ export interface BotLendingEntry extends UnknownRecord {
4
+ asset?: unknown;
5
+ collateralAsset?: unknown;
6
+ type?: unknown;
7
+ }
8
+ /** `debtPolicy` block of a bot entry. */
9
+ export interface BotDebtPolicy extends UnknownRecord {
10
+ lending?: BotLendingEntry[];
11
+ maxCollateralAmount?: unknown;
12
+ }
13
+ /** A loosely-typed bot entry as read from bots.json / user input. */
14
+ export interface BotEntry extends UnknownRecord {
15
+ name?: string;
16
+ active?: boolean;
17
+ creditOnly?: boolean;
18
+ assetA?: string;
19
+ assetB?: string;
20
+ botKey?: string;
21
+ botIndex?: number;
22
+ preferredAccount?: string;
23
+ activeOrders?: UnknownRecord;
24
+ reserveOrders?: number | UnknownRecord;
25
+ botFunds?: {
26
+ buy?: unknown;
27
+ sell?: unknown;
28
+ };
29
+ debtPolicy?: BotDebtPolicy;
30
+ }
31
+ /** The top-level bots.json document. */
32
+ export interface BotSettingsFile extends UnknownRecord {
33
+ bots?: BotEntry[];
34
+ }
1
35
  declare function loadSettingsFile(filePath: string, { silent, exitOnError }?: {
2
36
  silent?: boolean;
3
37
  exitOnError?: boolean;
4
38
  }): {
5
- config: any;
39
+ config: BotSettingsFile;
6
40
  filePath: string;
7
41
  };
8
- declare function saveSettingsFile(config: any, filePath: string): void;
9
- declare function resolveRawBotEntries(settings: any): any[];
10
- declare function normalizeBotEntry(entry: any, index?: number): any;
11
- declare function normalizeBotEntries(rawEntries: any[]): any[];
12
- declare function selectBotEntry(settings: any, botName: string): any;
13
- declare function selectActiveBotEntries(settings: any): any[];
14
- declare function validateBotEntry(b: any, i: number, src: string): string | null;
15
- declare function collectValidationIssues(entries: any[], sourceName: string): {
42
+ declare function saveSettingsFile(config: UnknownRecord, filePath: string): void;
43
+ declare function resolveRawBotEntries(settings: unknown): BotEntry[];
44
+ declare function normalizeBotEntry(entry: BotEntry, index?: number): BotEntry;
45
+ declare function normalizeBotEntries(rawEntries: unknown[]): BotEntry[];
46
+ declare function selectBotEntry(settings: unknown, botName: string): BotEntry | null;
47
+ declare function selectActiveBotEntries(settings: unknown): BotEntry[];
48
+ declare function validateBotEntry(b: BotEntry, i: number, src: string): string | null;
49
+ declare function collectValidationIssues(entries: BotEntry[], sourceName: string): {
16
50
  errors: string[];
17
51
  warnings: string[];
18
52
  };
19
- declare function assertNoDuplicateBotKeys(entries: any[], sourceName: string): void;
53
+ declare function assertNoDuplicateBotKeys(entries: BotEntry[], sourceName: string): void;
20
54
  export { assertNoDuplicateBotKeys, collectValidationIssues, loadSettingsFile, normalizeBotEntry, normalizeBotEntries, resolveRawBotEntries, saveSettingsFile, selectActiveBotEntries, selectBotEntry, validateBotEntry };
21
55
  //# sourceMappingURL=bot_settings.d.ts.map
@@ -8,6 +8,7 @@ import { isPositiveNumber, isPositiveNumberOrPercent, toDecimal } from './order/
8
8
  import { resolveMinCollateralIncreaseThreshold } from './cr_planner.js';
9
9
  import { getErrorMessage } from './utils/errors.js';
10
10
  import { canonicalizeBotAssetSymbols } from './utils/asset_symbols.js';
11
+ import { isUnknownRecord } from './types.js';
11
12
  const storage = getStorage();
12
13
  const { writeJSON } = storage;
13
14
  function loadSettingsFile(filePath, { silent = false, exitOnError = true } = {}) {
@@ -41,7 +42,7 @@ function saveSettingsFile(config, filePath) {
41
42
  }
42
43
  }
43
44
  function resolveRawBotEntries(settings) {
44
- if (!settings || typeof settings !== 'object')
45
+ if (!isUnknownRecord(settings))
45
46
  return [];
46
47
  if (Array.isArray(settings.bots))
47
48
  return settings.bots;
@@ -110,7 +111,8 @@ function validateBotEntry(b, i, src) {
110
111
  }
111
112
  else {
112
113
  for (const side of ['buy', 'sell']) {
113
- const v = b.reserveOrders[side];
114
+ const reserveOrders = b.reserveOrders;
115
+ const v = reserveOrders[side];
114
116
  if (v !== undefined && (!Number.isInteger(Number(v)) || Number(v) < 0))
115
117
  problems.push(`'reserveOrders.${side}' must be a non-negative integer`);
116
118
  }
@@ -147,7 +149,7 @@ function validateBotEntry(b, i, src) {
147
149
  if (!item.asset || typeof item.asset !== 'string') {
148
150
  problems.push(`debtPolicy.lending[${idx}].asset must be a non-empty string`);
149
151
  }
150
- if (!['mpa', 'creditOffer'].includes(item.type)) {
152
+ if (!['mpa', 'creditOffer'].includes(String(item.type))) {
151
153
  problems.push(`debtPolicy.lending[${idx}].type must be 'mpa' or 'creditOffer'`);
152
154
  }
153
155
  // outputWeight: canonical field (deprecated 'ratio' alias removed)
@@ -156,7 +158,7 @@ function validateBotEntry(b, i, src) {
156
158
  }
157
159
  if ('outputWeight' in item) {
158
160
  const weightVal = item.outputWeight;
159
- if (!Number.isFinite(weightVal) || weightVal < 0) {
161
+ if (typeof weightVal !== 'number' || !Number.isFinite(weightVal) || weightVal < 0) {
160
162
  problems.push(`debtPolicy.lending[${idx}].outputWeight must be a non-negative number`);
161
163
  }
162
164
  }
@@ -285,12 +287,13 @@ function collectValidationIssues(entries, sourceName) {
285
287
  // Cross-bot validation: check if botFunds percentages sum > 100% per account
286
288
  const accountFunds = {};
287
289
  for (const entry of entries) {
288
- if (!entry.active || !entry.preferredAccount || !entry.botFunds)
290
+ const account = entry.preferredAccount;
291
+ if (!entry.active || !account || !entry.botFunds)
289
292
  continue;
290
- if (!accountFunds[entry.preferredAccount]) {
291
- accountFunds[entry.preferredAccount] = { buy: 0, sell: 0, botNames: [] };
293
+ if (!accountFunds[account]) {
294
+ accountFunds[account] = { buy: 0, sell: 0, botNames: [] };
292
295
  }
293
- const acc = accountFunds[entry.preferredAccount];
296
+ const acc = accountFunds[account];
294
297
  acc.buy += toDecimal(entry.botFunds.buy);
295
298
  acc.sell += toDecimal(entry.botFunds.sell);
296
299
  acc.botNames.push(entry.name || entry.botKey || `bot-${entries.indexOf(entry)}`);
@@ -47,7 +47,7 @@
47
47
  * @param {string} targetPath - Path of the final JSON file.
48
48
  * @param {*} data - Anything `JSON.stringify` accepts.
49
49
  */
50
- declare function writeJsonFileAtomic(targetPath: any, data: any): void;
50
+ declare function writeJsonFileAtomic(targetPath: string, data: unknown): void;
51
51
  /**
52
52
  * Safely read bots.json with lock protection (re-entrant safe).
53
53
  * @param {string} botsJsonPath - Path to bots.json file
@@ -55,9 +55,9 @@ declare function writeJsonFileAtomic(targetPath: any, data: any): void;
55
55
  * @returns {Promise<{content: string, config: Object}>} File content and parsed config
56
56
  * @throws {Error} If file doesn't exist or JSON is invalid
57
57
  */
58
- declare function readBotsFileWithLock(botsJsonPath: any, parseFunction: any): Promise<{
58
+ declare function readBotsFileWithLock<T>(botsJsonPath: string, parseFunction: (content: string) => T): Promise<{
59
59
  content: string;
60
- config: any;
60
+ config: T;
61
61
  }>;
62
62
  /**
63
63
  * Safely write bots.json with lock protection (re-entrant safe).
@@ -66,7 +66,7 @@ declare function readBotsFileWithLock(botsJsonPath: any, parseFunction: any): Pr
66
66
  * @returns {Promise<void>}
67
67
  * @throws {Error} If write fails
68
68
  */
69
- declare function writeBotsFileWithLock(botsJsonPath: any, config: any): Promise<void>;
69
+ declare function writeBotsFileWithLock(botsJsonPath: string, config: unknown): Promise<void>;
70
70
  /**
71
71
  * Synchronously read bots.json (startup only, no lock — the in-memory
72
72
  * AsyncLock is inherently async and cannot be used here).
@@ -77,9 +77,9 @@ declare function writeBotsFileWithLock(botsJsonPath: any, config: any): Promise<
77
77
  * @returns {{content: string, config: Object}} File content and parsed config
78
78
  * @throws {Error} If file doesn't exist or JSON is invalid
79
79
  */
80
- declare function readBotsFileSync(botsJsonPath: any, parseFunction: any): {
80
+ declare function readBotsFileSync<T>(botsJsonPath: string, parseFunction: (content: string) => T): {
81
81
  content: string;
82
- config: any;
82
+ config: T;
83
83
  };
84
84
  export { readBotsFileWithLock, writeBotsFileWithLock, readBotsFileSync, writeJsonFileAtomic };
85
85
  //# sourceMappingURL=bots_file_lock.d.ts.map