dexbot 1.6.11 → 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 (354) hide show
  1. package/CHANGELOG.md +35 -4
  2. package/README.md +2 -1
  3. package/analysis/README.md +2 -0
  4. package/analysis/tradingview/README.md +1 -1
  5. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
  6. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  7. package/claw/modules/chain_broadcast.ts +7 -1
  8. package/claw/modules/claw_launcher.ts +1 -1
  9. package/claw/modules/launcher_mode_detector.ts +9 -2
  10. package/claw/package.json +1 -1
  11. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  12. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  13. package/dist/analysis/account_resolver.d.ts +1 -1
  14. package/dist/analysis/account_resolver.js +2 -1
  15. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  16. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -7
  17. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  18. package/dist/analysis/ama_fitting/fetch_lp_candles.js +4 -4
  19. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +20 -4
  20. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +9 -6
  21. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +16 -12
  22. package/dist/analysis/analyze_args.d.ts +31 -0
  23. package/dist/analysis/analyze_args.js +41 -0
  24. package/dist/analysis/analyze_dynamic_weight.js +7 -17
  25. package/dist/analysis/analyze_kalman.js +7 -17
  26. package/dist/analysis/analyze_regime.js +7 -17
  27. package/dist/analysis/analyze_regime_windows.js +8 -18
  28. package/dist/analysis/analyze_risk_profile.js +8 -18
  29. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  30. package/dist/analysis/analyze_volatility.js +7 -17
  31. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +220 -12
  32. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +6 -5
  33. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  34. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +11 -63
  35. package/dist/analysis/bot_fitting/shared_utils.d.ts +7 -7
  36. package/dist/analysis/bot_fitting/shared_utils.js +2 -2
  37. package/dist/analysis/bot_key_utils.d.ts +18 -10
  38. package/dist/analysis/bot_key_utils.js +7 -4
  39. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  40. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  41. package/dist/analysis/chain_pool.d.ts +3 -1
  42. package/dist/analysis/chart_ui.d.ts +5 -2
  43. package/dist/analysis/chart_ui.js +6 -3
  44. package/dist/analysis/chart_utils.d.ts +5 -5
  45. package/dist/analysis/chart_utils.js +9 -0
  46. package/dist/analysis/fills_cache.d.ts +1 -1
  47. package/dist/analysis/fills_source.d.ts +2 -2
  48. package/dist/analysis/fills_source.js +14 -12
  49. package/dist/analysis/grid_correction_check.d.ts +1 -1
  50. package/dist/analysis/grid_correction_check.js +12 -11
  51. package/dist/analysis/math_utils.d.ts +7 -6
  52. package/dist/analysis/math_utils.js +5 -8
  53. package/dist/analysis/pnl_report.js +29 -29
  54. package/dist/analysis/price_sources.d.ts +8 -8
  55. package/dist/analysis/price_sources.js +5 -4
  56. package/dist/analysis/resolve_bot_accounts.js +2 -2
  57. package/dist/analysis/resolve_source.d.ts +1 -1
  58. package/dist/analysis/trade_profitability.d.ts +23 -2
  59. package/dist/analysis/trade_profitability.js +50 -50
  60. package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
  61. package/dist/analysis/tradingview/analyze_tradingview.js +6 -5
  62. package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
  63. package/dist/analysis/tradingview/grid_reset_config.js +23 -11
  64. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
  65. package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
  66. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  67. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +18 -19
  68. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -1
  69. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +5 -5
  70. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  71. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +5 -4
  72. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
  73. package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
  74. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  75. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  76. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  77. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  78. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  79. package/dist/credential-daemon.js +34 -20
  80. package/dist/dexbot.js +11 -11
  81. package/dist/market_adapter/candle_utils.d.ts +22 -18
  82. package/dist/market_adapter/candle_utils.js +24 -20
  83. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  84. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  85. package/dist/market_adapter/core/kibana_candles.d.ts +53 -18
  86. package/dist/market_adapter/core/kibana_candles.js +9 -7
  87. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  88. package/dist/market_adapter/core/kibana_client.js +8 -7
  89. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  90. package/dist/market_adapter/core/market_adapter_service.d.ts +284 -117
  91. package/dist/market_adapter/core/market_adapter_service.js +137 -113
  92. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  93. package/dist/market_adapter/core/strategies/ama.js +2 -4
  94. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  95. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  96. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  97. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  98. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  99. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  100. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
  101. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
  102. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  103. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  104. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  105. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  106. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  107. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  108. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  109. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  110. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  111. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  112. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +96 -224
  113. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +42 -7
  114. package/dist/market_adapter/inputs/fetch_lp_data.js +22 -15
  115. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  116. package/dist/market_adapter/inputs/kibana_feed_source.js +29 -22
  117. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  118. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  119. package/dist/market_adapter/inputs/window_cache.d.ts +99 -94
  120. package/dist/market_adapter/inputs/window_cache.js +8 -8
  121. package/dist/market_adapter/interval_utils.d.ts +4 -4
  122. package/dist/market_adapter/log_format.d.ts +6 -6
  123. package/dist/market_adapter/log_format.js +28 -21
  124. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  125. package/dist/market_adapter/lp_chart_core.js +26 -192
  126. package/dist/market_adapter/lp_chart_runner.d.ts +7 -7
  127. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  128. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  129. package/dist/market_adapter/market_adapter.d.ts +94 -32
  130. package/dist/market_adapter/market_adapter.js +67 -48
  131. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  132. package/dist/market_adapter/utils/adapter_client.js +2 -2
  133. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  134. package/dist/market_adapter/utils/chain.d.ts +50 -41
  135. package/dist/market_adapter/utils/chain.js +40 -46
  136. package/dist/market_adapter/utils/data_discovery.d.ts +4 -1
  137. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  138. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  139. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  140. package/dist/market_adapter/utils/file_lock.js +36 -32
  141. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  142. package/dist/market_adapter/utils/native_history.js +35 -28
  143. package/dist/modules/account_bots.d.ts +577 -21
  144. package/dist/modules/account_bots.js +182 -158
  145. package/dist/modules/account_orders.d.ts +66 -30
  146. package/dist/modules/account_orders.js +22 -20
  147. package/dist/modules/authority_resolver.d.ts +12 -2
  148. package/dist/modules/authority_resolver.js +15 -8
  149. package/dist/modules/bitshares-native/chain_client.d.ts +38 -3
  150. package/dist/modules/bitshares-native/chain_client.js +45 -46
  151. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  152. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  153. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  154. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  155. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  156. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  157. package/dist/modules/bitshares-native/index.d.ts +1 -1
  158. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  159. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  160. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  161. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  162. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  163. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  164. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  165. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  166. package/dist/modules/bitshares-native/serial/types.js +55 -62
  167. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  168. package/dist/modules/bitshares-native/signing_client.js +19 -14
  169. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  170. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  171. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  172. package/dist/modules/bitshares-native/transport.js +5 -4
  173. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  174. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  175. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  176. package/dist/modules/bitshares_client.d.ts +45 -13
  177. package/dist/modules/bitshares_client.js +28 -19
  178. package/dist/modules/bot_defaults.d.ts +6 -15
  179. package/dist/modules/bot_defaults.js +1 -5
  180. package/dist/modules/bot_settings.d.ts +44 -10
  181. package/dist/modules/bot_settings.js +11 -8
  182. package/dist/modules/bots_file_lock.d.ts +6 -6
  183. package/dist/modules/bots_file_lock.js +16 -12
  184. package/dist/modules/broadcast_failure.d.ts +2 -2
  185. package/dist/modules/broadcast_failure.js +5 -4
  186. package/dist/modules/chain_keys.d.ts +42 -40
  187. package/dist/modules/chain_keys.js +53 -45
  188. package/dist/modules/chain_orders.d.ts +93 -59
  189. package/dist/modules/chain_orders.js +31 -23
  190. package/dist/modules/constants.d.ts +527 -31
  191. package/dist/modules/constants.js +15 -47
  192. package/dist/modules/cr_planner.d.ts +40 -2
  193. package/dist/modules/credential_policy.d.ts +68 -8
  194. package/dist/modules/credential_policy.js +37 -31
  195. package/dist/modules/credential_session_cache.d.ts +2 -2
  196. package/dist/modules/credit_pricing.d.ts +42 -6
  197. package/dist/modules/credit_pricing.js +44 -30
  198. package/dist/modules/credit_runtime.d.ts +276 -118
  199. package/dist/modules/credit_runtime.js +462 -165
  200. package/dist/modules/crypto/browser_provider.js +6 -4
  201. package/dist/modules/crypto/node_provider.js +1 -1
  202. package/dist/modules/crypto/pure_scrypt.js +35 -4
  203. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  204. package/dist/modules/crypto/sync.d.ts +9 -9
  205. package/dist/modules/crypto/sync.js +16 -9
  206. package/dist/modules/dexbot_class.d.ts +195 -139
  207. package/dist/modules/dexbot_class.js +78 -28
  208. package/dist/modules/dexbot_cow_runtime.d.ts +167 -87
  209. package/dist/modules/dexbot_cow_runtime.js +248 -206
  210. package/dist/modules/dexbot_credential_client.d.ts +19 -11
  211. package/dist/modules/dexbot_fill_runtime.d.ts +63 -48
  212. package/dist/modules/dexbot_fill_runtime.js +48 -41
  213. package/dist/modules/dexbot_maintenance_runtime.d.ts +109 -70
  214. package/dist/modules/dexbot_maintenance_runtime.js +108 -83
  215. package/dist/modules/dexbot_startup_runtime.d.ts +11 -10
  216. package/dist/modules/dexbot_startup_runtime.js +43 -43
  217. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  218. package/dist/modules/dexbot_state_recovery.js +18 -13
  219. package/dist/modules/fund_registry.d.ts +4 -2
  220. package/dist/modules/fund_registry.js +10 -10
  221. package/dist/modules/general_settings.d.ts +30 -4
  222. package/dist/modules/graceful_shutdown.d.ts +3 -3
  223. package/dist/modules/graceful_shutdown.js +2 -2
  224. package/dist/modules/grid_price_source.d.ts +1 -1
  225. package/dist/modules/key_store.d.ts +14 -8
  226. package/dist/modules/key_store.js +7 -6
  227. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  228. package/dist/modules/launcher/adapter_requirement.js +5 -5
  229. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  230. package/dist/modules/launcher/bot_supervisor.js +12 -11
  231. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  232. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  233. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  234. package/dist/modules/launcher/credential_daemon.js +2 -2
  235. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  236. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  237. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  238. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  239. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  240. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  241. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  242. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  243. package/dist/modules/launcher/supervisor_control.js +4 -2
  244. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  245. package/dist/modules/market_adapter_whitelist.js +15 -3
  246. package/dist/modules/node_manager.d.ts +41 -11
  247. package/dist/modules/node_manager.js +5 -4
  248. package/dist/modules/order/accounting.d.ts +53 -24
  249. package/dist/modules/order/accounting.js +16 -15
  250. package/dist/modules/order/async_lock.d.ts +5 -2
  251. package/dist/modules/order/async_lock.js +1 -1
  252. package/dist/modules/order/export.d.ts +7 -6
  253. package/dist/modules/order/export.js +1 -7
  254. package/dist/modules/order/format.d.ts +4 -4
  255. package/dist/modules/order/genesis_policy.d.ts +21 -18
  256. package/dist/modules/order/genesis_policy.js +12 -8
  257. package/dist/modules/order/grid.d.ts +142 -36
  258. package/dist/modules/order/grid.js +148 -123
  259. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  260. package/dist/modules/order/grid_reconcile.js +13 -12
  261. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  262. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  263. package/dist/modules/order/index.d.ts +263 -1
  264. package/dist/modules/order/logger.d.ts +45 -11
  265. package/dist/modules/order/logger.js +38 -40
  266. package/dist/modules/order/logger_state.d.ts +4 -4
  267. package/dist/modules/order/manager.d.ts +225 -180
  268. package/dist/modules/order/manager.js +80 -83
  269. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  270. package/dist/modules/order/processed_fill_store.js +16 -27
  271. package/dist/modules/order/strategy.d.ts +21 -13
  272. package/dist/modules/order/strategy.js +5 -6
  273. package/dist/modules/order/sync_engine.d.ts +91 -33
  274. package/dist/modules/order/sync_engine.js +84 -53
  275. package/dist/modules/order/utils/math.d.ts +157 -102
  276. package/dist/modules/order/utils/math.js +77 -38
  277. package/dist/modules/order/utils/order.d.ts +310 -110
  278. package/dist/modules/order/utils/order.js +122 -99
  279. package/dist/modules/order/utils/slot.d.ts +1 -1
  280. package/dist/modules/order/utils/system.d.ts +176 -26
  281. package/dist/modules/order/utils/system.js +86 -69
  282. package/dist/modules/order/utils/validate.d.ts +89 -41
  283. package/dist/modules/order/utils/validate.js +24 -22
  284. package/dist/modules/order/utils/withPoolRef.d.ts +4 -3
  285. package/dist/modules/order/utils/withPoolRef.js +18 -12
  286. package/dist/modules/order/working_grid.d.ts +14 -13
  287. package/dist/modules/paths.d.ts +1 -4
  288. package/dist/modules/paths.js +1 -27
  289. package/dist/modules/process_discovery.d.ts +1 -1
  290. package/dist/modules/process_discovery.js +2 -1
  291. package/dist/modules/runtime.d.ts +7 -3
  292. package/dist/modules/runtime.js +4 -3
  293. package/dist/modules/runtime_settings.d.ts +15 -10
  294. package/dist/modules/runtime_settings.js +30 -24
  295. package/dist/modules/settings_merge.d.ts +29 -3
  296. package/dist/modules/settings_merge.js +56 -78
  297. package/dist/modules/socket_json_client.d.ts +7 -4
  298. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  299. package/dist/modules/storage/browser_adapter.js +7 -30
  300. package/dist/modules/storage/index.d.ts +1 -1
  301. package/dist/modules/storage/node_adapter.d.ts +45 -27
  302. package/dist/modules/storage/node_adapter.js +9 -9
  303. package/dist/modules/storage/types.d.ts +5 -4
  304. package/dist/modules/types.d.ts +1071 -2
  305. package/dist/modules/types.js +4 -1
  306. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  307. package/dist/modules/utils/asset_symbols.js +2 -1
  308. package/dist/modules/utils/errors.d.ts +9 -0
  309. package/dist/modules/utils/errors.js +23 -1
  310. package/dist/modules/utils/time_range.d.ts +1 -12
  311. package/dist/modules/utils/time_range.js +1 -1
  312. package/dist/modules/validate_profiles.js +53 -43
  313. package/dist/modules/version_notice.d.ts +14 -3
  314. package/dist/modules/version_notice.js +6 -4
  315. package/dist/pm2.d.ts +29 -27
  316. package/dist/pm2.js +5 -5
  317. package/dist/scripts/analyze-credit.d.ts +2 -1
  318. package/dist/scripts/analyze-credit.js +23 -24
  319. package/dist/scripts/analyze-orders.d.ts +77 -9
  320. package/dist/scripts/analyze-orders.js +65 -40
  321. package/dist/scripts/chart_command.d.ts +27 -18
  322. package/dist/scripts/chart_command.js +13 -11
  323. package/dist/scripts/check_any.d.ts +18 -0
  324. package/dist/scripts/check_any.js +126 -0
  325. package/dist/scripts/diagnose-pool-history.js +12 -7
  326. package/dist/scripts/print_grid.js +0 -1
  327. package/dist/scripts/run-tests.js +39 -7
  328. package/dist/scripts/runner.js +1 -1
  329. package/dist/scripts/test-credit-renewal.js +30 -21
  330. package/dist/scripts/update.d.ts +10 -5
  331. package/dist/scripts/update.js +168 -103
  332. package/dist/scripts/update_dist_freshness.js +1 -0
  333. package/dist/scripts/update_layout.d.ts +61 -0
  334. package/dist/scripts/update_layout.js +180 -0
  335. package/dist/scripts/validate_bots.js +2 -1
  336. package/dist/scripts/verify-browser-bundle.js +8 -0
  337. package/dist/unlock.d.ts +28 -3
  338. package/dist/unlock.js +63 -35
  339. package/docs/BITSHARES_ONBOARDING.md +2 -0
  340. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  341. package/docs/COW_INVARIANTS.md +13 -6
  342. package/docs/DEXBOT_COMPARISON.md +8 -8
  343. package/docs/EVOLUTION.md +10 -9
  344. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  345. package/docs/GRID_RECALCULATION.md +4 -2
  346. package/docs/GRID_RECONCILE.md +14 -3
  347. package/docs/LIFECYCLE.md +11 -11
  348. package/docs/MPA_CREDIT_USAGE.md +22 -3
  349. package/docs/README.md +14 -3
  350. package/docs/architecture.md +12 -9
  351. package/docs/developer_guide.md +6 -6
  352. package/market_adapter/README.md +6 -1
  353. package/modules/README.md +4 -1
  354. package/package.json +4 -1
@@ -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) {
@@ -499,9 +507,10 @@ async function checkAndApplyBotConfigChanges(bot, context = 'bots-config poll',
499
507
  `Targeted maintenance will place missing / cancel excess orders.`, 'info');
500
508
  // Deliver the promise above instead of waiting for the next fill
501
509
  // 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).
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.
505
514
  try {
506
515
  const driftRun = maybeRunTargetedDriftReconciliation(bot, `${context} config pickup`);
507
516
  driftRun?.catch?.((err) => {
@@ -571,9 +580,9 @@ function getTargetActiveOrders(config, side) {
571
580
  * window = bottom slots = floor edge) makes the edge pick land on window
572
581
  * members and the count reads N/N with zero dedicated reserves, so the
573
582
  * 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
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
577
586
  * @returns {number|null} Live reserve count, or null when unclassifiable
578
587
  */
579
588
  function countLiveReserveOrders(manager, config, type) {
@@ -679,10 +688,12 @@ function getTargetedSyncReason(bot) {
679
688
  if (drift && drift.isValid === false) {
680
689
  return { reason: `fund drift: ${drift.reason}`, targetBuy, targetSell, liveBuy, liveSell, drift };
681
690
  }
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.
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.
686
697
  if (bot._spreadFundsExhausted === true) {
687
698
  return { reason: 'spread correction had no free funds', targetBuy, targetSell, liveBuy, liveSell, drift };
688
699
  }
@@ -716,6 +727,16 @@ async function maybeRunTargetedDriftReconciliation(bot, context) {
716
727
  bot._warn(`[TARGETED-SYNC] Chain sync failed during ${context}, skipping reconciliation`);
717
728
  return false;
718
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;
719
740
  const remaining = getTargetedSyncReason(bot);
720
741
  const unmatchedCount = Number(syncResult?.unmatchedChainOrders?.length || 0);
721
742
  if (remaining || unmatchedCount > 0) {
@@ -750,7 +771,7 @@ async function maybeRunTargetedDriftReconciliation(bot, context) {
750
771
  * Delegates to the canonical launcher/adapter_requirement helper so the
751
772
  * fingerprint is semantic (AMA-relevant changes only) and identical to the
752
773
  * unlock wrapper watchdog's view of the same file.
753
- * @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
754
775
  */
755
776
  function loadBotsConfigSnapshot() {
756
777
  return readAdapterRequirement(PROFILES_BOTS_FILE);
@@ -853,9 +874,9 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
853
874
  // fingerprints, retry next tick.
854
875
  let snapshot = null;
855
876
  try {
856
- snapshot = typeof bot._loadBotsConfigSnapshot === 'function'
877
+ snapshot = (typeof bot._loadBotsConfigSnapshot === 'function'
857
878
  ? await bot._loadBotsConfigSnapshot()
858
- : loadBotsConfigSnapshot();
879
+ : loadBotsConfigSnapshot());
859
880
  }
860
881
  catch (err) {
861
882
  bot._warn(`Ignoring unreadable bots.json during ${context}; keeping previous market adapter state.`);
@@ -897,8 +918,9 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
897
918
  // ?? (not ||): the semantic fingerprint is legitimately '' when no
898
919
  // active AMA bot exists, and '' must compare equal to a stored ''.
899
920
  const previousFingerprint = bot._marketAdapterWatchdogFingerprint ?? null;
900
- const changed = snapshot.fingerprint !== previousFingerprint;
901
- bot._marketAdapterWatchdogFingerprint = snapshot.fingerprint;
921
+ const fingerprint = snapshot.fingerprint;
922
+ const changed = fingerprint !== previousFingerprint;
923
+ bot._marketAdapterWatchdogFingerprint = fingerprint;
902
924
  if (changed) {
903
925
  bot._log(`Detected bots.json changes during ${context}; re-evaluating market adapter requirements.`);
904
926
  }
@@ -953,9 +975,10 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
953
975
  }
954
976
  // Cross-reference config-active bots against actually running PM2 processes
955
977
  // so we don't start the adapter for configured AMA bots that aren't running.
978
+ const activeBots = (snapshot.activeBots ?? []);
956
979
  const runningActiveBots = pm2QueryFailed
957
- ? snapshot.activeBots
958
- : snapshot.activeBots.filter((b) => processNames.includes(b.name));
980
+ ? activeBots
981
+ : activeBots.filter((b) => processNames.includes(String(b.name)));
959
982
  const needsAdapterForRunningBots = runningActiveBots.some(usesAmaGridPrice);
960
983
  if (!snapshot.exists || !needsAdapterForRunningBots) {
961
984
  const shouldStop = pm2QueryFailed || processNames.includes(MARKET_ADAPTER_APP_NAME);
@@ -1021,7 +1044,7 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
1021
1044
  * Applies live dynamic weights if the bot is whitelisted and weights are ready.
1022
1045
  * @param {import('./dexbot_class.js').DEXBot} bot
1023
1046
  * @param {string} [context='runtime'] - Context label for logging
1024
- * @returns {any}
1047
+ * @returns {unknown}
1025
1048
  */
1026
1049
  function refreshDynamicWeightDistribution(bot, context = 'runtime') {
1027
1050
  const baseWeights = cloneWeightDistribution(bot._baseWeightDistribution, bot.config?.weightDistribution || bot.manager?.config?.weightDistribution);
@@ -1077,7 +1100,7 @@ function refreshDynamicWeightDistribution(bot, context = 'runtime') {
1077
1100
  * Read and parse a trigger file's metadata payload.
1078
1101
  * Determines whether the trigger originated from the market adapter or was manual.
1079
1102
  * @param {string} triggerFile - Path to the trigger file
1080
- * @returns {any} Parsed trigger metadata
1103
+ * @returns {unknown} Parsed trigger metadata
1081
1104
  */
1082
1105
  function readTriggerMetadata(triggerFile) {
1083
1106
  const manualTriggerMetadata = (payload = null) => ({
@@ -1111,7 +1134,7 @@ function readTriggerMetadata(triggerFile) {
1111
1134
  * Build grid resync metadata from a reason string.
1112
1135
  * Maps known reason strings to structured metadata with refresh flags.
1113
1136
  * @param {string} reason - Resync reason identifier (e.g. 'manual_grid_resync', 'rms_structural_grid_resync')
1114
- * @returns {any}
1137
+ * @returns {unknown}
1115
1138
  */
1116
1139
  function buildGridResyncMetadata(reason) {
1117
1140
  const resetSource = String(reason || '').trim() || 'dexbot_grid_resync';
@@ -1136,12 +1159,12 @@ function buildGridResyncMetadata(reason) {
1136
1159
  /**
1137
1160
  * Build grid resync options from a reason string or metadata object.
1138
1161
  * @param {string|any} reasonOrMetadata - Reason string or metadata object
1139
- * @returns {any}
1162
+ * @returns {unknown}
1140
1163
  */
1141
1164
  function buildGridResyncOptions(reasonOrMetadata) {
1142
- const metadata = typeof reasonOrMetadata === 'string'
1165
+ const metadata = (typeof reasonOrMetadata === 'string'
1143
1166
  ? buildGridResyncMetadata(reasonOrMetadata)
1144
- : reasonOrMetadata;
1167
+ : reasonOrMetadata);
1145
1168
  return {
1146
1169
  refreshCenterPrice: !!metadata?.shouldRefreshCenterPrice,
1147
1170
  centerRefreshContext: metadata?.centerRefreshContext,
@@ -1164,16 +1187,17 @@ function promoteAmaCenterSnapshotForGridReset(botKey) {
1164
1187
  const snapshotPath = path.join(PATHS.ORDERS_DIR, `${botKey}.dynamicgrid.json`);
1165
1188
  try {
1166
1189
  const result = updateDynamicGridSnapshotSync(snapshotPath, (snapshot) => {
1167
- const amaCenterPrice = Number(snapshot?.amaCenterPrice);
1190
+ const snap = snapshot;
1191
+ const amaCenterPrice = Number(snap?.amaCenterPrice);
1168
1192
  if (!Number.isFinite(amaCenterPrice) || amaCenterPrice <= 0) {
1169
1193
  return { ok: false, write: false };
1170
1194
  }
1171
- const currentCenterPrice = Number(snapshot?.gridCenterPrice ?? snapshot?.centerPrice);
1195
+ const currentCenterPrice = Number(snap?.gridCenterPrice ?? snap?.centerPrice);
1172
1196
  if (Number.isFinite(currentCenterPrice) && currentCenterPrice === amaCenterPrice) {
1173
1197
  return { write: false };
1174
1198
  }
1175
1199
  return {
1176
- ...snapshot,
1200
+ ...snap,
1177
1201
  gridCenterPrice: amaCenterPrice,
1178
1202
  centerPrice: amaCenterPrice,
1179
1203
  updatedAt: nowIso(),
@@ -1201,12 +1225,13 @@ function updateBotGridResetMetadata(botKey, options = {}) {
1201
1225
  const snapshotPath = path.join(PATHS.ORDERS_DIR, `${botKey}.dynamicgrid.json`);
1202
1226
  try {
1203
1227
  const result = updateDynamicGridSnapshotSync(snapshotPath, (snapshot) => {
1204
- const gridCenterPrice = Number(snapshot?.gridCenterPrice ?? snapshot?.centerPrice);
1228
+ const snap = snapshot;
1229
+ const gridCenterPrice = Number(snap?.gridCenterPrice ?? snap?.centerPrice);
1205
1230
  if (!Number.isFinite(gridCenterPrice) || gridCenterPrice <= 0) {
1206
1231
  return { ok: false, write: false };
1207
1232
  }
1208
1233
  return {
1209
- ...snapshot,
1234
+ ...snap,
1210
1235
  gridCenterPrice,
1211
1236
  centerPrice: gridCenterPrice,
1212
1237
  lastGridResetAt: resetAt,
@@ -1224,7 +1249,7 @@ function updateBotGridResetMetadata(botKey, options = {}) {
1224
1249
  * Perform a full grid resync: reload config, optionally refresh center price,
1225
1250
  * recalculate the grid, persist, and record reset metadata.
1226
1251
  * @param {import('./dexbot_class.js').DEXBot} bot
1227
- * @param {any} [options] - Grid resync options
1252
+ * @param {unknown} [options] - Grid resync options
1228
1253
  * @param {boolean} [options.skipIdle=false] - Skip the idle-cooldown deferral
1229
1254
  * @returns {Promise<boolean>} True if resync succeeded
1230
1255
  */
@@ -1862,12 +1887,12 @@ function setupBlockchainFetchInterval(bot) {
1862
1887
  // from the window (then re-create them as duplicates).
1863
1888
  // Defer the sync to a clean read; fills are still
1864
1889
  // caught by subscription events and the next cycle.
1865
- chainOpenOrders = (typeof bot._readOpenOrdersHook === 'function')
1890
+ chainOpenOrders = ((typeof bot._readOpenOrdersHook === 'function')
1866
1891
  ? await bot._readOpenOrdersHook()
1867
1892
  : await readOpenOrdersGuarded(chainOrders, bot.accountId, {
1868
1893
  log: (message, level) => bot._log(message, level),
1869
1894
  label: 'PERIODIC-SYNC',
1870
- });
1895
+ }));
1871
1896
  if (chainOpenOrders !== null) {
1872
1897
  const syncResult = await bot.manager.synchronizeWithChain(chainOpenOrders, 'periodicBlockchainFetch');
1873
1898
  if (syncResult.filledOrders && syncResult.filledOrders.length > 0) {
@@ -2051,7 +2076,7 @@ function isOrderDoesNotExistError(message, orderId) {
2051
2076
  * manager._broadcastingStartedAt on every holder, so its age stays small;
2052
2077
  * a frozen timestamp ages past BROADCAST_STALE_CLEAR_MS and we let the tick
2053
2078
  * through so maintenance can hard-reset the flag.
2054
- * @param {any} bot
2079
+ * @param {unknown} bot
2055
2080
  * @returns {boolean} true when the caller should skip this tick
2056
2081
  */
2057
2082
  function shouldDeferMaintenanceForBroadcast(bot) {
@@ -2079,7 +2104,7 @@ function shouldDeferMaintenanceForBroadcast(bot) {
2079
2104
  * any such section visible: when the live hold crosses
2080
2105
  * TIMING.GRID_LOCK_HOLD_WARN_MS it emits a rate-limited warn. Called from the
2081
2106
  * maintenance tick so holds outside a broadcast region are observed too.
2082
- * @param {any} bot
2107
+ * @param {unknown} bot
2083
2108
  * @returns {number} Observed hold duration in ms (0 when not held)
2084
2109
  */
2085
2110
  function checkGridLockHoldDuration(bot) {
@@ -2124,7 +2149,7 @@ function getMaintenanceIdleDelayMs(ctx) {
2124
2149
  : TIMING.BLOCKCHAIN_SETTLE_DELAY_MS;
2125
2150
  if (settleDelayMs <= 0)
2126
2151
  return 0;
2127
- if (ctx?._incomingFillQueue?.length > 0)
2152
+ if ((ctx?._incomingFillQueue?.length ?? 0) > 0)
2128
2153
  return settleDelayMs;
2129
2154
  const lastActivityAt = Number(ctx?._lastGridActivityAt || 0);
2130
2155
  if (!Number.isFinite(lastActivityAt) || lastActivityAt <= 0)
@@ -2150,9 +2175,9 @@ function scheduleMaintenanceAfterIdle(ctx, context, options = {}) {
2150
2175
  ctx._maintenanceIdleTimer = null;
2151
2176
  if (ctx._shuttingDown)
2152
2177
  return;
2153
- ctx._runGridMaintenance(context, timerOptions)
2154
- .catch((err) => {
2155
- 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)}`);
2156
2181
  if (ctx.manager) {
2157
2182
  ctx.manager._recoveryState = { ...ctx.manager._recoveryState, lastFailureAt: Date.now() };
2158
2183
  }
@@ -2162,7 +2187,7 @@ function scheduleMaintenanceAfterIdle(ctx, context, options = {}) {
2162
2187
  /**
2163
2188
  * Schedule a deferred grid resync after idle delay elapses.
2164
2189
  * @param {Object} ctx - Bot context
2165
- * @param {any} [options] - Grid resync options
2190
+ * @param {unknown} [options] - Grid resync options
2166
2191
  */
2167
2192
  function scheduleDeferredGridResync(ctx, options = {}) {
2168
2193
  if (!ctx ||
@@ -2185,17 +2210,17 @@ function scheduleDeferredGridResync(ctx, options = {}) {
2185
2210
  return;
2186
2211
  if (triggerFileWasPresent && !storage.exists(ctx.triggerFile))
2187
2212
  return;
2188
- ctx.manager._fillProcessingLock.acquire(async () => {
2189
- const ok = await ctx._performGridResync(options);
2213
+ ctx.manager?._fillProcessingLock?.acquire?.(async () => {
2214
+ const ok = await ctx._performGridResync?.(options);
2190
2215
  if (!ok && !ctx._shuttingDown) {
2191
2216
  const curIdleMs = getMaintenanceIdleDelayMs(ctx);
2192
2217
  const reason = curIdleMs > 0
2193
2218
  ? `idle cooldown (${Math.ceil(curIdleMs / TIMING.MILLISECONDS_PER_SECOND)}s)`
2194
2219
  : 'grid resync rejected or failed';
2195
- ctx._warn(`Deferred trigger reset blocked: ${reason}; retaining existing grid state.`);
2220
+ ctx._warn?.(`Deferred trigger reset blocked: ${reason}; retaining existing grid state.`);
2196
2221
  }
2197
- }).catch((err) => {
2198
- ctx._warn(`Deferred trigger reset lock error: ${getErrorMessage(err)}`);
2222
+ })?.catch((err) => {
2223
+ ctx._warn?.(`Deferred trigger reset lock error: ${getErrorMessage(err)}`);
2199
2224
  if (ctx.manager) {
2200
2225
  ctx.manager._recoveryState = { ...ctx.manager._recoveryState, lastFailureAt: Date.now() };
2201
2226
  }
@@ -2478,7 +2503,7 @@ async function executeMaintenanceLogic(bot, context) {
2478
2503
  * dedupe concurrent requests; the re-center moves the boundary, which clears
2479
2504
  * any held-plan signature). Resets whenever the spread heals or a correction
2480
2505
  * places orders.
2481
- * @param {any} bot
2506
+ * @param {unknown} bot
2482
2507
  * @param {boolean} spreadChecked - Whether the spread check ran this tick
2483
2508
  * @param {number} ordersPlaced - Correction orders placed this tick
2484
2509
  * @returns {{staleMs: number, escalated: boolean}}
@@ -2564,9 +2589,9 @@ async function cancelOrderDeferredOnUncertain(bot, order) {
2564
2589
  // Test seam: compiled ESM exports cannot be monkey-patched, so tests
2565
2590
  // may override cancellation through this bot-level hook.
2566
2591
  if (typeof bot._submitCancelOrder === 'function') {
2567
- return await bot._submitCancelOrder(order.orderId);
2592
+ return await bot._submitCancelOrder(String(order.orderId));
2568
2593
  }
2569
- return await chainOrders.cancelOrder(bot.account, bot.privateKey, order.orderId);
2594
+ return await chainOrders.cancelOrder(bot.account, bot.privateKey, String(order.orderId));
2570
2595
  }
2571
2596
  catch (err) {
2572
2597
  if (err instanceof BroadcastUncertainError) {
@@ -2724,7 +2749,7 @@ async function checkBtsBalanceAndAcquire(bot) {
2724
2749
  const minBtsVal = calculateOrderCreationFees(bot.config.assetA, bot.config.assetB, totalTarget, btsReservationMultiplier);
2725
2750
  if (minBtsVal <= 0)
2726
2751
  return;
2727
- 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;
2728
2753
  const btsFree = bot.manager.btsBalance.free || 0;
2729
2754
  const btsAcquireThreshold = bot.config?.feeParams?.BTS_ACQUIRE_THRESHOLD;
2730
2755
  const triggerAt = effectiveMin * btsAcquireThreshold;
@@ -3059,14 +3084,14 @@ function wireStructuralGridResyncRequest(bot) {
3059
3084
  bot._recoverySyncInFlight = (bot._recoverySyncInFlight || 0) + 1;
3060
3085
  let resetResult;
3061
3086
  try {
3062
- resetResult = await bot.requestGridReset('rms_structural_grid_resync', {
3087
+ resetResult = await (bot.requestGridReset('rms_structural_grid_resync', {
3063
3088
  refreshCenterPrice: false,
3064
3089
  // Structural resync is a chain-read/rebuild; do not let a
3065
3090
  // fill storm starve it behind the idle cooldown or the
3066
3091
  // fill-processing lock.
3067
3092
  skipIdle: true,
3068
3093
  skipFillLock: true,
3069
- });
3094
+ }));
3070
3095
  }
3071
3096
  finally {
3072
3097
  bot._recoverySyncInFlight = Math.max(0, (bot._recoverySyncInFlight || 0) - 1);
@@ -3215,7 +3240,7 @@ async function syncOpenOrdersAndProcessFillsImpl(bot, tag) {
3215
3240
  return { syncResult: null, aborted: true, hasUnmatched: -1, openOrders: null };
3216
3241
  }
3217
3242
  }
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 };
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 };
3219
3244
  export default {
3220
3245
  loadBotsConfigSnapshot,
3221
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