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
@@ -122,7 +122,7 @@ const GRID_RESYNC_REASONS = Object.freeze({
122
122
  /**
123
123
  * Find a bot entry in the bots config snapshot that matches a runtime config.
124
124
  * Matches by botKey or name.
125
- * @param {any} snapshot - Bots configuration snapshot
125
+ * @param {unknown} snapshot - Bots configuration snapshot
126
126
  * @param {Object} config - Runtime bot configuration
127
127
  * @returns {Object|null} Matched bot entry or null
128
128
  */
@@ -144,7 +144,7 @@ function findSnapshotBotForRuntimeConfig(snapshot, config) {
144
144
  }
145
145
  /**
146
146
  * Check if a runtime bot configuration requires the market adapter.
147
- * @param {any} snapshot - Bots configuration snapshot
147
+ * @param {unknown} snapshot - Bots configuration snapshot
148
148
  * @param {Object} config - Runtime bot configuration
149
149
  * @returns {boolean} True if the bot uses AMA grid pricing
150
150
  */
@@ -174,7 +174,7 @@ const BOT_CONFIG_FINGERPRINT_IGNORED_KEYS = Object.freeze([
174
174
  /**
175
175
  * Deterministic JSON stringify with recursively sorted object keys.
176
176
  * Key order in bots.json must not count as a config change.
177
- * @param {any} value - Value to stringify
177
+ * @param {unknown} value - Value to stringify
178
178
  * @returns {string} Stable string representation
179
179
  */
180
180
  function stableStringifyForBotConfig(value) {
@@ -184,32 +184,34 @@ function stableStringifyForBotConfig(value) {
184
184
  return `[${value.map((v) => stableStringifyForBotConfig(v)).join(',')}]`;
185
185
  }
186
186
  if (typeof value === 'object') {
187
- const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort();
188
- return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringifyForBotConfig(value[k])}`).join(',')}}`;
187
+ const obj = value;
188
+ const keys = Object.keys(obj).filter((k) => obj[k] !== undefined).sort();
189
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringifyForBotConfig(obj[k])}`).join(',')}}`;
189
190
  }
190
191
  const serialized = JSON.stringify(value);
191
192
  return serialized === undefined ? 'null' : serialized;
192
193
  }
193
194
  /**
194
195
  * Normalize a raw bots.json entry for fingerprinting: drop volatile keys.
195
- * @param {any} entry - Raw bot entry from bots.json
196
- * @returns {any} Normalized plain object ({} when entry is missing)
196
+ * @param {unknown} entry - Raw bot entry from bots.json
197
+ * @returns {unknown} Normalized plain object ({} when entry is missing)
197
198
  */
198
199
  function normalizeBotEntryForFingerprint(entry) {
199
200
  if (!entry || typeof entry !== 'object' || Array.isArray(entry))
200
201
  return {};
201
202
  const out = {};
202
- for (const key of Object.keys(entry)) {
203
+ const e = entry;
204
+ for (const key of Object.keys(e)) {
203
205
  if (BOT_CONFIG_FINGERPRINT_IGNORED_KEYS.includes(key))
204
206
  continue;
205
- out[key] = entry[key];
207
+ out[key] = e[key];
206
208
  }
207
209
  return out;
208
210
  }
209
211
  /**
210
212
  * Build the full-entry fingerprint for one bot (stable across key order and
211
213
  * comment/whitespace edits, since those never reach the parsed entry).
212
- * @param {any} entry - Raw bot entry from bots.json
214
+ * @param {unknown} entry - Raw bot entry from bots.json
213
215
  * @returns {string} Fingerprint ('' when entry is missing)
214
216
  */
215
217
  function buildBotConfigFingerprint(entry) {
@@ -221,8 +223,8 @@ function buildBotConfigFingerprint(entry) {
221
223
  * Plain-data deep clone (bots.json entries are JSON-parsed, always
222
224
  * serializable; the fallback only guards exotic test doubles).
223
225
  * Single helper replacing the previously triplicated inline clones.
224
- * @param {any} value - Value to clone
225
- * @returns {any} Deep clone (or the original when unserializable)
226
+ * @param {unknown} value - Value to clone
227
+ * @returns {unknown} Deep clone (or the original when unserializable)
226
228
  */
227
229
  function cloneJsonValue(value) {
228
230
  if (value === undefined)
@@ -241,8 +243,8 @@ function cloneJsonValue(value) {
241
243
  * grid-resync path uses replaceBotConfigFromEntryPreservingRuntime below.
242
244
  * Synchronous in-memory merge only: no chain I/O, no fill-lock (assignments
243
245
  * are atomic; maintenance / targeted-reconcile ticks heal shortfalls/excess).
244
- * @param {any} bot - DEXBot instance
245
- * @param {any} entry - Raw bot entry from bots.json
246
+ * @param {unknown} bot - DEXBot instance
247
+ * @param {unknown} entry - Raw bot entry from bots.json
246
248
  * @param {string[]} keys - Entry keys to merge
247
249
  * @returns {string[]} Merged key names
248
250
  */
@@ -250,19 +252,20 @@ function mergeBotConfigKeysIntoRuntime(bot, entry, keys) {
250
252
  const applied = [];
251
253
  if (!bot?.config || !entry || typeof entry !== 'object')
252
254
  return applied;
255
+ const e = entry;
253
256
  for (const key of keys) {
254
257
  // A deleted key applies as null (mirrors the former ?? null diff
255
258
  // semantics) so the running config can never keep a stale value.
256
259
  // Cloned twice: bot.config and manager.config must never alias the
257
260
  // same nested object, or a future in-place mutation of one would
258
261
  // silently corrupt the other.
259
- const cloned = cloneJsonValue(entry[key] ?? null);
262
+ const cloned = cloneJsonValue(e[key] ?? null);
260
263
  bot.config[key] = cloned;
261
264
  if (bot.manager?.config) {
262
- bot.manager.config[key] = cloneJsonValue(entry[key] ?? null);
265
+ bot.manager.config[key] = cloneJsonValue(e[key] ?? null);
263
266
  }
264
267
  if (key === 'weightDistribution') {
265
- bot._baseWeightDistribution = cloned && typeof cloned === 'object' ? { ...cloned } : cloned;
268
+ bot._baseWeightDistribution = (cloned && typeof cloned === 'object' ? { ...cloned } : cloned);
266
269
  }
267
270
  applied.push(key);
268
271
  }
@@ -273,13 +276,14 @@ function mergeBotConfigKeysIntoRuntime(bot, entry, keys) {
273
276
  * constructor-resolved runtime settings (timing, gridLimits, feeParams,
274
277
  * etc.). Shared single implementation for performGridResync (previously an
275
278
  * inline block duplicating the merge/weights/refresh steps).
276
- * @param {any} bot - DEXBot instance
277
- * @param {any} updatedBot - Raw bot entry from bots.json
279
+ * @param {unknown} bot - DEXBot instance
280
+ * @param {unknown} updatedBot - Raw bot entry from bots.json
278
281
  * @param {string} contextLabel - Label for the weights-refresh log context
279
282
  */
280
283
  function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabel) {
281
284
  const oldKey = bot.config.botKey;
282
285
  const oldIndex = bot.config.botIndex;
286
+ const u = updatedBot;
283
287
  // Preserve runtime-only properties set by the constructor
284
288
  // (timing, gridLimits, feeParams, etc.) that are not present
285
289
  // in the raw profile from bots.json.
@@ -290,7 +294,7 @@ function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabe
290
294
  }
291
295
  }
292
296
  bot._log(`Reloaded configuration for bot '${bot.config.name}'`);
293
- bot.config = { ...updatedBot, botKey: oldKey, botIndex: oldIndex, ...runtimeProps };
297
+ bot.config = { ...u, botKey: oldKey, botIndex: oldIndex, ...runtimeProps };
294
298
  if (bot.manager?.config) {
295
299
  bot.manager.config = { ...bot.manager.config, ...bot.config };
296
300
  }
@@ -300,7 +304,7 @@ function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabe
300
304
  if (bot._creditRuntime) {
301
305
  bot._creditRuntime.config = bot.config;
302
306
  }
303
- bot._baseWeightDistribution = cloneWeightDistribution(updatedBot.weightDistribution, bot._baseWeightDistribution);
307
+ bot._baseWeightDistribution = cloneWeightDistribution(u.weightDistribution, bot._baseWeightDistribution);
304
308
  refreshDynamicWeightDistribution(bot, contextLabel);
305
309
  }
306
310
  /**
@@ -309,7 +313,7 @@ function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabe
309
313
  * bot_settings.ts). Full numeric validation stays where it belongs:
310
314
  * the `dexbot bot` editor at save time and per-offer at runtime.
311
315
  * null/undefined (policy removal) is safe — it takes the disable path.
312
- * @param {any} value - New debtPolicy value from bots.json
316
+ * @param {unknown} value - New debtPolicy value from bots.json
313
317
  * @returns {boolean} True when safe to merge live
314
318
  */
315
319
  function isDebtPolicyLiveApplySafe(value) {
@@ -320,10 +324,14 @@ function isDebtPolicyLiveApplySafe(value) {
320
324
  const lending = value.lending;
321
325
  if (!Array.isArray(lending) || lending.length === 0)
322
326
  return false;
323
- return lending.every((item) => item && typeof item === 'object'
324
- && typeof item.type === 'string' && item.type.length > 0
325
- && typeof item.asset === 'string' && item.asset.length > 0
326
- && typeof item.collateralAsset === 'string' && item.collateralAsset.length > 0);
327
+ return lending.every((item) => {
328
+ if (!item || typeof item !== 'object')
329
+ return false;
330
+ const it = item;
331
+ return typeof it.type === 'string' && it.type.length > 0
332
+ && typeof it.asset === 'string' && it.asset.length > 0
333
+ && typeof it.collateralAsset === 'string' && it.collateralAsset.length > 0;
334
+ });
327
335
  }
328
336
  /**
329
337
  * Reconcile the credit runtime after a live debtPolicy merge: (re)create +
@@ -332,7 +340,7 @@ function isDebtPolicyLiveApplySafe(value) {
332
340
  * an already-loaded runtime and both maintenance entry points bail while
333
341
  * disabled or in-flight, so this is safe on any tick (bot-level seams
334
342
  * guarded for stripped test doubles).
335
- * @param {any} bot - DEXBot instance
343
+ * @param {unknown} bot - DEXBot instance
336
344
  */
337
345
  async function reconcileCreditRuntimeAfterPolicyChange(bot) {
338
346
  try {
@@ -362,13 +370,13 @@ async function reconcileCreditRuntimeAfterPolicyChange(bot) {
362
370
  * Diff two normalized entries in a single pass over the key union.
363
371
  * Replaces the former twin-loop diffLiveBotConfig +
364
372
  * detectNonLiveBotConfigChanges pair.
365
- * @param {any} oldNormalized - Previously seen normalized entry
366
- * @param {any} newNormalized - New normalized entry
373
+ * @param {unknown} oldNormalized - Previously seen normalized entry
374
+ * @param {unknown} newNormalized - New normalized entry
367
375
  * @returns {{liveChanges: Array<{key: string, oldValue: any, newValue: any}>, otherKeys: string[]}} Split changes
368
376
  */
369
377
  function diffBotConfigEntries(oldNormalized, newNormalized) {
370
- const prev = oldNormalized && typeof oldNormalized === 'object' ? oldNormalized : {};
371
- const next = newNormalized && typeof newNormalized === 'object' ? newNormalized : {};
378
+ const prev = (oldNormalized && typeof oldNormalized === 'object' ? oldNormalized : {});
379
+ const next = (newNormalized && typeof newNormalized === 'object' ? newNormalized : {});
372
380
  const liveChanges = [];
373
381
  const otherKeys = [];
374
382
  for (const key of new Set([...Object.keys(prev), ...Object.keys(next)])) {
@@ -402,9 +410,9 @@ function diffBotConfigEntries(oldNormalized, newNormalized) {
402
410
  * the baseline with no hint. Corrupt/unreadable files and missing entries
403
411
  * never touch the stored fingerprint (except the missing-entry hint
404
412
  * throttle) so the next tick re-evaluates.
405
- * @param {any} bot - DEXBot instance
413
+ * @param {unknown} bot - DEXBot instance
406
414
  * @param {string} [context='bots-config poll'] - Context label for logging
407
- * @param {any} [preloadedSnapshot=null] - Reuse an already-loaded snapshot
415
+ * @param {unknown} [preloadedSnapshot=null] - Reuse an already-loaded snapshot
408
416
  * @returns {Promise<any>} Result with applied/liveChanges/otherKeys or skipped
409
417
  */
410
418
  async function checkAndApplyBotConfigChanges(bot, context = 'bots-config poll', preloadedSnapshot = null) {
@@ -497,6 +505,19 @@ async function checkAndApplyBotConfigChanges(bot, context = 'bots-config poll',
497
505
  .join('; ');
498
506
  bot._log?.(`Applied bots.json changes for '${botName}' live during ${context} (no restart needed): ${summary}. ` +
499
507
  `Targeted maintenance will place missing / cancel excess orders.`, 'info');
508
+ // Deliver the promise above instead of waiting for the next fill
509
+ // or the 240-min fetch: run the targeted drift reconciliation
510
+ // right away (same fire-and-forget shape as the poll tick). The
511
+ // callee owns the cooldown; the periodic call site additionally
512
+ // gates on an empty pipeline, which this config-pickup path does
513
+ // not — it retries on the next maintenance tick either way.
514
+ try {
515
+ const driftRun = maybeRunTargetedDriftReconciliation(bot, `${context} config pickup`);
516
+ driftRun?.catch?.((err) => {
517
+ bot._log?.(`[TARGETED-SYNC] Config-pickup reconciliation failed: ${getErrorMessage(err)}`, 'debug');
518
+ });
519
+ }
520
+ catch { /* never break the poll tick */ }
500
521
  }
501
522
  if (otherKeys.length > 0) {
502
523
  const shown = otherKeys.slice(0, 8).join(', ');
@@ -559,9 +580,9 @@ function getTargetActiveOrders(config, side) {
559
580
  * window = bottom slots = floor edge) makes the edge pick land on window
560
581
  * members and the count reads N/N with zero dedicated reserves, so the
561
582
  * deficit never fires (issue #27 follow-up).
562
- * @param {any} manager - OrderManager
563
- * @param {any} config - Bot configuration (reserve count source)
564
- * @param {any} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
583
+ * @param {unknown} manager - OrderManager
584
+ * @param {unknown} config - Bot configuration (reserve count source)
585
+ * @param {unknown} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
565
586
  * @returns {number|null} Live reserve count, or null when unclassifiable
566
587
  */
567
588
  function countLiveReserveOrders(manager, config, type) {
@@ -667,10 +688,12 @@ function getTargetedSyncReason(bot) {
667
688
  if (drift && drift.isValid === false) {
668
689
  return { reason: `fund drift: ${drift.reason}`, targetBuy, targetSell, liveBuy, liveSell, drift };
669
690
  }
670
- // Pure fund-driven spread correction found no free funds on either side.
671
- // The balances may simply be a stale snapshot (fills not yet booked), so
672
- // the only fallback is to refresh account totals + open orders and let the
673
- // next correction cycle re-check. Never recycle resting inventory.
691
+ // Spread correction placed no effective orders: either it found no free
692
+ // funds on either side, or the prepared batch did not execute. The balances
693
+ // or holds may simply be a stale snapshot (the grid does not lose funds, it
694
+ // holds them in resting/virtual slots), so the only fallback is to refresh
695
+ // account totals + open orders and let the next correction cycle re-check.
696
+ // Never recycle resting inventory.
674
697
  if (bot._spreadFundsExhausted === true) {
675
698
  return { reason: 'spread correction had no free funds', targetBuy, targetSell, liveBuy, liveSell, drift };
676
699
  }
@@ -704,6 +727,16 @@ async function maybeRunTargetedDriftReconciliation(bot, context) {
704
727
  bot._warn(`[TARGETED-SYNC] Chain sync failed during ${context}, skipping reconciliation`);
705
728
  return false;
706
729
  }
730
+ // The point of a funds-exhausted trigger is the REFRESH itself: it
731
+ // exists to correct a stale balance/reservation read, not to force a
732
+ // reconcile. Clear the flag now so the re-check below (and the next
733
+ // tick's gate) treats "funds appeared after the refresh" as resolved and
734
+ // only reconciles on a still-concrete signal — fund drift or a counted
735
+ // order shortfall. The spread check later this tick re-derives the flag
736
+ // from fresh state, so a genuinely empty balance re-arms it for the next
737
+ // tick (subject to the cooldown below).
738
+ if (bot._spreadFundsExhausted === true)
739
+ bot._spreadFundsExhausted = false;
707
740
  const remaining = getTargetedSyncReason(bot);
708
741
  const unmatchedCount = Number(syncResult?.unmatchedChainOrders?.length || 0);
709
742
  if (remaining || unmatchedCount > 0) {
@@ -738,7 +771,7 @@ async function maybeRunTargetedDriftReconciliation(bot, context) {
738
771
  * Delegates to the canonical launcher/adapter_requirement helper so the
739
772
  * fingerprint is semantic (AMA-relevant changes only) and identical to the
740
773
  * unlock wrapper watchdog's view of the same file.
741
- * @returns {any} Snapshot with exists flag, fingerprint, active bots list, and adapter requirement
774
+ * @returns {unknown} Snapshot with exists flag, fingerprint, active bots list, and adapter requirement
742
775
  */
743
776
  function loadBotsConfigSnapshot() {
744
777
  return readAdapterRequirement(PROFILES_BOTS_FILE);
@@ -841,9 +874,9 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
841
874
  // fingerprints, retry next tick.
842
875
  let snapshot = null;
843
876
  try {
844
- snapshot = typeof bot._loadBotsConfigSnapshot === 'function'
877
+ snapshot = (typeof bot._loadBotsConfigSnapshot === 'function'
845
878
  ? await bot._loadBotsConfigSnapshot()
846
- : loadBotsConfigSnapshot();
879
+ : loadBotsConfigSnapshot());
847
880
  }
848
881
  catch (err) {
849
882
  bot._warn(`Ignoring unreadable bots.json during ${context}; keeping previous market adapter state.`);
@@ -885,8 +918,9 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
885
918
  // ?? (not ||): the semantic fingerprint is legitimately '' when no
886
919
  // active AMA bot exists, and '' must compare equal to a stored ''.
887
920
  const previousFingerprint = bot._marketAdapterWatchdogFingerprint ?? null;
888
- const changed = snapshot.fingerprint !== previousFingerprint;
889
- bot._marketAdapterWatchdogFingerprint = snapshot.fingerprint;
921
+ const fingerprint = snapshot.fingerprint;
922
+ const changed = fingerprint !== previousFingerprint;
923
+ bot._marketAdapterWatchdogFingerprint = fingerprint;
890
924
  if (changed) {
891
925
  bot._log(`Detected bots.json changes during ${context}; re-evaluating market adapter requirements.`);
892
926
  }
@@ -941,9 +975,10 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
941
975
  }
942
976
  // Cross-reference config-active bots against actually running PM2 processes
943
977
  // so we don't start the adapter for configured AMA bots that aren't running.
978
+ const activeBots = (snapshot.activeBots ?? []);
944
979
  const runningActiveBots = pm2QueryFailed
945
- ? snapshot.activeBots
946
- : snapshot.activeBots.filter((b) => processNames.includes(b.name));
980
+ ? activeBots
981
+ : activeBots.filter((b) => processNames.includes(String(b.name)));
947
982
  const needsAdapterForRunningBots = runningActiveBots.some(usesAmaGridPrice);
948
983
  if (!snapshot.exists || !needsAdapterForRunningBots) {
949
984
  const shouldStop = pm2QueryFailed || processNames.includes(MARKET_ADAPTER_APP_NAME);
@@ -1009,7 +1044,7 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
1009
1044
  * Applies live dynamic weights if the bot is whitelisted and weights are ready.
1010
1045
  * @param {import('./dexbot_class.js').DEXBot} bot
1011
1046
  * @param {string} [context='runtime'] - Context label for logging
1012
- * @returns {any}
1047
+ * @returns {unknown}
1013
1048
  */
1014
1049
  function refreshDynamicWeightDistribution(bot, context = 'runtime') {
1015
1050
  const baseWeights = cloneWeightDistribution(bot._baseWeightDistribution, bot.config?.weightDistribution || bot.manager?.config?.weightDistribution);
@@ -1065,7 +1100,7 @@ function refreshDynamicWeightDistribution(bot, context = 'runtime') {
1065
1100
  * Read and parse a trigger file's metadata payload.
1066
1101
  * Determines whether the trigger originated from the market adapter or was manual.
1067
1102
  * @param {string} triggerFile - Path to the trigger file
1068
- * @returns {any} Parsed trigger metadata
1103
+ * @returns {unknown} Parsed trigger metadata
1069
1104
  */
1070
1105
  function readTriggerMetadata(triggerFile) {
1071
1106
  const manualTriggerMetadata = (payload = null) => ({
@@ -1099,7 +1134,7 @@ function readTriggerMetadata(triggerFile) {
1099
1134
  * Build grid resync metadata from a reason string.
1100
1135
  * Maps known reason strings to structured metadata with refresh flags.
1101
1136
  * @param {string} reason - Resync reason identifier (e.g. 'manual_grid_resync', 'rms_structural_grid_resync')
1102
- * @returns {any}
1137
+ * @returns {unknown}
1103
1138
  */
1104
1139
  function buildGridResyncMetadata(reason) {
1105
1140
  const resetSource = String(reason || '').trim() || 'dexbot_grid_resync';
@@ -1124,12 +1159,12 @@ function buildGridResyncMetadata(reason) {
1124
1159
  /**
1125
1160
  * Build grid resync options from a reason string or metadata object.
1126
1161
  * @param {string|any} reasonOrMetadata - Reason string or metadata object
1127
- * @returns {any}
1162
+ * @returns {unknown}
1128
1163
  */
1129
1164
  function buildGridResyncOptions(reasonOrMetadata) {
1130
- const metadata = typeof reasonOrMetadata === 'string'
1165
+ const metadata = (typeof reasonOrMetadata === 'string'
1131
1166
  ? buildGridResyncMetadata(reasonOrMetadata)
1132
- : reasonOrMetadata;
1167
+ : reasonOrMetadata);
1133
1168
  return {
1134
1169
  refreshCenterPrice: !!metadata?.shouldRefreshCenterPrice,
1135
1170
  centerRefreshContext: metadata?.centerRefreshContext,
@@ -1152,16 +1187,17 @@ function promoteAmaCenterSnapshotForGridReset(botKey) {
1152
1187
  const snapshotPath = path.join(PATHS.ORDERS_DIR, `${botKey}.dynamicgrid.json`);
1153
1188
  try {
1154
1189
  const result = updateDynamicGridSnapshotSync(snapshotPath, (snapshot) => {
1155
- const amaCenterPrice = Number(snapshot?.amaCenterPrice);
1190
+ const snap = snapshot;
1191
+ const amaCenterPrice = Number(snap?.amaCenterPrice);
1156
1192
  if (!Number.isFinite(amaCenterPrice) || amaCenterPrice <= 0) {
1157
1193
  return { ok: false, write: false };
1158
1194
  }
1159
- const currentCenterPrice = Number(snapshot?.gridCenterPrice ?? snapshot?.centerPrice);
1195
+ const currentCenterPrice = Number(snap?.gridCenterPrice ?? snap?.centerPrice);
1160
1196
  if (Number.isFinite(currentCenterPrice) && currentCenterPrice === amaCenterPrice) {
1161
1197
  return { write: false };
1162
1198
  }
1163
1199
  return {
1164
- ...snapshot,
1200
+ ...snap,
1165
1201
  gridCenterPrice: amaCenterPrice,
1166
1202
  centerPrice: amaCenterPrice,
1167
1203
  updatedAt: nowIso(),
@@ -1189,12 +1225,13 @@ function updateBotGridResetMetadata(botKey, options = {}) {
1189
1225
  const snapshotPath = path.join(PATHS.ORDERS_DIR, `${botKey}.dynamicgrid.json`);
1190
1226
  try {
1191
1227
  const result = updateDynamicGridSnapshotSync(snapshotPath, (snapshot) => {
1192
- const gridCenterPrice = Number(snapshot?.gridCenterPrice ?? snapshot?.centerPrice);
1228
+ const snap = snapshot;
1229
+ const gridCenterPrice = Number(snap?.gridCenterPrice ?? snap?.centerPrice);
1193
1230
  if (!Number.isFinite(gridCenterPrice) || gridCenterPrice <= 0) {
1194
1231
  return { ok: false, write: false };
1195
1232
  }
1196
1233
  return {
1197
- ...snapshot,
1234
+ ...snap,
1198
1235
  gridCenterPrice,
1199
1236
  centerPrice: gridCenterPrice,
1200
1237
  lastGridResetAt: resetAt,
@@ -1212,7 +1249,7 @@ function updateBotGridResetMetadata(botKey, options = {}) {
1212
1249
  * Perform a full grid resync: reload config, optionally refresh center price,
1213
1250
  * recalculate the grid, persist, and record reset metadata.
1214
1251
  * @param {import('./dexbot_class.js').DEXBot} bot
1215
- * @param {any} [options] - Grid resync options
1252
+ * @param {unknown} [options] - Grid resync options
1216
1253
  * @param {boolean} [options.skipIdle=false] - Skip the idle-cooldown deferral
1217
1254
  * @returns {Promise<boolean>} True if resync succeeded
1218
1255
  */
@@ -1850,12 +1887,12 @@ function setupBlockchainFetchInterval(bot) {
1850
1887
  // from the window (then re-create them as duplicates).
1851
1888
  // Defer the sync to a clean read; fills are still
1852
1889
  // caught by subscription events and the next cycle.
1853
- chainOpenOrders = (typeof bot._readOpenOrdersHook === 'function')
1890
+ chainOpenOrders = ((typeof bot._readOpenOrdersHook === 'function')
1854
1891
  ? await bot._readOpenOrdersHook()
1855
1892
  : await readOpenOrdersGuarded(chainOrders, bot.accountId, {
1856
1893
  log: (message, level) => bot._log(message, level),
1857
1894
  label: 'PERIODIC-SYNC',
1858
- });
1895
+ }));
1859
1896
  if (chainOpenOrders !== null) {
1860
1897
  const syncResult = await bot.manager.synchronizeWithChain(chainOpenOrders, 'periodicBlockchainFetch');
1861
1898
  if (syncResult.filledOrders && syncResult.filledOrders.length > 0) {
@@ -2039,7 +2076,7 @@ function isOrderDoesNotExistError(message, orderId) {
2039
2076
  * manager._broadcastingStartedAt on every holder, so its age stays small;
2040
2077
  * a frozen timestamp ages past BROADCAST_STALE_CLEAR_MS and we let the tick
2041
2078
  * through so maintenance can hard-reset the flag.
2042
- * @param {any} bot
2079
+ * @param {unknown} bot
2043
2080
  * @returns {boolean} true when the caller should skip this tick
2044
2081
  */
2045
2082
  function shouldDeferMaintenanceForBroadcast(bot) {
@@ -2067,7 +2104,7 @@ function shouldDeferMaintenanceForBroadcast(bot) {
2067
2104
  * any such section visible: when the live hold crosses
2068
2105
  * TIMING.GRID_LOCK_HOLD_WARN_MS it emits a rate-limited warn. Called from the
2069
2106
  * maintenance tick so holds outside a broadcast region are observed too.
2070
- * @param {any} bot
2107
+ * @param {unknown} bot
2071
2108
  * @returns {number} Observed hold duration in ms (0 when not held)
2072
2109
  */
2073
2110
  function checkGridLockHoldDuration(bot) {
@@ -2112,7 +2149,7 @@ function getMaintenanceIdleDelayMs(ctx) {
2112
2149
  : TIMING.BLOCKCHAIN_SETTLE_DELAY_MS;
2113
2150
  if (settleDelayMs <= 0)
2114
2151
  return 0;
2115
- if (ctx?._incomingFillQueue?.length > 0)
2152
+ if ((ctx?._incomingFillQueue?.length ?? 0) > 0)
2116
2153
  return settleDelayMs;
2117
2154
  const lastActivityAt = Number(ctx?._lastGridActivityAt || 0);
2118
2155
  if (!Number.isFinite(lastActivityAt) || lastActivityAt <= 0)
@@ -2138,9 +2175,9 @@ function scheduleMaintenanceAfterIdle(ctx, context, options = {}) {
2138
2175
  ctx._maintenanceIdleTimer = null;
2139
2176
  if (ctx._shuttingDown)
2140
2177
  return;
2141
- ctx._runGridMaintenance(context, timerOptions)
2142
- .catch((err) => {
2143
- ctx._warn(`Deferred ${context} grid maintenance failed: ${getErrorMessage(err)}`);
2178
+ ctx._runGridMaintenance?.(context, timerOptions)
2179
+ ?.catch((err) => {
2180
+ ctx._warn?.(`Deferred ${context} grid maintenance failed: ${getErrorMessage(err)}`);
2144
2181
  if (ctx.manager) {
2145
2182
  ctx.manager._recoveryState = { ...ctx.manager._recoveryState, lastFailureAt: Date.now() };
2146
2183
  }
@@ -2150,7 +2187,7 @@ function scheduleMaintenanceAfterIdle(ctx, context, options = {}) {
2150
2187
  /**
2151
2188
  * Schedule a deferred grid resync after idle delay elapses.
2152
2189
  * @param {Object} ctx - Bot context
2153
- * @param {any} [options] - Grid resync options
2190
+ * @param {unknown} [options] - Grid resync options
2154
2191
  */
2155
2192
  function scheduleDeferredGridResync(ctx, options = {}) {
2156
2193
  if (!ctx ||
@@ -2173,17 +2210,17 @@ function scheduleDeferredGridResync(ctx, options = {}) {
2173
2210
  return;
2174
2211
  if (triggerFileWasPresent && !storage.exists(ctx.triggerFile))
2175
2212
  return;
2176
- ctx.manager._fillProcessingLock.acquire(async () => {
2177
- const ok = await ctx._performGridResync(options);
2213
+ ctx.manager?._fillProcessingLock?.acquire?.(async () => {
2214
+ const ok = await ctx._performGridResync?.(options);
2178
2215
  if (!ok && !ctx._shuttingDown) {
2179
2216
  const curIdleMs = getMaintenanceIdleDelayMs(ctx);
2180
2217
  const reason = curIdleMs > 0
2181
2218
  ? `idle cooldown (${Math.ceil(curIdleMs / TIMING.MILLISECONDS_PER_SECOND)}s)`
2182
2219
  : 'grid resync rejected or failed';
2183
- ctx._warn(`Deferred trigger reset blocked: ${reason}; retaining existing grid state.`);
2220
+ ctx._warn?.(`Deferred trigger reset blocked: ${reason}; retaining existing grid state.`);
2184
2221
  }
2185
- }).catch((err) => {
2186
- ctx._warn(`Deferred trigger reset lock error: ${getErrorMessage(err)}`);
2222
+ })?.catch((err) => {
2223
+ ctx._warn?.(`Deferred trigger reset lock error: ${getErrorMessage(err)}`);
2187
2224
  if (ctx.manager) {
2188
2225
  ctx.manager._recoveryState = { ...ctx.manager._recoveryState, lastFailureAt: Date.now() };
2189
2226
  }
@@ -2466,7 +2503,7 @@ async function executeMaintenanceLogic(bot, context) {
2466
2503
  * dedupe concurrent requests; the re-center moves the boundary, which clears
2467
2504
  * any held-plan signature). Resets whenever the spread heals or a correction
2468
2505
  * places orders.
2469
- * @param {any} bot
2506
+ * @param {unknown} bot
2470
2507
  * @param {boolean} spreadChecked - Whether the spread check ran this tick
2471
2508
  * @param {number} ordersPlaced - Correction orders placed this tick
2472
2509
  * @returns {{staleMs: number, escalated: boolean}}
@@ -2552,9 +2589,9 @@ async function cancelOrderDeferredOnUncertain(bot, order) {
2552
2589
  // Test seam: compiled ESM exports cannot be monkey-patched, so tests
2553
2590
  // may override cancellation through this bot-level hook.
2554
2591
  if (typeof bot._submitCancelOrder === 'function') {
2555
- return await bot._submitCancelOrder(order.orderId);
2592
+ return await bot._submitCancelOrder(String(order.orderId));
2556
2593
  }
2557
- return await chainOrders.cancelOrder(bot.account, bot.privateKey, order.orderId);
2594
+ return await chainOrders.cancelOrder(bot.account, bot.privateKey, String(order.orderId));
2558
2595
  }
2559
2596
  catch (err) {
2560
2597
  if (err instanceof BroadcastUncertainError) {
@@ -2712,7 +2749,7 @@ async function checkBtsBalanceAndAcquire(bot) {
2712
2749
  const minBtsVal = calculateOrderCreationFees(bot.config.assetA, bot.config.assetB, totalTarget, btsReservationMultiplier);
2713
2750
  if (minBtsVal <= 0)
2714
2751
  return;
2715
- const effectiveMin = (bot.config.min_BTS_value > 0) ? bot.config.min_BTS_value : minBtsVal;
2752
+ const effectiveMin = ((bot.config.min_BTS_value ?? 0) > 0) ? bot.config.min_BTS_value : minBtsVal;
2716
2753
  const btsFree = bot.manager.btsBalance.free || 0;
2717
2754
  const btsAcquireThreshold = bot.config?.feeParams?.BTS_ACQUIRE_THRESHOLD;
2718
2755
  const triggerAt = effectiveMin * btsAcquireThreshold;
@@ -3047,14 +3084,14 @@ function wireStructuralGridResyncRequest(bot) {
3047
3084
  bot._recoverySyncInFlight = (bot._recoverySyncInFlight || 0) + 1;
3048
3085
  let resetResult;
3049
3086
  try {
3050
- resetResult = await bot.requestGridReset('rms_structural_grid_resync', {
3087
+ resetResult = await (bot.requestGridReset('rms_structural_grid_resync', {
3051
3088
  refreshCenterPrice: false,
3052
3089
  // Structural resync is a chain-read/rebuild; do not let a
3053
3090
  // fill storm starve it behind the idle cooldown or the
3054
3091
  // fill-processing lock.
3055
3092
  skipIdle: true,
3056
3093
  skipFillLock: true,
3057
- });
3094
+ }));
3058
3095
  }
3059
3096
  finally {
3060
3097
  bot._recoverySyncInFlight = Math.max(0, (bot._recoverySyncInFlight || 0) - 1);
@@ -3203,7 +3240,7 @@ async function syncOpenOrdersAndProcessFillsImpl(bot, tag) {
3203
3240
  return { syncResult: null, aborted: true, hasUnmatched: -1, openOrders: null };
3204
3241
  }
3205
3242
  }
3206
- export { loadBotsConfigSnapshot, isWrapperAdapterOwner, checkAndApplyBotConfigChanges, buildBotConfigFingerprint, refreshDynamicWeightDistribution, performGridResync, updateBotGridResetMetadata, handlePendingTriggerReset, setupTriggerFileDetection, performPeriodicGridChecks, isOpenOrdersSyncLoopEnabled, startOpenOrdersSyncLoop, stopOpenOrdersSyncLoop, setupBlockchainFetchInterval, stopBlockchainFetchInterval, setupBotsConfigPollInterval, stopBotsConfigPollInterval, executeMaintenanceLogic, getTargetedSyncReason, countLiveReserveOrders, cancelDustOrders, isOrderDoesNotExistError, runGridMaintenance, releaseMarketAdapterRuntime, syncMarketAdapterOnPeriodicConfigCheck, usesAmaGridPrice, runDustHealthCheck, setupDustHealthCheckInterval, requestGridReset, wireStructuralGridResyncRequest, getPipelineSignals, markGridActivity, getMetrics, syncOpenOrdersAndProcessFills, shouldDeferMaintenanceForBroadcast, checkGridLockHoldDuration };
3243
+ export { loadBotsConfigSnapshot, isWrapperAdapterOwner, checkAndApplyBotConfigChanges, buildBotConfigFingerprint, refreshDynamicWeightDistribution, performGridResync, updateBotGridResetMetadata, handlePendingTriggerReset, setupTriggerFileDetection, performPeriodicGridChecks, isOpenOrdersSyncLoopEnabled, startOpenOrdersSyncLoop, stopOpenOrdersSyncLoop, setupBlockchainFetchInterval, stopBlockchainFetchInterval, setupBotsConfigPollInterval, stopBotsConfigPollInterval, executeMaintenanceLogic, getTargetedSyncReason, maybeRunTargetedDriftReconciliation, countLiveReserveOrders, cancelDustOrders, isOrderDoesNotExistError, runGridMaintenance, releaseMarketAdapterRuntime, syncMarketAdapterOnPeriodicConfigCheck, usesAmaGridPrice, runDustHealthCheck, setupDustHealthCheckInterval, requestGridReset, wireStructuralGridResyncRequest, getPipelineSignals, markGridActivity, getMetrics, syncOpenOrdersAndProcessFills, shouldDeferMaintenanceForBroadcast, checkGridLockHoldDuration };
3207
3244
  export default {
3208
3245
  loadBotsConfigSnapshot,
3209
3246
  isWrapperAdapterOwner,
@@ -1,28 +1,29 @@
1
1
  /** Startup runtime - bot initialization, grid placement, and startup sequence */
2
+ import type { BotLike } from './types.js';
2
3
  /**
3
4
  * Initialize the startup state: account orders, manager, persisted data.
4
5
  * @param {import('./dexbot_class.js').DEXBot} bot
5
6
  * @returns {Promise<Object>} startupState
6
7
  */
7
- declare function initializeStartupState(bot: any): Promise<{
8
- persistedGrid: any;
9
- persistedBtsFeesOwed: any;
10
- persistedBoundaryIdx: any;
11
- persistedBtsBalance: any;
12
- persistedRecentFillKeys: any;
13
- persistedGenesis: any;
14
- persistedGapEvacStreaks: any;
8
+ declare function initializeStartupState(bot: BotLike): Promise<{
9
+ persistedGrid: unknown[] | null;
10
+ persistedBtsFeesOwed: unknown;
11
+ persistedBoundaryIdx: number | null;
12
+ persistedBtsBalance: unknown;
13
+ persistedRecentFillKeys: unknown;
14
+ persistedGenesis: {} | null;
15
+ persistedGapEvacStreaks: {} | null;
15
16
  }>;
16
17
  /**
17
18
  * Finish the startup sequence: activate fill listener, reconcile grid, place initial orders.
18
19
  * @param {import('./dexbot_class.js').DEXBot} bot
19
20
  * @param {Object} startupState
20
21
  */
21
- declare function finishStartupSequence(bot: any, startupState: any): Promise<void>;
22
+ declare function finishStartupSequence(bot: BotLike, startupState: Awaited<ReturnType<typeof initializeStartupState>>): Promise<void>;
22
23
  /**
23
24
  * Place initial orders on the blockchain (extracted logic from original placeInitialOrders).
24
25
  * @param {import('./dexbot_class.js').DEXBot} bot
25
26
  */
26
- declare function placeInitialOrdersImpl(bot: any): Promise<void>;
27
+ declare function placeInitialOrdersImpl(bot: BotLike): Promise<void>;
27
28
  export { initializeStartupState, finishStartupSequence, placeInitialOrdersImpl };
28
29
  //# sourceMappingURL=dexbot_startup_runtime.d.ts.map