dexbot 1.6.11 → 1.6.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (398) hide show
  1. package/CHANGELOG.md +67 -4
  2. package/README.md +2 -1
  3. package/analysis/README.md +11 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/analysis/tradingview/README.md +1 -1
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
  7. package/claw/README.md +1 -0
  8. package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
  9. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  10. package/claw/modules/chain_broadcast.ts +7 -1
  11. package/claw/modules/claw_bridge.ts +0 -3
  12. package/claw/modules/claw_launcher.ts +1 -1
  13. package/claw/modules/claw_skill_md.ts +1 -0
  14. package/claw/modules/launcher_mode_detector.ts +9 -2
  15. package/claw/package.json +3 -3
  16. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  17. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/account_resolver.d.ts +1 -1
  20. package/dist/analysis/account_resolver.js +2 -1
  21. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  22. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +3 -21
  23. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  24. package/dist/analysis/ama_fitting/fetch_lp_candles.js +55 -45
  25. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -8
  26. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +45 -24
  27. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +34 -78
  28. package/dist/analysis/analyze_args.d.ts +43 -0
  29. package/dist/analysis/analyze_args.js +61 -0
  30. package/dist/analysis/analyze_dynamic_weight.js +7 -17
  31. package/dist/analysis/analyze_kalman.js +7 -17
  32. package/dist/analysis/analyze_regime.js +7 -17
  33. package/dist/analysis/analyze_regime_windows.js +8 -18
  34. package/dist/analysis/analyze_risk_profile.js +8 -18
  35. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  36. package/dist/analysis/analyze_volatility.js +7 -17
  37. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +221 -28
  38. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +23 -103
  39. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  40. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +32 -150
  41. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  42. package/dist/analysis/bot_fitting/shared_utils.d.ts +77 -9
  43. package/dist/analysis/bot_fitting/shared_utils.js +125 -9
  44. package/dist/analysis/bot_key_utils.d.ts +18 -10
  45. package/dist/analysis/bot_key_utils.js +7 -4
  46. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  47. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  48. package/dist/analysis/chain_pool.d.ts +3 -1
  49. package/dist/analysis/chart_ui.d.ts +35 -3
  50. package/dist/analysis/chart_ui.js +43 -4
  51. package/dist/analysis/chart_utils.d.ts +5 -5
  52. package/dist/analysis/chart_utils.js +9 -0
  53. package/dist/analysis/fills_cache.d.ts +4 -24
  54. package/dist/analysis/fills_cache.js +3 -84
  55. package/dist/analysis/fills_source.d.ts +33 -3
  56. package/dist/analysis/fills_source.js +83 -13
  57. package/dist/analysis/grid_correction_check.d.ts +2 -24
  58. package/dist/analysis/grid_correction_check.js +27 -69
  59. package/dist/analysis/math_utils.d.ts +91 -6
  60. package/dist/analysis/math_utils.js +119 -7
  61. package/dist/analysis/pnl_report.js +29 -29
  62. package/dist/analysis/price_sources.d.ts +30 -9
  63. package/dist/analysis/price_sources.js +28 -4
  64. package/dist/analysis/resolve_bot_accounts.js +2 -2
  65. package/dist/analysis/resolve_source.d.ts +1 -1
  66. package/dist/analysis/resolve_source.js +31 -10
  67. package/dist/analysis/trade_profitability.d.ts +29 -2
  68. package/dist/analysis/trade_profitability.js +73 -147
  69. package/dist/analysis/tradingview/analyze_tradingview.d.ts +3 -8
  70. package/dist/analysis/tradingview/analyze_tradingview.js +7 -6
  71. package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
  72. package/dist/analysis/tradingview/grid_reset_config.js +23 -11
  73. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
  74. package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
  75. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  76. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -34
  77. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  78. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +26 -84
  79. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  80. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +16 -41
  81. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
  82. package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
  83. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  84. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  85. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  86. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  87. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  88. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  89. package/dist/analysis/worker_pool.d.ts +38 -0
  90. package/dist/analysis/worker_pool.js +67 -0
  91. package/dist/credential-daemon.js +34 -20
  92. package/dist/dexbot.js +78 -59
  93. package/dist/market_adapter/ama_signal_runner.js +21 -54
  94. package/dist/market_adapter/candle_utils.d.ts +29 -19
  95. package/dist/market_adapter/candle_utils.js +35 -21
  96. package/dist/market_adapter/cli_args.d.ts +22 -0
  97. package/dist/market_adapter/cli_args.js +30 -0
  98. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  99. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  100. package/dist/market_adapter/core/config_normalizers.js +11 -6
  101. package/dist/market_adapter/core/kibana_candles.d.ts +56 -19
  102. package/dist/market_adapter/core/kibana_candles.js +12 -9
  103. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  104. package/dist/market_adapter/core/kibana_client.js +8 -7
  105. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  106. package/dist/market_adapter/core/market_adapter_service.d.ts +320 -153
  107. package/dist/market_adapter/core/market_adapter_service.js +228 -269
  108. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  109. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  110. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  111. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  112. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  113. package/dist/market_adapter/core/strategies/ama.js +2 -4
  114. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  115. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  116. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  117. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  118. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  119. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  120. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
  121. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
  122. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  123. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  124. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  125. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  126. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  127. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  128. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  129. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  130. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  131. package/dist/market_adapter/inputs/fetch_book_data.js +3 -2
  132. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +160 -332
  133. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +50 -8
  134. package/dist/market_adapter/inputs/fetch_lp_data.js +47 -22
  135. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  136. package/dist/market_adapter/inputs/kibana_feed_source.js +26 -41
  137. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  138. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  139. package/dist/market_adapter/inputs/window_cache.d.ts +93 -156
  140. package/dist/market_adapter/inputs/window_cache.js +59 -184
  141. package/dist/market_adapter/interval_utils.d.ts +15 -5
  142. package/dist/market_adapter/interval_utils.js +16 -1
  143. package/dist/market_adapter/log_format.d.ts +6 -6
  144. package/dist/market_adapter/log_format.js +28 -21
  145. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  146. package/dist/market_adapter/lp_chart_core.js +26 -192
  147. package/dist/market_adapter/lp_chart_runner.d.ts +10 -7
  148. package/dist/market_adapter/lp_chart_runner.js +37 -19
  149. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  150. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  151. package/dist/market_adapter/market_adapter.d.ts +94 -32
  152. package/dist/market_adapter/market_adapter.js +94 -120
  153. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  154. package/dist/market_adapter/utils/adapter_client.js +2 -2
  155. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  156. package/dist/market_adapter/utils/chain.d.ts +50 -41
  157. package/dist/market_adapter/utils/chain.js +40 -46
  158. package/dist/market_adapter/utils/data_discovery.d.ts +49 -2
  159. package/dist/market_adapter/utils/data_discovery.js +220 -27
  160. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  161. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  162. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  163. package/dist/market_adapter/utils/file_lock.js +36 -32
  164. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  165. package/dist/market_adapter/utils/month_shards.js +237 -0
  166. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  167. package/dist/market_adapter/utils/native_history.js +35 -28
  168. package/dist/modules/account_bots.d.ts +578 -21
  169. package/dist/modules/account_bots.js +272 -267
  170. package/dist/modules/account_orders.d.ts +79 -30
  171. package/dist/modules/account_orders.js +60 -64
  172. package/dist/modules/authority_resolver.d.ts +12 -2
  173. package/dist/modules/authority_resolver.js +15 -8
  174. package/dist/modules/bitshares-native/chain_client.d.ts +39 -4
  175. package/dist/modules/bitshares-native/chain_client.js +59 -59
  176. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  177. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  178. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  179. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  180. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  181. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  182. package/dist/modules/bitshares-native/index.d.ts +1 -1
  183. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  184. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  185. package/dist/modules/bitshares-native/resolvers.js +22 -25
  186. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  187. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  188. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  189. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  190. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  191. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  192. package/dist/modules/bitshares-native/serial/types.js +73 -108
  193. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  194. package/dist/modules/bitshares-native/signing_client.js +19 -14
  195. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  196. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  197. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  198. package/dist/modules/bitshares-native/transport.js +5 -4
  199. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  200. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  201. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  202. package/dist/modules/bitshares_client.d.ts +45 -13
  203. package/dist/modules/bitshares_client.js +28 -19
  204. package/dist/modules/bot_defaults.d.ts +8 -16
  205. package/dist/modules/bot_defaults.js +1 -5
  206. package/dist/modules/bot_settings.d.ts +44 -10
  207. package/dist/modules/bot_settings.js +11 -8
  208. package/dist/modules/bots_file_lock.d.ts +6 -6
  209. package/dist/modules/bots_file_lock.js +16 -12
  210. package/dist/modules/broadcast_failure.d.ts +4 -3
  211. package/dist/modules/broadcast_failure.js +5 -4
  212. package/dist/modules/chain_keys.d.ts +42 -40
  213. package/dist/modules/chain_keys.js +53 -45
  214. package/dist/modules/chain_orders.d.ts +94 -60
  215. package/dist/modules/chain_orders.js +81 -118
  216. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  217. package/dist/modules/constants.d.ts +534 -32
  218. package/dist/modules/constants.js +35 -48
  219. package/dist/modules/cr_planner.d.ts +41 -3
  220. package/dist/modules/cr_planner.js +1 -5
  221. package/dist/modules/credential_policy.d.ts +68 -8
  222. package/dist/modules/credential_policy.js +37 -31
  223. package/dist/modules/credential_session_cache.d.ts +2 -2
  224. package/dist/modules/credit_pricing.d.ts +43 -6
  225. package/dist/modules/credit_pricing.js +70 -60
  226. package/dist/modules/credit_runtime.d.ts +283 -118
  227. package/dist/modules/credit_runtime.js +500 -231
  228. package/dist/modules/crypto/browser_provider.js +6 -4
  229. package/dist/modules/crypto/node_provider.js +1 -1
  230. package/dist/modules/crypto/pure_scrypt.js +35 -4
  231. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  232. package/dist/modules/crypto/sync.d.ts +9 -9
  233. package/dist/modules/crypto/sync.js +16 -9
  234. package/dist/modules/daemon_node_health.d.ts +4 -3
  235. package/dist/modules/dexbot_class.d.ts +213 -146
  236. package/dist/modules/dexbot_class.js +183 -86
  237. package/dist/modules/dexbot_cow_runtime.d.ts +160 -87
  238. package/dist/modules/dexbot_cow_runtime.js +302 -234
  239. package/dist/modules/dexbot_credential_client.d.ts +19 -18
  240. package/dist/modules/dexbot_credential_client.js +1 -2
  241. package/dist/modules/dexbot_fill_runtime.d.ts +63 -49
  242. package/dist/modules/dexbot_fill_runtime.js +53 -47
  243. package/dist/modules/dexbot_maintenance_runtime.d.ts +127 -71
  244. package/dist/modules/dexbot_maintenance_runtime.js +187 -147
  245. package/dist/modules/dexbot_startup_runtime.d.ts +11 -11
  246. package/dist/modules/dexbot_startup_runtime.js +56 -57
  247. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  248. package/dist/modules/dexbot_state_recovery.js +18 -13
  249. package/dist/modules/fund_registry.d.ts +4 -2
  250. package/dist/modules/fund_registry.js +10 -10
  251. package/dist/modules/general_settings.d.ts +30 -4
  252. package/dist/modules/graceful_shutdown.d.ts +3 -3
  253. package/dist/modules/graceful_shutdown.js +19 -13
  254. package/dist/modules/grid_price_source.d.ts +1 -1
  255. package/dist/modules/key_store.d.ts +14 -8
  256. package/dist/modules/key_store.js +7 -7
  257. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  258. package/dist/modules/launcher/adapter_requirement.js +5 -5
  259. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  260. package/dist/modules/launcher/bot_supervisor.js +12 -11
  261. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  262. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  263. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  264. package/dist/modules/launcher/credential_daemon.js +2 -2
  265. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  266. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  267. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  268. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  269. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  270. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  271. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  272. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  273. package/dist/modules/launcher/supervisor_control.js +4 -2
  274. package/dist/modules/lazy_shim.d.ts +11 -0
  275. package/dist/modules/lazy_shim.js +16 -0
  276. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  277. package/dist/modules/market_adapter_whitelist.js +15 -3
  278. package/dist/modules/node_connect_policy.d.ts +3 -2
  279. package/dist/modules/node_failure_ledger.d.ts +6 -5
  280. package/dist/modules/node_manager.d.ts +41 -11
  281. package/dist/modules/node_manager.js +5 -4
  282. package/dist/modules/order/accounting.d.ts +53 -24
  283. package/dist/modules/order/accounting.js +16 -15
  284. package/dist/modules/order/async_lock.d.ts +5 -2
  285. package/dist/modules/order/async_lock.js +1 -1
  286. package/dist/modules/order/export.d.ts +7 -6
  287. package/dist/modules/order/export.js +1 -7
  288. package/dist/modules/order/format.d.ts +16 -7
  289. package/dist/modules/order/format.js +15 -3
  290. package/dist/modules/order/genesis_policy.d.ts +24 -21
  291. package/dist/modules/order/genesis_policy.js +17 -10
  292. package/dist/modules/order/grid.d.ts +144 -36
  293. package/dist/modules/order/grid.js +226 -145
  294. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  295. package/dist/modules/order/grid_reconcile.js +13 -12
  296. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  297. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  298. package/dist/modules/order/index.d.ts +264 -1
  299. package/dist/modules/order/logger.d.ts +46 -19
  300. package/dist/modules/order/logger.js +38 -49
  301. package/dist/modules/order/logger_state.d.ts +4 -4
  302. package/dist/modules/order/manager.d.ts +232 -191
  303. package/dist/modules/order/manager.js +110 -130
  304. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  305. package/dist/modules/order/processed_fill_store.js +16 -27
  306. package/dist/modules/order/strategy.d.ts +21 -13
  307. package/dist/modules/order/strategy.js +5 -6
  308. package/dist/modules/order/sync_engine.d.ts +91 -33
  309. package/dist/modules/order/sync_engine.js +84 -53
  310. package/dist/modules/order/utils/math.d.ts +157 -102
  311. package/dist/modules/order/utils/math.js +77 -38
  312. package/dist/modules/order/utils/order.d.ts +310 -110
  313. package/dist/modules/order/utils/order.js +153 -126
  314. package/dist/modules/order/utils/slot.d.ts +1 -1
  315. package/dist/modules/order/utils/system.d.ts +156 -26
  316. package/dist/modules/order/utils/system.js +103 -71
  317. package/dist/modules/order/utils/validate.d.ts +89 -41
  318. package/dist/modules/order/utils/validate.js +26 -24
  319. package/dist/modules/order/utils/withPoolRef.d.ts +6 -4
  320. package/dist/modules/order/utils/withPoolRef.js +18 -12
  321. package/dist/modules/order/working_grid.d.ts +14 -13
  322. package/dist/modules/paths.d.ts +1 -4
  323. package/dist/modules/paths.js +33 -61
  324. package/dist/modules/process_discovery.d.ts +1 -1
  325. package/dist/modules/process_discovery.js +2 -1
  326. package/dist/modules/runtime.d.ts +7 -3
  327. package/dist/modules/runtime.js +4 -3
  328. package/dist/modules/runtime_settings.d.ts +14 -11
  329. package/dist/modules/runtime_settings.js +30 -24
  330. package/dist/modules/settings_merge.d.ts +29 -3
  331. package/dist/modules/settings_merge.js +56 -78
  332. package/dist/modules/socket_json_client.d.ts +9 -5
  333. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  334. package/dist/modules/storage/browser_adapter.js +7 -30
  335. package/dist/modules/storage/index.d.ts +1 -1
  336. package/dist/modules/storage/node_adapter.d.ts +45 -27
  337. package/dist/modules/storage/node_adapter.js +9 -9
  338. package/dist/modules/storage/types.d.ts +5 -4
  339. package/dist/modules/types.d.ts +1090 -6
  340. package/dist/modules/types.js +4 -1
  341. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  342. package/dist/modules/utils/asset_symbols.js +2 -1
  343. package/dist/modules/utils/errors.d.ts +9 -0
  344. package/dist/modules/utils/errors.js +24 -4
  345. package/dist/modules/utils/time_range.d.ts +1 -12
  346. package/dist/modules/utils/time_range.js +1 -1
  347. package/dist/modules/validate_profiles.js +53 -43
  348. package/dist/modules/version_notice.d.ts +23 -11
  349. package/dist/modules/version_notice.js +6 -4
  350. package/dist/pm2.d.ts +28 -27
  351. package/dist/pm2.js +61 -40
  352. package/dist/scripts/analyze-credit.d.ts +2 -1
  353. package/dist/scripts/analyze-credit.js +23 -24
  354. package/dist/scripts/analyze-git.js +2 -15
  355. package/dist/scripts/analyze-orders.d.ts +77 -9
  356. package/dist/scripts/analyze-orders.js +65 -40
  357. package/dist/scripts/chart_command.d.ts +27 -18
  358. package/dist/scripts/chart_command.js +15 -13
  359. package/dist/scripts/check_any.d.ts +22 -0
  360. package/dist/scripts/check_any.js +158 -0
  361. package/dist/scripts/diagnose-pool-history.js +13 -13
  362. package/dist/scripts/print_grid.js +0 -1
  363. package/dist/scripts/run-tests.js +39 -8
  364. package/dist/scripts/runner.js +1 -1
  365. package/dist/scripts/sync-version.js +0 -10
  366. package/dist/scripts/test-credit-renewal.js +30 -21
  367. package/dist/scripts/update.d.ts +10 -5
  368. package/dist/scripts/update.js +168 -103
  369. package/dist/scripts/update_dist_freshness.js +1 -0
  370. package/dist/scripts/update_layout.d.ts +61 -0
  371. package/dist/scripts/update_layout.js +180 -0
  372. package/dist/scripts/validate_bots.js +2 -1
  373. package/dist/scripts/verify-browser-bundle.js +8 -0
  374. package/dist/unlock.d.ts +28 -3
  375. package/dist/unlock.js +63 -35
  376. package/docs/BITSHARES_ONBOARDING.md +10 -12
  377. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -2
  378. package/docs/COW_INVARIANTS.md +13 -6
  379. package/docs/DEXBOT_COMPARISON.md +8 -8
  380. package/docs/EVOLUTION.md +10 -8
  381. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  382. package/docs/GRID_RECALCULATION.md +4 -2
  383. package/docs/GRID_RECONCILE.md +14 -3
  384. package/docs/LIFECYCLE.md +11 -11
  385. package/docs/MPA_CREDIT_USAGE.md +22 -3
  386. package/docs/README.md +14 -3
  387. package/docs/WORKFLOW.md +1 -0
  388. package/docs/architecture.md +31 -19
  389. package/docs/developer_guide.md +6 -6
  390. package/market_adapter/README.md +12 -5
  391. package/modules/README.md +4 -1
  392. package/package.json +9 -9
  393. package/scripts/README.md +43 -38
  394. package/tests/README.md +25 -10
  395. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  396. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  397. package/scripts/git-viewer.sh +0 -489
  398. package/scripts/postinstall.js +0 -16
@@ -5,9 +5,10 @@ import { dirname as _esmDirname } from 'node:path';
5
5
  const __filename = fileURLToPath(import.meta.url);
6
6
  const __dirname = _esmDirname(__filename);
7
7
  const require = createRequire(import.meta.url);
8
+ import { lazyShim } from './lazy_shim.js';
8
9
  import fs from 'node:fs';
9
10
  import { spawn } from 'node:child_process';
10
- import { nowIso } from './order/utils/system.js';
11
+ import { nowIso, fireStructuralResync } from './order/utils/system.js';
11
12
  import { path } from './path_api.js';
12
13
  import * as chainOrders from './chain_orders.js';
13
14
  import * as grid from './order/grid.js';
@@ -29,48 +30,48 @@ const { Config } = configModule;
29
30
  import { getErrorMessage } from './utils/errors.js';
30
31
  import { isSameBotName } from './utils/sanitize_key.js';
31
32
  import { usesAmaGridPrice } from './grid_price_source.js';
32
- function hasOpenOrdersSyncLoopMsSet(...args) { return require('./config').hasOpenOrdersSyncLoopMsSet(...args); }
33
- function getOpenOrdersSyncLoopMs(...args) { return require('./config').getOpenOrdersSyncLoopMs(...args); }
33
+ const hasOpenOrdersSyncLoopMsSet = lazyShim('./config', 'hasOpenOrdersSyncLoopMsSet');
34
+ const getOpenOrdersSyncLoopMs = lazyShim('./config', 'getOpenOrdersSyncLoopMs');
34
35
  function isGridBloated(...args) { return grid.isGridBloated(...args); }
35
36
  function isGridBloatGraceActive(...args) { return grid.isGridBloatGraceActive(...args); }
36
37
  function clearGridBloatFlag(...args) { return grid.clearGridBloatFlag(...args); }
37
38
  function recalculateGrid(...args) { return grid.recalculateGrid(...args); }
38
- function buildRuntimeScriptPath(...args) { return require('./launcher/runtime_entry').buildRuntimeScriptPath(...args); }
39
- function applyGridDivergenceCorrections(...args) { return require('./order/utils/system').applyGridDivergenceCorrections(...args); }
40
- function updateGridFromBlockchainSnapshot(...args) { return require('./order/grid').updateGridFromBlockchainSnapshot(...args); }
41
- function loadAmaCenterSnapshot(...args) { return require('./order/utils/system').loadAmaCenterSnapshot(...args); }
42
- function sleep(...args) { return require('./order/utils/system').sleep(...args); }
43
- function parseJsonWithComments(...args) { return require('./order/utils/system').parseJsonWithComments(...args); }
44
- function isPm2Runtime(...args) { return require('./order/logger').isPm2Runtime(...args); }
45
- function isWrapperAdapterOwner(...args) { return require('./launcher/adapter_requirement').isWrapperAdapterOwner(...args); }
46
- function readAdapterRequirement(...args) { return require('./launcher/adapter_requirement').readAdapterRequirement(...args); }
47
- function getSharedMarketAdapterRuntime(...args) { return require('./launcher/market_adapter_runtime').getSharedMarketAdapterRuntime(...args); }
48
- function resetMarketAdapterWhitelistCache(...args) { return require('./market_adapter_whitelist').resetMarketAdapterWhitelistCache(...args); }
49
- function isBotDynamicWeightWhitelisted(...args) { return require('./market_adapter_whitelist').isBotDynamicWeightWhitelisted(...args); }
39
+ const buildRuntimeScriptPath = lazyShim('./launcher/runtime_entry', 'buildRuntimeScriptPath');
40
+ const applyGridDivergenceCorrections = lazyShim('./order/utils/system', 'applyGridDivergenceCorrections');
41
+ const updateGridFromBlockchainSnapshot = lazyShim('./order/grid', 'updateGridFromBlockchainSnapshot');
42
+ const loadAmaCenterSnapshot = lazyShim('./order/utils/system', 'loadAmaCenterSnapshot');
43
+ const sleep = lazyShim('./order/utils/system', 'sleep');
44
+ const parseJsonWithComments = lazyShim('./order/utils/system', 'parseJsonWithComments');
45
+ const isPm2Runtime = lazyShim('./order/logger', 'isPm2Runtime');
46
+ const isWrapperAdapterOwner = lazyShim('./launcher/adapter_requirement', 'isWrapperAdapterOwner');
47
+ const readAdapterRequirement = lazyShim('./launcher/adapter_requirement', 'readAdapterRequirement');
48
+ const getSharedMarketAdapterRuntime = lazyShim('./launcher/market_adapter_runtime', 'getSharedMarketAdapterRuntime');
49
+ const resetMarketAdapterWhitelistCache = lazyShim('./market_adapter_whitelist', 'resetMarketAdapterWhitelistCache');
50
+ const isBotDynamicWeightWhitelisted = lazyShim('./market_adapter_whitelist', 'isBotDynamicWeightWhitelisted');
50
51
  function getRuntimeSettingsKeys() { return require('./runtime_settings').RUNTIME_SETTINGS_KEYS; }
51
- function cloneWeightDistribution(...args) { return require('./order/utils/math').cloneWeightDistribution(...args); }
52
- function calculateOrderCreationFees(...args) { return require('./order/utils/math').calculateOrderCreationFees(...args); }
53
- function calculateSwapInAmount(...args) { return require('./order/utils/math').calculateSwapInAmount(...args); }
54
- function floatToBlockchainInt(...args) { return require('./order/utils/math').floatToBlockchainInt(...args); }
55
- function blockchainToFloat(...args) { return require('./order/utils/math').blockchainToFloat(...args); }
56
- function updateDynamicGridSnapshotSync(...args) { return require('../market_adapter/utils/dynamic_grid_snapshot').updateDynamicGridSnapshotSync(...args); }
52
+ const cloneWeightDistribution = lazyShim('./order/utils/math', 'cloneWeightDistribution');
53
+ const calculateOrderCreationFees = lazyShim('./order/utils/math', 'calculateOrderCreationFees');
54
+ const calculateSwapInAmount = lazyShim('./order/utils/math', 'calculateSwapInAmount');
55
+ const floatToBlockchainInt = lazyShim('./order/utils/math', 'floatToBlockchainInt');
56
+ const blockchainToFloat = lazyShim('./order/utils/math', 'blockchainToFloat');
57
+ const updateDynamicGridSnapshotSync = lazyShim('../market_adapter/utils/dynamic_grid_snapshot', 'updateDynamicGridSnapshotSync');
57
58
  // Lazy require: dexbot_fill_runtime imports this module, so a static import
58
59
  // would be circular; at call time both modules are fully loaded.
59
- function scheduleFillConsumerRestartFn(...args) { return require('./dexbot_fill_runtime').scheduleFillConsumerRestart(...args); }
60
- function reconcileGridOrders(...args) { return require('./order/grid_reconcile').reconcileGridOrders(...args); }
61
- function resolveReserveCount(...args) { return require('./order/utils/order').resolveReserveCount(...args); }
62
- function reserveEdgeIdSet(...args) { return require('./order/utils/order').reserveEdgeIdSet(...args); }
63
- function liveWindowIdSet(...args) { return require('./order/utils/order').liveWindowIdSet(...args); }
64
- function resolveLiveReserveEdgeAnchorPrice(...args) { return require('./order/utils/order').resolveLiveReserveEdgeAnchorPrice(...args); }
65
- function formatUnmatchedChainOrder(...args) { return require('./order/utils/order').formatUnmatchedChainOrder(...args); }
66
- function isNonBlockingUnmatchedOrder(...args) { return require('./order/utils/order').isNonBlockingUnmatchedOrder(...args); }
67
- function isStrandedHoldOrder(...args) { return require('./order/utils/order').isStrandedHoldOrder(...args); }
68
- function getSideBudget(...args) { return require('./order/utils/order').getSideBudget(...args); }
60
+ const scheduleFillConsumerRestartFn = lazyShim('./dexbot_fill_runtime', 'scheduleFillConsumerRestart');
61
+ const reconcileGridOrders = lazyShim('./order/grid_reconcile', 'reconcileGridOrders');
62
+ const resolveReserveCount = lazyShim('./order/utils/order', 'resolveReserveCount');
63
+ const reserveEdgeIdSet = lazyShim('./order/utils/order', 'reserveEdgeIdSet');
64
+ const liveWindowIdSet = lazyShim('./order/utils/order', 'liveWindowIdSet');
65
+ const resolveLiveReserveEdgeAnchorPrice = lazyShim('./order/utils/order', 'resolveLiveReserveEdgeAnchorPrice');
66
+ const formatUnmatchedChainOrder = lazyShim('./order/utils/order', 'formatUnmatchedChainOrder');
67
+ const isNonBlockingUnmatchedOrder = lazyShim('./order/utils/order', 'isNonBlockingUnmatchedOrder');
68
+ const isStrandedHoldOrder = lazyShim('./order/utils/order', 'isStrandedHoldOrder');
69
+ const getSideBudget = lazyShim('./order/utils/order', 'getSideBudget');
69
70
  function getActiveOrdersTotal(config) { return require('./order/utils/order').getActiveOrdersTotal(config); }
70
- function correctAllPriceMismatches(...args) { return require('./order/utils/order').correctAllPriceMismatches(...args); }
71
- function isOrderOnChain(...args) { return require('./order/utils/order').isOrderOnChain(...args); }
72
- function parseChainOrder(...args) { return require('./order/utils/order').parseChainOrder(...args); }
73
- function parseSlotIndex(...args) { return require('./order/utils/order').parseSlotIndex(...args); }
71
+ const correctAllPriceMismatches = lazyShim('./order/utils/order', 'correctAllPriceMismatches');
72
+ const isOrderOnChain = lazyShim('./order/utils/order', 'isOrderOnChain');
73
+ const parseChainOrder = lazyShim('./order/utils/order', 'parseChainOrder');
74
+ const parseSlotIndex = lazyShim('./order/utils/order', 'parseSlotIndex');
74
75
  const CODE_ROOT = path.join(__dirname, '..');
75
76
  const PROFILES_DIR = PATHS.PROFILES_DIR;
76
77
  const PROFILES_BOTS_FILE = PATHS.PROFILES.BOTS_JSON;
@@ -122,7 +123,7 @@ const GRID_RESYNC_REASONS = Object.freeze({
122
123
  /**
123
124
  * Find a bot entry in the bots config snapshot that matches a runtime config.
124
125
  * Matches by botKey or name.
125
- * @param {any} snapshot - Bots configuration snapshot
126
+ * @param {unknown} snapshot - Bots configuration snapshot
126
127
  * @param {Object} config - Runtime bot configuration
127
128
  * @returns {Object|null} Matched bot entry or null
128
129
  */
@@ -144,7 +145,7 @@ function findSnapshotBotForRuntimeConfig(snapshot, config) {
144
145
  }
145
146
  /**
146
147
  * Check if a runtime bot configuration requires the market adapter.
147
- * @param {any} snapshot - Bots configuration snapshot
148
+ * @param {unknown} snapshot - Bots configuration snapshot
148
149
  * @param {Object} config - Runtime bot configuration
149
150
  * @returns {boolean} True if the bot uses AMA grid pricing
150
151
  */
@@ -174,7 +175,7 @@ const BOT_CONFIG_FINGERPRINT_IGNORED_KEYS = Object.freeze([
174
175
  /**
175
176
  * Deterministic JSON stringify with recursively sorted object keys.
176
177
  * Key order in bots.json must not count as a config change.
177
- * @param {any} value - Value to stringify
178
+ * @param {unknown} value - Value to stringify
178
179
  * @returns {string} Stable string representation
179
180
  */
180
181
  function stableStringifyForBotConfig(value) {
@@ -184,32 +185,34 @@ function stableStringifyForBotConfig(value) {
184
185
  return `[${value.map((v) => stableStringifyForBotConfig(v)).join(',')}]`;
185
186
  }
186
187
  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(',')}}`;
188
+ const obj = value;
189
+ const keys = Object.keys(obj).filter((k) => obj[k] !== undefined).sort();
190
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringifyForBotConfig(obj[k])}`).join(',')}}`;
189
191
  }
190
192
  const serialized = JSON.stringify(value);
191
193
  return serialized === undefined ? 'null' : serialized;
192
194
  }
193
195
  /**
194
196
  * 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)
197
+ * @param {unknown} entry - Raw bot entry from bots.json
198
+ * @returns {unknown} Normalized plain object ({} when entry is missing)
197
199
  */
198
200
  function normalizeBotEntryForFingerprint(entry) {
199
201
  if (!entry || typeof entry !== 'object' || Array.isArray(entry))
200
202
  return {};
201
203
  const out = {};
202
- for (const key of Object.keys(entry)) {
204
+ const e = entry;
205
+ for (const key of Object.keys(e)) {
203
206
  if (BOT_CONFIG_FINGERPRINT_IGNORED_KEYS.includes(key))
204
207
  continue;
205
- out[key] = entry[key];
208
+ out[key] = e[key];
206
209
  }
207
210
  return out;
208
211
  }
209
212
  /**
210
213
  * Build the full-entry fingerprint for one bot (stable across key order and
211
214
  * comment/whitespace edits, since those never reach the parsed entry).
212
- * @param {any} entry - Raw bot entry from bots.json
215
+ * @param {unknown} entry - Raw bot entry from bots.json
213
216
  * @returns {string} Fingerprint ('' when entry is missing)
214
217
  */
215
218
  function buildBotConfigFingerprint(entry) {
@@ -221,8 +224,8 @@ function buildBotConfigFingerprint(entry) {
221
224
  * Plain-data deep clone (bots.json entries are JSON-parsed, always
222
225
  * serializable; the fallback only guards exotic test doubles).
223
226
  * 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)
227
+ * @param {unknown} value - Value to clone
228
+ * @returns {unknown} Deep clone (or the original when unserializable)
226
229
  */
227
230
  function cloneJsonValue(value) {
228
231
  if (value === undefined)
@@ -241,8 +244,8 @@ function cloneJsonValue(value) {
241
244
  * grid-resync path uses replaceBotConfigFromEntryPreservingRuntime below.
242
245
  * Synchronous in-memory merge only: no chain I/O, no fill-lock (assignments
243
246
  * 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
247
+ * @param {unknown} bot - DEXBot instance
248
+ * @param {unknown} entry - Raw bot entry from bots.json
246
249
  * @param {string[]} keys - Entry keys to merge
247
250
  * @returns {string[]} Merged key names
248
251
  */
@@ -250,19 +253,20 @@ function mergeBotConfigKeysIntoRuntime(bot, entry, keys) {
250
253
  const applied = [];
251
254
  if (!bot?.config || !entry || typeof entry !== 'object')
252
255
  return applied;
256
+ const e = entry;
253
257
  for (const key of keys) {
254
258
  // A deleted key applies as null (mirrors the former ?? null diff
255
259
  // semantics) so the running config can never keep a stale value.
256
260
  // Cloned twice: bot.config and manager.config must never alias the
257
261
  // same nested object, or a future in-place mutation of one would
258
262
  // silently corrupt the other.
259
- const cloned = cloneJsonValue(entry[key] ?? null);
263
+ const cloned = cloneJsonValue(e[key] ?? null);
260
264
  bot.config[key] = cloned;
261
265
  if (bot.manager?.config) {
262
- bot.manager.config[key] = cloneJsonValue(entry[key] ?? null);
266
+ bot.manager.config[key] = cloneJsonValue(e[key] ?? null);
263
267
  }
264
268
  if (key === 'weightDistribution') {
265
- bot._baseWeightDistribution = cloned && typeof cloned === 'object' ? { ...cloned } : cloned;
269
+ bot._baseWeightDistribution = (cloned && typeof cloned === 'object' ? { ...cloned } : cloned);
266
270
  }
267
271
  applied.push(key);
268
272
  }
@@ -273,13 +277,14 @@ function mergeBotConfigKeysIntoRuntime(bot, entry, keys) {
273
277
  * constructor-resolved runtime settings (timing, gridLimits, feeParams,
274
278
  * etc.). Shared single implementation for performGridResync (previously an
275
279
  * inline block duplicating the merge/weights/refresh steps).
276
- * @param {any} bot - DEXBot instance
277
- * @param {any} updatedBot - Raw bot entry from bots.json
280
+ * @param {unknown} bot - DEXBot instance
281
+ * @param {unknown} updatedBot - Raw bot entry from bots.json
278
282
  * @param {string} contextLabel - Label for the weights-refresh log context
279
283
  */
280
284
  function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabel) {
281
285
  const oldKey = bot.config.botKey;
282
286
  const oldIndex = bot.config.botIndex;
287
+ const u = updatedBot;
283
288
  // Preserve runtime-only properties set by the constructor
284
289
  // (timing, gridLimits, feeParams, etc.) that are not present
285
290
  // in the raw profile from bots.json.
@@ -290,7 +295,7 @@ function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabe
290
295
  }
291
296
  }
292
297
  bot._log(`Reloaded configuration for bot '${bot.config.name}'`);
293
- bot.config = { ...updatedBot, botKey: oldKey, botIndex: oldIndex, ...runtimeProps };
298
+ bot.config = { ...u, botKey: oldKey, botIndex: oldIndex, ...runtimeProps };
294
299
  if (bot.manager?.config) {
295
300
  bot.manager.config = { ...bot.manager.config, ...bot.config };
296
301
  }
@@ -300,7 +305,7 @@ function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabe
300
305
  if (bot._creditRuntime) {
301
306
  bot._creditRuntime.config = bot.config;
302
307
  }
303
- bot._baseWeightDistribution = cloneWeightDistribution(updatedBot.weightDistribution, bot._baseWeightDistribution);
308
+ bot._baseWeightDistribution = cloneWeightDistribution(u.weightDistribution, bot._baseWeightDistribution);
304
309
  refreshDynamicWeightDistribution(bot, contextLabel);
305
310
  }
306
311
  /**
@@ -309,7 +314,7 @@ function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabe
309
314
  * bot_settings.ts). Full numeric validation stays where it belongs:
310
315
  * the `dexbot bot` editor at save time and per-offer at runtime.
311
316
  * null/undefined (policy removal) is safe — it takes the disable path.
312
- * @param {any} value - New debtPolicy value from bots.json
317
+ * @param {unknown} value - New debtPolicy value from bots.json
313
318
  * @returns {boolean} True when safe to merge live
314
319
  */
315
320
  function isDebtPolicyLiveApplySafe(value) {
@@ -320,10 +325,14 @@ function isDebtPolicyLiveApplySafe(value) {
320
325
  const lending = value.lending;
321
326
  if (!Array.isArray(lending) || lending.length === 0)
322
327
  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);
328
+ return lending.every((item) => {
329
+ if (!item || typeof item !== 'object')
330
+ return false;
331
+ const it = item;
332
+ return typeof it.type === 'string' && it.type.length > 0
333
+ && typeof it.asset === 'string' && it.asset.length > 0
334
+ && typeof it.collateralAsset === 'string' && it.collateralAsset.length > 0;
335
+ });
327
336
  }
328
337
  /**
329
338
  * Reconcile the credit runtime after a live debtPolicy merge: (re)create +
@@ -332,7 +341,7 @@ function isDebtPolicyLiveApplySafe(value) {
332
341
  * an already-loaded runtime and both maintenance entry points bail while
333
342
  * disabled or in-flight, so this is safe on any tick (bot-level seams
334
343
  * guarded for stripped test doubles).
335
- * @param {any} bot - DEXBot instance
344
+ * @param {unknown} bot - DEXBot instance
336
345
  */
337
346
  async function reconcileCreditRuntimeAfterPolicyChange(bot) {
338
347
  try {
@@ -362,13 +371,13 @@ async function reconcileCreditRuntimeAfterPolicyChange(bot) {
362
371
  * Diff two normalized entries in a single pass over the key union.
363
372
  * Replaces the former twin-loop diffLiveBotConfig +
364
373
  * detectNonLiveBotConfigChanges pair.
365
- * @param {any} oldNormalized - Previously seen normalized entry
366
- * @param {any} newNormalized - New normalized entry
374
+ * @param {unknown} oldNormalized - Previously seen normalized entry
375
+ * @param {unknown} newNormalized - New normalized entry
367
376
  * @returns {{liveChanges: Array<{key: string, oldValue: any, newValue: any}>, otherKeys: string[]}} Split changes
368
377
  */
369
378
  function diffBotConfigEntries(oldNormalized, newNormalized) {
370
- const prev = oldNormalized && typeof oldNormalized === 'object' ? oldNormalized : {};
371
- const next = newNormalized && typeof newNormalized === 'object' ? newNormalized : {};
379
+ const prev = (oldNormalized && typeof oldNormalized === 'object' ? oldNormalized : {});
380
+ const next = (newNormalized && typeof newNormalized === 'object' ? newNormalized : {});
372
381
  const liveChanges = [];
373
382
  const otherKeys = [];
374
383
  for (const key of new Set([...Object.keys(prev), ...Object.keys(next)])) {
@@ -402,9 +411,9 @@ function diffBotConfigEntries(oldNormalized, newNormalized) {
402
411
  * the baseline with no hint. Corrupt/unreadable files and missing entries
403
412
  * never touch the stored fingerprint (except the missing-entry hint
404
413
  * throttle) so the next tick re-evaluates.
405
- * @param {any} bot - DEXBot instance
414
+ * @param {unknown} bot - DEXBot instance
406
415
  * @param {string} [context='bots-config poll'] - Context label for logging
407
- * @param {any} [preloadedSnapshot=null] - Reuse an already-loaded snapshot
416
+ * @param {unknown} [preloadedSnapshot=null] - Reuse an already-loaded snapshot
408
417
  * @returns {Promise<any>} Result with applied/liveChanges/otherKeys or skipped
409
418
  */
410
419
  async function checkAndApplyBotConfigChanges(bot, context = 'bots-config poll', preloadedSnapshot = null) {
@@ -499,9 +508,10 @@ async function checkAndApplyBotConfigChanges(bot, context = 'bots-config poll',
499
508
  `Targeted maintenance will place missing / cancel excess orders.`, 'info');
500
509
  // Deliver the promise above instead of waiting for the next fill
501
510
  // or the 240-min fetch: run the targeted drift reconciliation
502
- // right away (same fire-and-forget shape as the poll tick — the
503
- // callee owns its cooldown and pipeline gates, so a busy pipeline
504
- // skips and the next maintenance tick retries).
511
+ // right away (same fire-and-forget shape as the poll tick). The
512
+ // callee owns the cooldown; the periodic call site additionally
513
+ // gates on an empty pipeline, which this config-pickup path does
514
+ // not — it retries on the next maintenance tick either way.
505
515
  try {
506
516
  const driftRun = maybeRunTargetedDriftReconciliation(bot, `${context} config pickup`);
507
517
  driftRun?.catch?.((err) => {
@@ -571,9 +581,9 @@ function getTargetActiveOrders(config, side) {
571
581
  * window = bottom slots = floor edge) makes the edge pick land on window
572
582
  * members and the count reads N/N with zero dedicated reserves, so the
573
583
  * deficit never fires (issue #27 follow-up).
574
- * @param {any} manager - OrderManager
575
- * @param {any} config - Bot configuration (reserve count source)
576
- * @param {any} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
584
+ * @param {unknown} manager - OrderManager
585
+ * @param {unknown} config - Bot configuration (reserve count source)
586
+ * @param {unknown} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
577
587
  * @returns {number|null} Live reserve count, or null when unclassifiable
578
588
  */
579
589
  function countLiveReserveOrders(manager, config, type) {
@@ -642,6 +652,25 @@ function _hasBudgetForSide(manager, config, side) {
642
652
  return true;
643
653
  }
644
654
  }
655
+ /**
656
+ * Mirror a spread-check stall into the flags the targeted-sync gate reads.
657
+ *
658
+ * ANY stall — fund, batch, or structural — arms the refresh. When the
659
+ * correction cannot act on the local snapshot, that snapshot may simply be
660
+ * stale relative to the chain: a missed fill leaves an ACTIVE slot occupying
661
+ * the window edge, so `isSlotAvailable` hides every tightening slot and the
662
+ * check reports 'no-candidates' even though real geometry exists. A refresh is
663
+ * the only way to tell a genuinely structural stall from a stale one, so we
664
+ * sync rather than wait for the out-of-spread staleness watchdog to re-center.
665
+ * The stall cause is kept alongside the flag so the log states the truth.
666
+ * Exported for tests.
667
+ * @param {BotLike} bot
668
+ * @param {SpreadCorrectionStall|null|undefined} stall
669
+ */
670
+ export function mirrorSpreadStall(bot, stall) {
671
+ bot._spreadCorrectionStall = stall ?? null;
672
+ bot._spreadFundsExhausted = stall != null;
673
+ }
645
674
  function getTargetedSyncReason(bot) {
646
675
  if (!bot.manager || bot.config?.dryRun)
647
676
  return null;
@@ -679,12 +708,18 @@ function getTargetedSyncReason(bot) {
679
708
  if (drift && drift.isValid === false) {
680
709
  return { reason: `fund drift: ${drift.reason}`, targetBuy, targetSell, liveBuy, liveSell, drift };
681
710
  }
682
- // Pure fund-driven spread correction found no free funds on either side.
683
- // The balances may simply be a stale snapshot (fills not yet booked), so
684
- // the only fallback is to refresh account totals + open orders and let the
685
- // next correction cycle re-check. Never recycle resting inventory.
711
+ // Spread correction placed no effective order for ANY cause. The local
712
+ // snapshot the check reasoned over may be stale relative to the chain —
713
+ // balances/holds can be a stale read (the grid does not lose funds, it
714
+ // holds them in resting/virtual slots), and a missed fill can leave an
715
+ // ACTIVE slot occupying the window edge so no tightening slot appears to
716
+ // exist ('no-candidates'). Only a chain sync can tell a genuinely
717
+ // structural stall from a stale one, so arm the refresh for every cause
718
+ // instead of waiting up to SPREAD_STALE_ESCALATE_MS for the watchdog.
719
+ // Never recycle resting inventory.
686
720
  if (bot._spreadFundsExhausted === true) {
687
- return { reason: 'spread correction had no free funds', targetBuy, targetSell, liveBuy, liveSell, drift };
721
+ const cause = bot._spreadCorrectionStall || 'funds-exhausted';
722
+ return { reason: `spread correction stalled (${cause})`, targetBuy, targetSell, liveBuy, liveSell, drift };
688
723
  }
689
724
  if (shortfalls.length > 0) {
690
725
  return { reason: `active order shortfall: ${shortfalls.join(', ')}`, targetBuy, targetSell, liveBuy, liveSell, drift };
@@ -716,6 +751,19 @@ async function maybeRunTargetedDriftReconciliation(bot, context) {
716
751
  bot._warn(`[TARGETED-SYNC] Chain sync failed during ${context}, skipping reconciliation`);
717
752
  return false;
718
753
  }
754
+ // The point of a funds-exhausted trigger is the REFRESH itself: it
755
+ // exists to correct a stale balance/reservation read, not to force a
756
+ // reconcile. Clear the flag now so the re-check below (and the next
757
+ // tick's gate) treats "funds appeared after the refresh" as resolved and
758
+ // only reconciles on a still-concrete signal — fund drift or a counted
759
+ // order shortfall. The spread check later this tick re-derives the flag
760
+ // from fresh state, so a genuinely empty balance re-arms it for the next
761
+ // tick (subject to the cooldown below).
762
+ if (bot._spreadFundsExhausted === true)
763
+ bot._spreadFundsExhausted = false;
764
+ // Clear the companion cause with the flag so the two never drift apart
765
+ // (a leftover cause would mislabel the next tick's reason).
766
+ bot._spreadCorrectionStall = null;
719
767
  const remaining = getTargetedSyncReason(bot);
720
768
  const unmatchedCount = Number(syncResult?.unmatchedChainOrders?.length || 0);
721
769
  if (remaining || unmatchedCount > 0) {
@@ -750,7 +798,7 @@ async function maybeRunTargetedDriftReconciliation(bot, context) {
750
798
  * Delegates to the canonical launcher/adapter_requirement helper so the
751
799
  * fingerprint is semantic (AMA-relevant changes only) and identical to the
752
800
  * unlock wrapper watchdog's view of the same file.
753
- * @returns {any} Snapshot with exists flag, fingerprint, active bots list, and adapter requirement
801
+ * @returns {unknown} Snapshot with exists flag, fingerprint, active bots list, and adapter requirement
754
802
  */
755
803
  function loadBotsConfigSnapshot() {
756
804
  return readAdapterRequirement(PROFILES_BOTS_FILE);
@@ -853,9 +901,9 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
853
901
  // fingerprints, retry next tick.
854
902
  let snapshot = null;
855
903
  try {
856
- snapshot = typeof bot._loadBotsConfigSnapshot === 'function'
904
+ snapshot = (typeof bot._loadBotsConfigSnapshot === 'function'
857
905
  ? await bot._loadBotsConfigSnapshot()
858
- : loadBotsConfigSnapshot();
906
+ : loadBotsConfigSnapshot());
859
907
  }
860
908
  catch (err) {
861
909
  bot._warn(`Ignoring unreadable bots.json during ${context}; keeping previous market adapter state.`);
@@ -897,8 +945,9 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
897
945
  // ?? (not ||): the semantic fingerprint is legitimately '' when no
898
946
  // active AMA bot exists, and '' must compare equal to a stored ''.
899
947
  const previousFingerprint = bot._marketAdapterWatchdogFingerprint ?? null;
900
- const changed = snapshot.fingerprint !== previousFingerprint;
901
- bot._marketAdapterWatchdogFingerprint = snapshot.fingerprint;
948
+ const fingerprint = snapshot.fingerprint;
949
+ const changed = fingerprint !== previousFingerprint;
950
+ bot._marketAdapterWatchdogFingerprint = fingerprint;
902
951
  if (changed) {
903
952
  bot._log(`Detected bots.json changes during ${context}; re-evaluating market adapter requirements.`);
904
953
  }
@@ -953,9 +1002,10 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
953
1002
  }
954
1003
  // Cross-reference config-active bots against actually running PM2 processes
955
1004
  // so we don't start the adapter for configured AMA bots that aren't running.
1005
+ const activeBots = (snapshot.activeBots ?? []);
956
1006
  const runningActiveBots = pm2QueryFailed
957
- ? snapshot.activeBots
958
- : snapshot.activeBots.filter((b) => processNames.includes(b.name));
1007
+ ? activeBots
1008
+ : activeBots.filter((b) => processNames.includes(String(b.name)));
959
1009
  const needsAdapterForRunningBots = runningActiveBots.some(usesAmaGridPrice);
960
1010
  if (!snapshot.exists || !needsAdapterForRunningBots) {
961
1011
  const shouldStop = pm2QueryFailed || processNames.includes(MARKET_ADAPTER_APP_NAME);
@@ -1021,7 +1071,7 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
1021
1071
  * Applies live dynamic weights if the bot is whitelisted and weights are ready.
1022
1072
  * @param {import('./dexbot_class.js').DEXBot} bot
1023
1073
  * @param {string} [context='runtime'] - Context label for logging
1024
- * @returns {any}
1074
+ * @returns {unknown}
1025
1075
  */
1026
1076
  function refreshDynamicWeightDistribution(bot, context = 'runtime') {
1027
1077
  const baseWeights = cloneWeightDistribution(bot._baseWeightDistribution, bot.config?.weightDistribution || bot.manager?.config?.weightDistribution);
@@ -1077,7 +1127,7 @@ function refreshDynamicWeightDistribution(bot, context = 'runtime') {
1077
1127
  * Read and parse a trigger file's metadata payload.
1078
1128
  * Determines whether the trigger originated from the market adapter or was manual.
1079
1129
  * @param {string} triggerFile - Path to the trigger file
1080
- * @returns {any} Parsed trigger metadata
1130
+ * @returns {unknown} Parsed trigger metadata
1081
1131
  */
1082
1132
  function readTriggerMetadata(triggerFile) {
1083
1133
  const manualTriggerMetadata = (payload = null) => ({
@@ -1111,7 +1161,7 @@ function readTriggerMetadata(triggerFile) {
1111
1161
  * Build grid resync metadata from a reason string.
1112
1162
  * Maps known reason strings to structured metadata with refresh flags.
1113
1163
  * @param {string} reason - Resync reason identifier (e.g. 'manual_grid_resync', 'rms_structural_grid_resync')
1114
- * @returns {any}
1164
+ * @returns {unknown}
1115
1165
  */
1116
1166
  function buildGridResyncMetadata(reason) {
1117
1167
  const resetSource = String(reason || '').trim() || 'dexbot_grid_resync';
@@ -1136,12 +1186,12 @@ function buildGridResyncMetadata(reason) {
1136
1186
  /**
1137
1187
  * Build grid resync options from a reason string or metadata object.
1138
1188
  * @param {string|any} reasonOrMetadata - Reason string or metadata object
1139
- * @returns {any}
1189
+ * @returns {unknown}
1140
1190
  */
1141
1191
  function buildGridResyncOptions(reasonOrMetadata) {
1142
- const metadata = typeof reasonOrMetadata === 'string'
1192
+ const metadata = (typeof reasonOrMetadata === 'string'
1143
1193
  ? buildGridResyncMetadata(reasonOrMetadata)
1144
- : reasonOrMetadata;
1194
+ : reasonOrMetadata);
1145
1195
  return {
1146
1196
  refreshCenterPrice: !!metadata?.shouldRefreshCenterPrice,
1147
1197
  centerRefreshContext: metadata?.centerRefreshContext,
@@ -1164,16 +1214,17 @@ function promoteAmaCenterSnapshotForGridReset(botKey) {
1164
1214
  const snapshotPath = path.join(PATHS.ORDERS_DIR, `${botKey}.dynamicgrid.json`);
1165
1215
  try {
1166
1216
  const result = updateDynamicGridSnapshotSync(snapshotPath, (snapshot) => {
1167
- const amaCenterPrice = Number(snapshot?.amaCenterPrice);
1217
+ const snap = snapshot;
1218
+ const amaCenterPrice = Number(snap?.amaCenterPrice);
1168
1219
  if (!Number.isFinite(amaCenterPrice) || amaCenterPrice <= 0) {
1169
1220
  return { ok: false, write: false };
1170
1221
  }
1171
- const currentCenterPrice = Number(snapshot?.gridCenterPrice ?? snapshot?.centerPrice);
1222
+ const currentCenterPrice = Number(snap?.gridCenterPrice ?? snap?.centerPrice);
1172
1223
  if (Number.isFinite(currentCenterPrice) && currentCenterPrice === amaCenterPrice) {
1173
1224
  return { write: false };
1174
1225
  }
1175
1226
  return {
1176
- ...snapshot,
1227
+ ...snap,
1177
1228
  gridCenterPrice: amaCenterPrice,
1178
1229
  centerPrice: amaCenterPrice,
1179
1230
  updatedAt: nowIso(),
@@ -1201,12 +1252,13 @@ function updateBotGridResetMetadata(botKey, options = {}) {
1201
1252
  const snapshotPath = path.join(PATHS.ORDERS_DIR, `${botKey}.dynamicgrid.json`);
1202
1253
  try {
1203
1254
  const result = updateDynamicGridSnapshotSync(snapshotPath, (snapshot) => {
1204
- const gridCenterPrice = Number(snapshot?.gridCenterPrice ?? snapshot?.centerPrice);
1255
+ const snap = snapshot;
1256
+ const gridCenterPrice = Number(snap?.gridCenterPrice ?? snap?.centerPrice);
1205
1257
  if (!Number.isFinite(gridCenterPrice) || gridCenterPrice <= 0) {
1206
1258
  return { ok: false, write: false };
1207
1259
  }
1208
1260
  return {
1209
- ...snapshot,
1261
+ ...snap,
1210
1262
  gridCenterPrice,
1211
1263
  centerPrice: gridCenterPrice,
1212
1264
  lastGridResetAt: resetAt,
@@ -1224,7 +1276,7 @@ function updateBotGridResetMetadata(botKey, options = {}) {
1224
1276
  * Perform a full grid resync: reload config, optionally refresh center price,
1225
1277
  * recalculate the grid, persist, and record reset metadata.
1226
1278
  * @param {import('./dexbot_class.js').DEXBot} bot
1227
- * @param {any} [options] - Grid resync options
1279
+ * @param {unknown} [options] - Grid resync options
1228
1280
  * @param {boolean} [options.skipIdle=false] - Skip the idle-cooldown deferral
1229
1281
  * @returns {Promise<boolean>} True if resync succeeded
1230
1282
  */
@@ -1629,19 +1681,11 @@ function considerDeferredHoldEscalation(bot, strandedOrders, strandedMs) {
1629
1681
  `requesting structural resync to resolve the hold (reconcile is update-first, ` +
1630
1682
  `so funds are released by price-updating onto rail slots) — ` +
1631
1683
  `${describeDeferredHolds(bot, strandedOrders)}`, 'error');
1632
- try {
1633
- const res = bot.manager.requestStructuralGridResync('deferred-hold-stale', {
1634
- reason: `${held} deferred chain order(s) held unchanged for ~${heldHours}h`,
1635
- heldCount: held,
1636
- heldMs,
1637
- });
1638
- res?.catch?.((err) => {
1639
- bot.manager?.logger?.log?.(`[HOLD] Structural resync for stale hold failed: ${getErrorMessage(err)}`, 'error');
1640
- });
1641
- }
1642
- catch (err) {
1643
- bot.manager?.logger?.log?.(`[HOLD] Structural resync for stale hold failed: ${getErrorMessage(err)}`, 'error');
1644
- }
1684
+ fireStructuralResync(bot, 'deferred-hold-stale', {
1685
+ reason: `${held} deferred chain order(s) held unchanged for ~${heldHours}h`,
1686
+ heldCount: held,
1687
+ heldMs,
1688
+ }, '[HOLD] Structural resync for stale hold failed');
1645
1689
  }
1646
1690
  /**
1647
1691
  * Render the per-order detail for a deferred-hold summary: side, price, size,
@@ -1862,12 +1906,12 @@ function setupBlockchainFetchInterval(bot) {
1862
1906
  // from the window (then re-create them as duplicates).
1863
1907
  // Defer the sync to a clean read; fills are still
1864
1908
  // caught by subscription events and the next cycle.
1865
- chainOpenOrders = (typeof bot._readOpenOrdersHook === 'function')
1909
+ chainOpenOrders = ((typeof bot._readOpenOrdersHook === 'function')
1866
1910
  ? await bot._readOpenOrdersHook()
1867
1911
  : await readOpenOrdersGuarded(chainOrders, bot.accountId, {
1868
1912
  log: (message, level) => bot._log(message, level),
1869
1913
  label: 'PERIODIC-SYNC',
1870
- });
1914
+ }));
1871
1915
  if (chainOpenOrders !== null) {
1872
1916
  const syncResult = await bot.manager.synchronizeWithChain(chainOpenOrders, 'periodicBlockchainFetch');
1873
1917
  if (syncResult.filledOrders && syncResult.filledOrders.length > 0) {
@@ -2051,7 +2095,7 @@ function isOrderDoesNotExistError(message, orderId) {
2051
2095
  * manager._broadcastingStartedAt on every holder, so its age stays small;
2052
2096
  * a frozen timestamp ages past BROADCAST_STALE_CLEAR_MS and we let the tick
2053
2097
  * through so maintenance can hard-reset the flag.
2054
- * @param {any} bot
2098
+ * @param {unknown} bot
2055
2099
  * @returns {boolean} true when the caller should skip this tick
2056
2100
  */
2057
2101
  function shouldDeferMaintenanceForBroadcast(bot) {
@@ -2079,7 +2123,7 @@ function shouldDeferMaintenanceForBroadcast(bot) {
2079
2123
  * any such section visible: when the live hold crosses
2080
2124
  * TIMING.GRID_LOCK_HOLD_WARN_MS it emits a rate-limited warn. Called from the
2081
2125
  * maintenance tick so holds outside a broadcast region are observed too.
2082
- * @param {any} bot
2126
+ * @param {unknown} bot
2083
2127
  * @returns {number} Observed hold duration in ms (0 when not held)
2084
2128
  */
2085
2129
  function checkGridLockHoldDuration(bot) {
@@ -2124,7 +2168,7 @@ function getMaintenanceIdleDelayMs(ctx) {
2124
2168
  : TIMING.BLOCKCHAIN_SETTLE_DELAY_MS;
2125
2169
  if (settleDelayMs <= 0)
2126
2170
  return 0;
2127
- if (ctx?._incomingFillQueue?.length > 0)
2171
+ if ((ctx?._incomingFillQueue?.length ?? 0) > 0)
2128
2172
  return settleDelayMs;
2129
2173
  const lastActivityAt = Number(ctx?._lastGridActivityAt || 0);
2130
2174
  if (!Number.isFinite(lastActivityAt) || lastActivityAt <= 0)
@@ -2150,9 +2194,9 @@ function scheduleMaintenanceAfterIdle(ctx, context, options = {}) {
2150
2194
  ctx._maintenanceIdleTimer = null;
2151
2195
  if (ctx._shuttingDown)
2152
2196
  return;
2153
- ctx._runGridMaintenance(context, timerOptions)
2154
- .catch((err) => {
2155
- ctx._warn(`Deferred ${context} grid maintenance failed: ${getErrorMessage(err)}`);
2197
+ ctx._runGridMaintenance?.(context, timerOptions)
2198
+ ?.catch((err) => {
2199
+ ctx._warn?.(`Deferred ${context} grid maintenance failed: ${getErrorMessage(err)}`);
2156
2200
  if (ctx.manager) {
2157
2201
  ctx.manager._recoveryState = { ...ctx.manager._recoveryState, lastFailureAt: Date.now() };
2158
2202
  }
@@ -2162,7 +2206,7 @@ function scheduleMaintenanceAfterIdle(ctx, context, options = {}) {
2162
2206
  /**
2163
2207
  * Schedule a deferred grid resync after idle delay elapses.
2164
2208
  * @param {Object} ctx - Bot context
2165
- * @param {any} [options] - Grid resync options
2209
+ * @param {unknown} [options] - Grid resync options
2166
2210
  */
2167
2211
  function scheduleDeferredGridResync(ctx, options = {}) {
2168
2212
  if (!ctx ||
@@ -2185,17 +2229,17 @@ function scheduleDeferredGridResync(ctx, options = {}) {
2185
2229
  return;
2186
2230
  if (triggerFileWasPresent && !storage.exists(ctx.triggerFile))
2187
2231
  return;
2188
- ctx.manager._fillProcessingLock.acquire(async () => {
2189
- const ok = await ctx._performGridResync(options);
2232
+ ctx.manager?._fillProcessingLock?.acquire?.(async () => {
2233
+ const ok = await ctx._performGridResync?.(options);
2190
2234
  if (!ok && !ctx._shuttingDown) {
2191
2235
  const curIdleMs = getMaintenanceIdleDelayMs(ctx);
2192
2236
  const reason = curIdleMs > 0
2193
2237
  ? `idle cooldown (${Math.ceil(curIdleMs / TIMING.MILLISECONDS_PER_SECOND)}s)`
2194
2238
  : 'grid resync rejected or failed';
2195
- ctx._warn(`Deferred trigger reset blocked: ${reason}; retaining existing grid state.`);
2239
+ ctx._warn?.(`Deferred trigger reset blocked: ${reason}; retaining existing grid state.`);
2196
2240
  }
2197
- }).catch((err) => {
2198
- ctx._warn(`Deferred trigger reset lock error: ${getErrorMessage(err)}`);
2241
+ })?.catch((err) => {
2242
+ ctx._warn?.(`Deferred trigger reset lock error: ${getErrorMessage(err)}`);
2199
2243
  if (ctx.manager) {
2200
2244
  ctx.manager._recoveryState = { ...ctx.manager._recoveryState, lastFailureAt: Date.now() };
2201
2245
  }
@@ -2439,10 +2483,13 @@ async function executeMaintenanceLogic(bot, context) {
2439
2483
  const spreadResult = await bot.manager.checkSpreadCondition(BitShares, bot.updateOrdersOnChainPlan.bind(bot));
2440
2484
  if (await bot._abortFlowIfIllegalState(`${context} spread check`))
2441
2485
  return;
2442
- // Mirror the check result so the next tick's targeted-sync gate
2443
- // (getTargetedSyncReason) refreshes funds/open orders when the
2444
- // correction could not find any free funds.
2445
- bot._spreadFundsExhausted = spreadResult?.fundsExhausted === true;
2486
+ // Mirror the stall cause and arm the targeted-sync refresh for
2487
+ // every cause. The check can report 'no-candidates' on a stale
2488
+ // local snapshot (a missed fill leaves an ACTIVE slot hiding the
2489
+ // tightening slot), so the refresh must fire here too rather than
2490
+ // wait for trackOutOfSpreadStaleness to re-center. The stall cause
2491
+ // is kept so the next tick's reason names the truth.
2492
+ mirrorSpreadStall(bot, spreadResult?.stall ?? null);
2446
2493
  const spreadPlaced = Number(spreadResult?.ordersPlaced) || 0;
2447
2494
  if (spreadPlaced > 0) {
2448
2495
  bot._log(`✓ Spread correction during ${context}: ${spreadResult.ordersPlaced} order(s) placed`);
@@ -2478,7 +2525,7 @@ async function executeMaintenanceLogic(bot, context) {
2478
2525
  * dedupe concurrent requests; the re-center moves the boundary, which clears
2479
2526
  * any held-plan signature). Resets whenever the spread heals or a correction
2480
2527
  * places orders.
2481
- * @param {any} bot
2528
+ * @param {unknown} bot
2482
2529
  * @param {boolean} spreadChecked - Whether the spread check ran this tick
2483
2530
  * @param {number} ordersPlaced - Correction orders placed this tick
2484
2531
  * @returns {{staleMs: number, escalated: boolean}}
@@ -2525,17 +2572,9 @@ export function trackOutOfSpreadStaleness(bot, spreadChecked, ordersPlaced) {
2525
2572
  bot._lastSpreadStaleResyncAt = now;
2526
2573
  bot._log(`[SPREAD-STALE] Spread out of tolerance for ${staleMin}min despite corrections; ` +
2527
2574
  `requesting structural re-center`, 'warn');
2528
- try {
2529
- const res = bot.manager.requestStructuralGridResync('spread-stale-persistent', {
2530
- reason: `Spread out of tolerance for ${staleMin}min with no effective correction (outOfSpread=${outOfSpread})`
2531
- });
2532
- res?.catch?.((err) => {
2533
- bot.manager?.logger?.log?.(`[SPREAD-STALE] Structural re-center request failed: ${getErrorMessage(err)}`, 'error');
2534
- });
2535
- }
2536
- catch (err) {
2537
- bot.manager?.logger?.log?.(`[SPREAD-STALE] Structural re-center request failed: ${getErrorMessage(err)}`, 'error');
2538
- }
2575
+ fireStructuralResync(bot, 'spread-stale-persistent', {
2576
+ reason: `Spread out of tolerance for ${staleMin}min with no effective correction (outOfSpread=${outOfSpread})`
2577
+ }, '[SPREAD-STALE] Structural re-center request failed');
2539
2578
  return { staleMs, escalated: true };
2540
2579
  }
2541
2580
  }
@@ -2564,9 +2603,9 @@ async function cancelOrderDeferredOnUncertain(bot, order) {
2564
2603
  // Test seam: compiled ESM exports cannot be monkey-patched, so tests
2565
2604
  // may override cancellation through this bot-level hook.
2566
2605
  if (typeof bot._submitCancelOrder === 'function') {
2567
- return await bot._submitCancelOrder(order.orderId);
2606
+ return await bot._submitCancelOrder(String(order.orderId));
2568
2607
  }
2569
- return await chainOrders.cancelOrder(bot.account, bot.privateKey, order.orderId);
2608
+ return await chainOrders.cancelOrder(bot.account, bot.privateKey, String(order.orderId));
2570
2609
  }
2571
2610
  catch (err) {
2572
2611
  if (err instanceof BroadcastUncertainError) {
@@ -2724,7 +2763,7 @@ async function checkBtsBalanceAndAcquire(bot) {
2724
2763
  const minBtsVal = calculateOrderCreationFees(bot.config.assetA, bot.config.assetB, totalTarget, btsReservationMultiplier);
2725
2764
  if (minBtsVal <= 0)
2726
2765
  return;
2727
- const effectiveMin = (bot.config.min_BTS_value > 0) ? bot.config.min_BTS_value : minBtsVal;
2766
+ const effectiveMin = ((bot.config.min_BTS_value ?? 0) > 0) ? bot.config.min_BTS_value : minBtsVal;
2728
2767
  const btsFree = bot.manager.btsBalance.free || 0;
2729
2768
  const btsAcquireThreshold = bot.config?.feeParams?.BTS_ACQUIRE_THRESHOLD;
2730
2769
  const triggerAt = effectiveMin * btsAcquireThreshold;
@@ -3059,14 +3098,14 @@ function wireStructuralGridResyncRequest(bot) {
3059
3098
  bot._recoverySyncInFlight = (bot._recoverySyncInFlight || 0) + 1;
3060
3099
  let resetResult;
3061
3100
  try {
3062
- resetResult = await bot.requestGridReset('rms_structural_grid_resync', {
3101
+ resetResult = await (bot.requestGridReset('rms_structural_grid_resync', {
3063
3102
  refreshCenterPrice: false,
3064
3103
  // Structural resync is a chain-read/rebuild; do not let a
3065
3104
  // fill storm starve it behind the idle cooldown or the
3066
3105
  // fill-processing lock.
3067
3106
  skipIdle: true,
3068
3107
  skipFillLock: true,
3069
- });
3108
+ }));
3070
3109
  }
3071
3110
  finally {
3072
3111
  bot._recoverySyncInFlight = Math.max(0, (bot._recoverySyncInFlight || 0) - 1);
@@ -3215,7 +3254,7 @@ async function syncOpenOrdersAndProcessFillsImpl(bot, tag) {
3215
3254
  return { syncResult: null, aborted: true, hasUnmatched: -1, openOrders: null };
3216
3255
  }
3217
3256
  }
3218
- 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 };
3257
+ 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 };
3219
3258
  export default {
3220
3259
  loadBotsConfigSnapshot,
3221
3260
  isWrapperAdapterOwner,
@@ -3236,6 +3275,7 @@ export default {
3236
3275
  stopBotsConfigPollInterval,
3237
3276
  executeMaintenanceLogic,
3238
3277
  getTargetedSyncReason,
3278
+ mirrorSpreadStall,
3239
3279
  countLiveReserveOrders,
3240
3280
  maybeRunTargetedDriftReconciliation,
3241
3281
  cancelDustOrders,