dexbot 1.6.6 → 1.6.8

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 (632) hide show
  1. package/CHANGELOG.md +89 -1
  2. package/README.md +8 -5
  3. package/analysis/README.md +2 -3
  4. package/analysis/tradingview/README.md +78 -1
  5. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/tradingview/analyze_tradingview.d.ts +4 -0
  10. package/dist/analysis/tradingview/analyze_tradingview.js +55 -0
  11. package/dist/analysis/tradingview/grid_reset_config.d.ts +61 -0
  12. package/dist/analysis/tradingview/grid_reset_config.js +235 -0
  13. package/dist/analysis/tradingview/grid_reset_sim.d.ts +67 -0
  14. package/dist/analysis/tradingview/grid_reset_sim.js +307 -0
  15. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +419 -3
  16. package/dist/dexbot.js +44 -15
  17. package/dist/market_adapter/core/market_adapter_service.js +14 -2
  18. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +8 -1
  19. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +5 -1
  20. package/dist/market_adapter/inputs/window_cache.d.ts +97 -19
  21. package/dist/market_adapter/inputs/window_cache.js +302 -48
  22. package/dist/market_adapter/market_adapter.d.ts +8 -1
  23. package/dist/market_adapter/market_adapter.js +22 -4
  24. package/dist/modules/account_bots.js +20 -9
  25. package/dist/modules/account_orders.d.ts +44 -4
  26. package/dist/modules/account_orders.js +104 -7
  27. package/dist/modules/bitshares-native/chain_client.d.ts +10 -0
  28. package/dist/modules/bitshares-native/chain_client.js +197 -28
  29. package/dist/modules/bitshares-native/subscriptions.js +312 -10
  30. package/dist/modules/bitshares-native/transport.d.ts +1 -0
  31. package/dist/modules/bitshares-native/transport.js +97 -3
  32. package/dist/modules/bitshares_client.d.ts +20 -0
  33. package/dist/modules/bitshares_client.js +29 -0
  34. package/dist/modules/bot_settings.js +10 -1
  35. package/dist/modules/chain_keys.d.ts +37 -22
  36. package/dist/modules/chain_keys.js +145 -44
  37. package/dist/modules/cli_start_onboarding.d.ts +10 -0
  38. package/dist/modules/cli_start_onboarding.js +15 -0
  39. package/dist/modules/cli_start_output.d.ts +6 -0
  40. package/dist/modules/cli_start_output.js +8 -0
  41. package/dist/modules/config.d.ts +1 -0
  42. package/dist/modules/config.js +1 -0
  43. package/dist/modules/constants.d.ts +23 -2
  44. package/dist/modules/constants.js +196 -15
  45. package/dist/modules/dexbot_class.d.ts +6 -76
  46. package/dist/modules/dexbot_class.js +0 -32
  47. package/dist/modules/dexbot_cow_runtime.d.ts +3 -58
  48. package/dist/modules/dexbot_cow_runtime.js +53 -96
  49. package/dist/modules/dexbot_fill_runtime.d.ts +6 -1
  50. package/dist/modules/dexbot_fill_runtime.js +22 -3
  51. package/dist/modules/dexbot_maintenance_runtime.d.ts +38 -1
  52. package/dist/modules/dexbot_maintenance_runtime.js +103 -11
  53. package/dist/modules/dexbot_startup_runtime.js +73 -20
  54. package/dist/modules/dexbot_state_recovery.d.ts +6 -0
  55. package/dist/modules/dexbot_state_recovery.js +34 -1
  56. package/dist/modules/order/async_lock.d.ts +8 -0
  57. package/dist/modules/order/async_lock.js +15 -0
  58. package/dist/modules/order/genesis_policy.d.ts +162 -0
  59. package/dist/modules/order/genesis_policy.js +267 -0
  60. package/dist/modules/order/grid.js +109 -135
  61. package/dist/modules/order/grid_reconcile.d.ts +9 -0
  62. package/dist/modules/order/grid_reconcile.js +13 -4
  63. package/dist/modules/order/grid_reconcile_internal.js +13 -2
  64. package/dist/modules/order/logger.d.ts +12 -2
  65. package/dist/modules/order/logger.js +29 -7
  66. package/dist/modules/order/manager.d.ts +53 -0
  67. package/dist/modules/order/manager.js +86 -25
  68. package/dist/modules/order/sync_engine.d.ts +19 -0
  69. package/dist/modules/order/sync_engine.js +284 -344
  70. package/dist/modules/order/utils/math.d.ts +22 -1
  71. package/dist/modules/order/utils/math.js +64 -1
  72. package/dist/modules/order/utils/order.d.ts +43 -58
  73. package/dist/modules/order/utils/order.js +302 -194
  74. package/dist/modules/order/utils/system.d.ts +97 -0
  75. package/dist/modules/order/utils/system.js +282 -3
  76. package/dist/modules/paths.d.ts +8 -1
  77. package/dist/modules/paths.js +11 -3
  78. package/dist/modules/utils/text_width.d.ts +19 -0
  79. package/dist/modules/utils/text_width.js +97 -0
  80. package/dist/modules/version_notice.d.ts +165 -0
  81. package/dist/modules/version_notice.js +364 -0
  82. package/dist/pm2.js +104 -18
  83. package/dist/scripts/update.js +62 -13
  84. package/dist/unlock.d.ts +14 -2
  85. package/dist/unlock.js +101 -4
  86. package/docs/BITSHARES_ONBOARDING.md +8 -1
  87. package/docs/COW_INVARIANTS.md +11 -2
  88. package/docs/CREDENTIAL_SECURITY.md +26 -0
  89. package/docs/DEXBOT_COMPARISON.md +4 -4
  90. package/docs/EVOLUTION.md +20 -18
  91. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  92. package/docs/GRID_PRICE_INVARIANT.md +204 -31
  93. package/docs/GRID_RECALCULATION.md +12 -0
  94. package/docs/LOGGING.md +17 -2
  95. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +6 -7
  96. package/docs/README.md +3 -1
  97. package/docs/WORKFLOW.md +16 -5
  98. package/market_adapter/README.md +1 -1
  99. package/modules/README.md +18 -1
  100. package/package.json +14 -6
  101. package/scripts/README.md +28 -2
  102. package/scripts/clear-all.sh +13 -4
  103. package/scripts/clear-logs.sh +13 -4
  104. package/scripts/clear-market-adapter.sh +6 -0
  105. package/scripts/clear-orders.sh +5 -0
  106. package/scripts/lib/dexbot-paths.sh +108 -0
  107. package/tests/README.md +11 -3
  108. package/analysis/account_resolver.ts +0 -161
  109. package/analysis/ama_fitting/analyze_ama_price_changes.ts +0 -155
  110. package/analysis/ama_fitting/analyze_lambda_vs_slow.ts +0 -404
  111. package/analysis/ama_fitting/calibrate_convergence_er.ts +0 -201
  112. package/analysis/ama_fitting/fetch_lp_candles.ts +0 -184
  113. package/analysis/ama_fitting/generate_unified_comparison_chart.ts +0 -232
  114. package/analysis/ama_fitting/optimizer_high_resolution.ts +0 -802
  115. package/analysis/analyze_dynamic_weight.ts +0 -243
  116. package/analysis/analyze_kalman.ts +0 -157
  117. package/analysis/analyze_regime.ts +0 -158
  118. package/analysis/analyze_regime_windows.ts +0 -470
  119. package/analysis/analyze_risk_profile.ts +0 -199
  120. package/analysis/analyze_trade_heatmap.ts +0 -362
  121. package/analysis/analyze_volatility.ts +0 -182
  122. package/analysis/bot_fitting/backtest_ama_sweep.ts +0 -934
  123. package/analysis/bot_fitting/backtest_bot_fitting.ts +0 -861
  124. package/analysis/bot_fitting/shared_utils.ts +0 -52
  125. package/analysis/bot_key_utils.ts +0 -426
  126. package/analysis/bot_usage/discover_bot_accounts.ts +0 -635
  127. package/analysis/bot_usage/kibana_bot_queries.ts +0 -211
  128. package/analysis/chain_pool.ts +0 -47
  129. package/analysis/chart_css.ts +0 -62
  130. package/analysis/chart_ui.ts +0 -105
  131. package/analysis/chart_utils.ts +0 -210
  132. package/analysis/fills_source.ts +0 -228
  133. package/analysis/grid_correction_check.ts +0 -786
  134. package/analysis/math_utils.ts +0 -53
  135. package/analysis/price_sources.ts +0 -136
  136. package/analysis/resolve_bot_accounts.ts +0 -199
  137. package/analysis/resolve_source.ts +0 -99
  138. package/analysis/results/ama_sweep_results_lp_pool_133_1h.json +0 -2455
  139. package/analysis/results/bot_fitting_results_lp_pool_133_1h.json +0 -218
  140. package/analysis/trade_profitability.ts +0 -1335
  141. package/analysis/tradingview/analyze_tradingview.ts +0 -280
  142. package/analysis/tradingview/h-bts_tradingview.html +0 -1570
  143. package/analysis/tradingview/t-bts_tradingview.html +0 -1570
  144. package/analysis/tradingview/tradingview_uplot_chart_generator.ts +0 -3268
  145. package/analysis/trend_detection/dynamic_weight_chart_generator.ts +0 -1481
  146. package/analysis/trend_detection/hurst_analyzer.ts +0 -7
  147. package/analysis/trend_detection/kalman_chart_generator.ts +0 -398
  148. package/analysis/trend_detection/kalman_trend_analyzer.ts +0 -9
  149. package/analysis/trend_detection/kalman_velocity_smoothing.ts +0 -7
  150. package/analysis/trend_detection/package.json +0 -23
  151. package/analysis/trend_detection/permutation_entropy_analyzer.ts +0 -7
  152. package/analysis/trend_detection/regime_chart_generator.ts +0 -338
  153. package/analysis/trend_detection/tests/test_kalman_trend.ts +0 -153
  154. package/analysis/trend_detection/tests/test_kalman_velocity_smoothing.ts +0 -64
  155. package/analysis/trend_detection/volatility_chart_generator.ts +0 -654
  156. package/analysis/tsconfig.json +0 -29
  157. package/claw/tests/package.json +0 -3
  158. package/claw/tests/test_claw_bridge.ts +0 -570
  159. package/claw/tests/test_claw_catalog_and_credentials.ts +0 -156
  160. package/claw/tests/test_claw_chain_layer.ts +0 -739
  161. package/claw/tests/test_claw_data_flow.ts +0 -525
  162. package/claw/tests/test_claw_domain_logic.ts +0 -471
  163. package/claw/tests/test_claw_manifest_and_matrix.ts +0 -222
  164. package/claw/tests/test_claw_mcp_transport.ts +0 -243
  165. package/claw/tests/test_claw_regressions.ts +0 -711
  166. package/claw/tests/test_claw_skill_generation.ts +0 -103
  167. package/claw/tests/test_claw_state_store.ts +0 -44
  168. package/claw/tests/test_dexbot_profiles.ts +0 -654
  169. package/claw/tests/test_memu_bridge.ts +0 -189
  170. package/claw/tests/test_nullclaw_tmp_integration.ts +0 -57
  171. package/claw/tests/test_position_health.ts +0 -343
  172. package/claw/tests/test_position_manager.ts +0 -429
  173. package/claw/tests/test_position_manager_watch_health.ts +0 -100
  174. package/claw/tests/test_short_mpa_strategy.ts +0 -232
  175. package/dist/analysis/account_resolver.d.ts.map +0 -1
  176. package/dist/analysis/account_resolver.js.map +0 -1
  177. package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts.map +0 -1
  178. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js.map +0 -1
  179. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts.map +0 -1
  180. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +0 -1
  181. package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts.map +0 -1
  182. package/dist/analysis/ama_fitting/calibrate_convergence_er.js.map +0 -1
  183. package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts.map +0 -1
  184. package/dist/analysis/ama_fitting/fetch_lp_candles.js.map +0 -1
  185. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts.map +0 -1
  186. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js.map +0 -1
  187. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts.map +0 -1
  188. package/dist/analysis/ama_fitting/optimizer_high_resolution.js.map +0 -1
  189. package/dist/analysis/analyze_dynamic_weight.d.ts.map +0 -1
  190. package/dist/analysis/analyze_dynamic_weight.js.map +0 -1
  191. package/dist/analysis/analyze_kalman.d.ts.map +0 -1
  192. package/dist/analysis/analyze_kalman.js.map +0 -1
  193. package/dist/analysis/analyze_regime.d.ts.map +0 -1
  194. package/dist/analysis/analyze_regime.js.map +0 -1
  195. package/dist/analysis/analyze_regime_windows.d.ts.map +0 -1
  196. package/dist/analysis/analyze_regime_windows.js.map +0 -1
  197. package/dist/analysis/analyze_risk_profile.d.ts.map +0 -1
  198. package/dist/analysis/analyze_risk_profile.js.map +0 -1
  199. package/dist/analysis/analyze_trade_heatmap.d.ts.map +0 -1
  200. package/dist/analysis/analyze_trade_heatmap.js.map +0 -1
  201. package/dist/analysis/analyze_volatility.d.ts.map +0 -1
  202. package/dist/analysis/analyze_volatility.js.map +0 -1
  203. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts.map +0 -1
  204. package/dist/analysis/bot_fitting/backtest_ama_sweep.js.map +0 -1
  205. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts.map +0 -1
  206. package/dist/analysis/bot_fitting/backtest_bot_fitting.js.map +0 -1
  207. package/dist/analysis/bot_fitting/shared_utils.d.ts.map +0 -1
  208. package/dist/analysis/bot_fitting/shared_utils.js.map +0 -1
  209. package/dist/analysis/bot_key_utils.d.ts.map +0 -1
  210. package/dist/analysis/bot_key_utils.js.map +0 -1
  211. package/dist/analysis/bot_usage/discover_bot_accounts.d.ts.map +0 -1
  212. package/dist/analysis/bot_usage/discover_bot_accounts.js.map +0 -1
  213. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +0 -1
  214. package/dist/analysis/bot_usage/kibana_bot_queries.js.map +0 -1
  215. package/dist/analysis/chain_pool.d.ts.map +0 -1
  216. package/dist/analysis/chain_pool.js.map +0 -1
  217. package/dist/analysis/chart_css.d.ts.map +0 -1
  218. package/dist/analysis/chart_css.js.map +0 -1
  219. package/dist/analysis/chart_ui.d.ts.map +0 -1
  220. package/dist/analysis/chart_ui.js.map +0 -1
  221. package/dist/analysis/chart_utils.d.ts.map +0 -1
  222. package/dist/analysis/chart_utils.js.map +0 -1
  223. package/dist/analysis/fills_source.d.ts.map +0 -1
  224. package/dist/analysis/fills_source.js.map +0 -1
  225. package/dist/analysis/grid_correction_check.d.ts.map +0 -1
  226. package/dist/analysis/grid_correction_check.js.map +0 -1
  227. package/dist/analysis/math_utils.d.ts.map +0 -1
  228. package/dist/analysis/math_utils.js.map +0 -1
  229. package/dist/analysis/price_sources.d.ts.map +0 -1
  230. package/dist/analysis/price_sources.js.map +0 -1
  231. package/dist/analysis/resolve_bot_accounts.d.ts.map +0 -1
  232. package/dist/analysis/resolve_bot_accounts.js.map +0 -1
  233. package/dist/analysis/resolve_source.d.ts.map +0 -1
  234. package/dist/analysis/resolve_source.js.map +0 -1
  235. package/dist/analysis/trade_profitability.d.ts.map +0 -1
  236. package/dist/analysis/trade_profitability.js.map +0 -1
  237. package/dist/analysis/tradingview/analyze_tradingview.d.ts.map +0 -1
  238. package/dist/analysis/tradingview/analyze_tradingview.js.map +0 -1
  239. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts.map +0 -1
  240. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js.map +0 -1
  241. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +0 -1
  242. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +0 -1
  243. package/dist/analysis/trend_detection/hurst_analyzer.d.ts.map +0 -1
  244. package/dist/analysis/trend_detection/hurst_analyzer.js.map +0 -1
  245. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts.map +0 -1
  246. package/dist/analysis/trend_detection/kalman_chart_generator.js.map +0 -1
  247. package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts.map +0 -1
  248. package/dist/analysis/trend_detection/kalman_trend_analyzer.js.map +0 -1
  249. package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts.map +0 -1
  250. package/dist/analysis/trend_detection/kalman_velocity_smoothing.js.map +0 -1
  251. package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts.map +0 -1
  252. package/dist/analysis/trend_detection/permutation_entropy_analyzer.js.map +0 -1
  253. package/dist/analysis/trend_detection/regime_chart_generator.d.ts.map +0 -1
  254. package/dist/analysis/trend_detection/regime_chart_generator.js.map +0 -1
  255. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts +0 -2
  256. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts.map +0 -1
  257. package/dist/analysis/trend_detection/tests/test_kalman_trend.js +0 -128
  258. package/dist/analysis/trend_detection/tests/test_kalman_trend.js.map +0 -1
  259. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts +0 -2
  260. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts.map +0 -1
  261. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js +0 -37
  262. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js.map +0 -1
  263. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts.map +0 -1
  264. package/dist/analysis/trend_detection/volatility_chart_generator.js.map +0 -1
  265. package/dist/bot.d.ts.map +0 -1
  266. package/dist/bot.js.map +0 -1
  267. package/dist/credential-daemon.d.ts.map +0 -1
  268. package/dist/credential-daemon.js.map +0 -1
  269. package/dist/dexbot.d.ts.map +0 -1
  270. package/dist/dexbot.js.map +0 -1
  271. package/dist/market_adapter/ama_signal_runner.d.ts.map +0 -1
  272. package/dist/market_adapter/ama_signal_runner.js.map +0 -1
  273. package/dist/market_adapter/candle_utils.d.ts.map +0 -1
  274. package/dist/market_adapter/candle_utils.js.map +0 -1
  275. package/dist/market_adapter/core/asymmetric_bounds.d.ts.map +0 -1
  276. package/dist/market_adapter/core/asymmetric_bounds.js.map +0 -1
  277. package/dist/market_adapter/core/config_normalizers.d.ts.map +0 -1
  278. package/dist/market_adapter/core/config_normalizers.js.map +0 -1
  279. package/dist/market_adapter/core/kibana_candles.d.ts.map +0 -1
  280. package/dist/market_adapter/core/kibana_candles.js.map +0 -1
  281. package/dist/market_adapter/core/kibana_client.d.ts.map +0 -1
  282. package/dist/market_adapter/core/kibana_client.js.map +0 -1
  283. package/dist/market_adapter/core/kibana_market_candles.d.ts.map +0 -1
  284. package/dist/market_adapter/core/kibana_market_candles.js.map +0 -1
  285. package/dist/market_adapter/core/market_adapter_service.d.ts.map +0 -1
  286. package/dist/market_adapter/core/market_adapter_service.js.map +0 -1
  287. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts.map +0 -1
  288. package/dist/market_adapter/core/signals/hurst_analyzer.js.map +0 -1
  289. package/dist/market_adapter/core/signals/kalman_trend_analyzer.d.ts.map +0 -1
  290. package/dist/market_adapter/core/signals/kalman_trend_analyzer.js.map +0 -1
  291. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.d.ts.map +0 -1
  292. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.js.map +0 -1
  293. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts.map +0 -1
  294. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js.map +0 -1
  295. package/dist/market_adapter/core/strategies/ama.d.ts.map +0 -1
  296. package/dist/market_adapter/core/strategies/ama.js.map +0 -1
  297. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts.map +0 -1
  298. package/dist/market_adapter/core/strategies/ama_slope_model.js.map +0 -1
  299. package/dist/market_adapter/core/strategies/atr/calculator.d.ts.map +0 -1
  300. package/dist/market_adapter/core/strategies/atr/calculator.js.map +0 -1
  301. package/dist/market_adapter/core/strategies/collateral_manager.d.ts.map +0 -1
  302. package/dist/market_adapter/core/strategies/collateral_manager.js.map +0 -1
  303. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts.map +0 -1
  304. package/dist/market_adapter/core/strategies/dynamic_weight_series.js.map +0 -1
  305. package/dist/market_adapter/core/strategies/regime_gate.d.ts.map +0 -1
  306. package/dist/market_adapter/core/strategies/regime_gate.js.map +0 -1
  307. package/dist/market_adapter/core/strategies/regime_interp.d.ts.map +0 -1
  308. package/dist/market_adapter/core/strategies/regime_interp.js.map +0 -1
  309. package/dist/market_adapter/core/strategies/volatility_shift.d.ts.map +0 -1
  310. package/dist/market_adapter/core/strategies/volatility_shift.js.map +0 -1
  311. package/dist/market_adapter/inputs/fetch_book_data.d.ts.map +0 -1
  312. package/dist/market_adapter/inputs/fetch_book_data.js.map +0 -1
  313. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.d.ts.map +0 -1
  314. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js.map +0 -1
  315. package/dist/market_adapter/inputs/fetch_lp_data.d.ts.map +0 -1
  316. package/dist/market_adapter/inputs/fetch_lp_data.js.map +0 -1
  317. package/dist/market_adapter/inputs/kibana_feed_source.d.ts.map +0 -1
  318. package/dist/market_adapter/inputs/kibana_feed_source.js.map +0 -1
  319. package/dist/market_adapter/inputs/kibana_source.d.ts.map +0 -1
  320. package/dist/market_adapter/inputs/kibana_source.js.map +0 -1
  321. package/dist/market_adapter/inputs/window_cache.d.ts.map +0 -1
  322. package/dist/market_adapter/inputs/window_cache.js.map +0 -1
  323. package/dist/market_adapter/interval_utils.d.ts.map +0 -1
  324. package/dist/market_adapter/interval_utils.js.map +0 -1
  325. package/dist/market_adapter/log_format.d.ts.map +0 -1
  326. package/dist/market_adapter/log_format.js.map +0 -1
  327. package/dist/market_adapter/lp_chart_core.d.ts.map +0 -1
  328. package/dist/market_adapter/lp_chart_core.js.map +0 -1
  329. package/dist/market_adapter/lp_chart_runner.d.ts.map +0 -1
  330. package/dist/market_adapter/lp_chart_runner.js.map +0 -1
  331. package/dist/market_adapter/lp_chart_strategy_loader.d.ts.map +0 -1
  332. package/dist/market_adapter/lp_chart_strategy_loader.js.map +0 -1
  333. package/dist/market_adapter/market_adapter.d.ts.map +0 -1
  334. package/dist/market_adapter/market_adapter.js.map +0 -1
  335. package/dist/market_adapter/test_helpers.d.ts.map +0 -1
  336. package/dist/market_adapter/test_helpers.js.map +0 -1
  337. package/dist/market_adapter/utils/adapter_client.d.ts.map +0 -1
  338. package/dist/market_adapter/utils/adapter_client.js.map +0 -1
  339. package/dist/market_adapter/utils/atomic_write.d.ts.map +0 -1
  340. package/dist/market_adapter/utils/atomic_write.js.map +0 -1
  341. package/dist/market_adapter/utils/chain.d.ts.map +0 -1
  342. package/dist/market_adapter/utils/chain.js.map +0 -1
  343. package/dist/market_adapter/utils/data_discovery.d.ts.map +0 -1
  344. package/dist/market_adapter/utils/data_discovery.js.map +0 -1
  345. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts.map +0 -1
  346. package/dist/market_adapter/utils/dynamic_grid_snapshot.js.map +0 -1
  347. package/dist/market_adapter/utils/file_lock.d.ts.map +0 -1
  348. package/dist/market_adapter/utils/file_lock.js.map +0 -1
  349. package/dist/market_adapter/utils/native_history.d.ts.map +0 -1
  350. package/dist/market_adapter/utils/native_history.js.map +0 -1
  351. package/dist/modules/account_bots.d.ts.map +0 -1
  352. package/dist/modules/account_bots.js.map +0 -1
  353. package/dist/modules/account_orders.d.ts.map +0 -1
  354. package/dist/modules/account_orders.js.map +0 -1
  355. package/dist/modules/authority_resolver.d.ts.map +0 -1
  356. package/dist/modules/authority_resolver.js.map +0 -1
  357. package/dist/modules/bitshares-native/chain_client.d.ts.map +0 -1
  358. package/dist/modules/bitshares-native/chain_client.js.map +0 -1
  359. package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts.map +0 -1
  360. package/dist/modules/bitshares-native/crypto/ecc.browser.js.map +0 -1
  361. package/dist/modules/bitshares-native/crypto/ecc.d.ts.map +0 -1
  362. package/dist/modules/bitshares-native/crypto/ecc.js.map +0 -1
  363. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts.map +0 -1
  364. package/dist/modules/bitshares-native/crypto/ecc_selector.js.map +0 -1
  365. package/dist/modules/bitshares-native/index.d.ts.map +0 -1
  366. package/dist/modules/bitshares-native/index.js.map +0 -1
  367. package/dist/modules/bitshares-native/lru_cache.d.ts.map +0 -1
  368. package/dist/modules/bitshares-native/lru_cache.js.map +0 -1
  369. package/dist/modules/bitshares-native/resolvers.d.ts.map +0 -1
  370. package/dist/modules/bitshares-native/resolvers.js.map +0 -1
  371. package/dist/modules/bitshares-native/serial/chain_constants.d.ts.map +0 -1
  372. package/dist/modules/bitshares-native/serial/chain_constants.js.map +0 -1
  373. package/dist/modules/bitshares-native/serial/index.d.ts.map +0 -1
  374. package/dist/modules/bitshares-native/serial/index.js.map +0 -1
  375. package/dist/modules/bitshares-native/serial/operations.d.ts.map +0 -1
  376. package/dist/modules/bitshares-native/serial/operations.js.map +0 -1
  377. package/dist/modules/bitshares-native/serial/serializer.d.ts.map +0 -1
  378. package/dist/modules/bitshares-native/serial/serializer.js.map +0 -1
  379. package/dist/modules/bitshares-native/serial/types.d.ts.map +0 -1
  380. package/dist/modules/bitshares-native/serial/types.js.map +0 -1
  381. package/dist/modules/bitshares-native/signing_client.d.ts.map +0 -1
  382. package/dist/modules/bitshares-native/signing_client.js.map +0 -1
  383. package/dist/modules/bitshares-native/subscriptions.d.ts.map +0 -1
  384. package/dist/modules/bitshares-native/subscriptions.js.map +0 -1
  385. package/dist/modules/bitshares-native/transport.d.ts.map +0 -1
  386. package/dist/modules/bitshares-native/transport.js.map +0 -1
  387. package/dist/modules/bitshares-native/tx/builder.d.ts.map +0 -1
  388. package/dist/modules/bitshares-native/tx/builder.js.map +0 -1
  389. package/dist/modules/bitshares-native/tx/tx_cache.d.ts.map +0 -1
  390. package/dist/modules/bitshares-native/tx/tx_cache.js.map +0 -1
  391. package/dist/modules/bitshares_client.d.ts.map +0 -1
  392. package/dist/modules/bitshares_client.js.map +0 -1
  393. package/dist/modules/bot_defaults.d.ts.map +0 -1
  394. package/dist/modules/bot_defaults.js.map +0 -1
  395. package/dist/modules/bot_settings.d.ts.map +0 -1
  396. package/dist/modules/bot_settings.js.map +0 -1
  397. package/dist/modules/bots_file_lock.d.ts.map +0 -1
  398. package/dist/modules/bots_file_lock.js.map +0 -1
  399. package/dist/modules/broadcast_failure.d.ts.map +0 -1
  400. package/dist/modules/broadcast_failure.js.map +0 -1
  401. package/dist/modules/chain_keys.d.ts.map +0 -1
  402. package/dist/modules/chain_keys.js.map +0 -1
  403. package/dist/modules/chain_orders.d.ts.map +0 -1
  404. package/dist/modules/chain_orders.js.map +0 -1
  405. package/dist/modules/cli_colors.d.ts.map +0 -1
  406. package/dist/modules/cli_colors.js.map +0 -1
  407. package/dist/modules/config.d.ts.map +0 -1
  408. package/dist/modules/config.js.map +0 -1
  409. package/dist/modules/constants.d.ts.map +0 -1
  410. package/dist/modules/constants.js.map +0 -1
  411. package/dist/modules/cr_planner.d.ts.map +0 -1
  412. package/dist/modules/cr_planner.js.map +0 -1
  413. package/dist/modules/credential_policy.d.ts.map +0 -1
  414. package/dist/modules/credential_policy.js.map +0 -1
  415. package/dist/modules/credential_runtime.d.ts.map +0 -1
  416. package/dist/modules/credential_runtime.js.map +0 -1
  417. package/dist/modules/credential_session_cache.d.ts.map +0 -1
  418. package/dist/modules/credential_session_cache.js.map +0 -1
  419. package/dist/modules/credit_pricing.d.ts.map +0 -1
  420. package/dist/modules/credit_pricing.js.map +0 -1
  421. package/dist/modules/credit_runtime.d.ts.map +0 -1
  422. package/dist/modules/credit_runtime.js.map +0 -1
  423. package/dist/modules/crypto/browser_provider.d.ts.map +0 -1
  424. package/dist/modules/crypto/browser_provider.js.map +0 -1
  425. package/dist/modules/crypto/index.d.ts.map +0 -1
  426. package/dist/modules/crypto/index.js.map +0 -1
  427. package/dist/modules/crypto/node_provider.d.ts.map +0 -1
  428. package/dist/modules/crypto/node_provider.js.map +0 -1
  429. package/dist/modules/crypto/provider.d.ts.map +0 -1
  430. package/dist/modules/crypto/provider.js.map +0 -1
  431. package/dist/modules/crypto/pure_ripemd160.d.ts.map +0 -1
  432. package/dist/modules/crypto/pure_ripemd160.js.map +0 -1
  433. package/dist/modules/crypto/pure_scrypt.d.ts.map +0 -1
  434. package/dist/modules/crypto/pure_scrypt.js.map +0 -1
  435. package/dist/modules/crypto/pure_secp256k1.d.ts.map +0 -1
  436. package/dist/modules/crypto/pure_secp256k1.js.map +0 -1
  437. package/dist/modules/crypto/sync.d.ts.map +0 -1
  438. package/dist/modules/crypto/sync.js.map +0 -1
  439. package/dist/modules/daemon_node_health.d.ts.map +0 -1
  440. package/dist/modules/daemon_node_health.js.map +0 -1
  441. package/dist/modules/dexbot_class.d.ts.map +0 -1
  442. package/dist/modules/dexbot_class.js.map +0 -1
  443. package/dist/modules/dexbot_cow_runtime.d.ts.map +0 -1
  444. package/dist/modules/dexbot_cow_runtime.js.map +0 -1
  445. package/dist/modules/dexbot_credential_client.d.ts.map +0 -1
  446. package/dist/modules/dexbot_credential_client.js.map +0 -1
  447. package/dist/modules/dexbot_fill_runtime.d.ts.map +0 -1
  448. package/dist/modules/dexbot_fill_runtime.js.map +0 -1
  449. package/dist/modules/dexbot_maintenance_runtime.d.ts.map +0 -1
  450. package/dist/modules/dexbot_maintenance_runtime.js.map +0 -1
  451. package/dist/modules/dexbot_startup_runtime.d.ts.map +0 -1
  452. package/dist/modules/dexbot_startup_runtime.js.map +0 -1
  453. package/dist/modules/dexbot_state_recovery.d.ts.map +0 -1
  454. package/dist/modules/dexbot_state_recovery.js.map +0 -1
  455. package/dist/modules/env.d.ts.map +0 -1
  456. package/dist/modules/env.js.map +0 -1
  457. package/dist/modules/fund_registry.d.ts.map +0 -1
  458. package/dist/modules/fund_registry.js.map +0 -1
  459. package/dist/modules/general_settings.d.ts.map +0 -1
  460. package/dist/modules/general_settings.js.map +0 -1
  461. package/dist/modules/graceful_shutdown.d.ts.map +0 -1
  462. package/dist/modules/graceful_shutdown.js.map +0 -1
  463. package/dist/modules/grid_price_source.d.ts.map +0 -1
  464. package/dist/modules/grid_price_source.js.map +0 -1
  465. package/dist/modules/key_store.d.ts.map +0 -1
  466. package/dist/modules/key_store.js.map +0 -1
  467. package/dist/modules/launcher/adapter_requirement.d.ts.map +0 -1
  468. package/dist/modules/launcher/adapter_requirement.js.map +0 -1
  469. package/dist/modules/launcher/bot_supervisor.d.ts.map +0 -1
  470. package/dist/modules/launcher/bot_supervisor.js.map +0 -1
  471. package/dist/modules/launcher/child_env.d.ts.map +0 -1
  472. package/dist/modules/launcher/child_env.js.map +0 -1
  473. package/dist/modules/launcher/credential_bootstrap.d.ts.map +0 -1
  474. package/dist/modules/launcher/credential_bootstrap.js.map +0 -1
  475. package/dist/modules/launcher/credential_daemon.d.ts.map +0 -1
  476. package/dist/modules/launcher/credential_daemon.js.map +0 -1
  477. package/dist/modules/launcher/credential_secret.d.ts.map +0 -1
  478. package/dist/modules/launcher/credential_secret.js.map +0 -1
  479. package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +0 -1
  480. package/dist/modules/launcher/foreign_cred_daemon.js.map +0 -1
  481. package/dist/modules/launcher/headless_password.d.ts.map +0 -1
  482. package/dist/modules/launcher/headless_password.js.map +0 -1
  483. package/dist/modules/launcher/launch_modes.d.ts.map +0 -1
  484. package/dist/modules/launcher/launch_modes.js.map +0 -1
  485. package/dist/modules/launcher/market_adapter_runtime.d.ts.map +0 -1
  486. package/dist/modules/launcher/market_adapter_runtime.js.map +0 -1
  487. package/dist/modules/launcher/market_adapter_watchdog.d.ts.map +0 -1
  488. package/dist/modules/launcher/market_adapter_watchdog.js.map +0 -1
  489. package/dist/modules/launcher/monolithic_runtime.d.ts.map +0 -1
  490. package/dist/modules/launcher/monolithic_runtime.js.map +0 -1
  491. package/dist/modules/launcher/runtime_entry.d.ts.map +0 -1
  492. package/dist/modules/launcher/runtime_entry.js.map +0 -1
  493. package/dist/modules/launcher/status_reporting.d.ts.map +0 -1
  494. package/dist/modules/launcher/status_reporting.js.map +0 -1
  495. package/dist/modules/launcher/supervisor_control.d.ts.map +0 -1
  496. package/dist/modules/launcher/supervisor_control.js.map +0 -1
  497. package/dist/modules/market_adapter_whitelist.d.ts.map +0 -1
  498. package/dist/modules/market_adapter_whitelist.js.map +0 -1
  499. package/dist/modules/node_connect_policy.d.ts.map +0 -1
  500. package/dist/modules/node_connect_policy.js.map +0 -1
  501. package/dist/modules/node_failure_ledger.d.ts.map +0 -1
  502. package/dist/modules/node_failure_ledger.js.map +0 -1
  503. package/dist/modules/node_health_cache.d.ts.map +0 -1
  504. package/dist/modules/node_health_cache.js.map +0 -1
  505. package/dist/modules/node_manager.d.ts.map +0 -1
  506. package/dist/modules/node_manager.js.map +0 -1
  507. package/dist/modules/order/accounting.d.ts.map +0 -1
  508. package/dist/modules/order/accounting.js.map +0 -1
  509. package/dist/modules/order/async_lock.d.ts.map +0 -1
  510. package/dist/modules/order/async_lock.js.map +0 -1
  511. package/dist/modules/order/export.d.ts.map +0 -1
  512. package/dist/modules/order/export.js.map +0 -1
  513. package/dist/modules/order/format.d.ts.map +0 -1
  514. package/dist/modules/order/format.js.map +0 -1
  515. package/dist/modules/order/grid.d.ts.map +0 -1
  516. package/dist/modules/order/grid.js.map +0 -1
  517. package/dist/modules/order/grid_reconcile.d.ts.map +0 -1
  518. package/dist/modules/order/grid_reconcile.js.map +0 -1
  519. package/dist/modules/order/grid_reconcile_internal.d.ts.map +0 -1
  520. package/dist/modules/order/grid_reconcile_internal.js.map +0 -1
  521. package/dist/modules/order/index.d.ts.map +0 -1
  522. package/dist/modules/order/index.js.map +0 -1
  523. package/dist/modules/order/logger.d.ts.map +0 -1
  524. package/dist/modules/order/logger.js.map +0 -1
  525. package/dist/modules/order/logger_state.d.ts.map +0 -1
  526. package/dist/modules/order/logger_state.js.map +0 -1
  527. package/dist/modules/order/manager.d.ts.map +0 -1
  528. package/dist/modules/order/manager.js.map +0 -1
  529. package/dist/modules/order/processed_fill_store.d.ts.map +0 -1
  530. package/dist/modules/order/processed_fill_store.js.map +0 -1
  531. package/dist/modules/order/strategy.d.ts.map +0 -1
  532. package/dist/modules/order/strategy.js.map +0 -1
  533. package/dist/modules/order/sync_engine.d.ts.map +0 -1
  534. package/dist/modules/order/sync_engine.js.map +0 -1
  535. package/dist/modules/order/utils/math.d.ts.map +0 -1
  536. package/dist/modules/order/utils/math.js.map +0 -1
  537. package/dist/modules/order/utils/order.d.ts.map +0 -1
  538. package/dist/modules/order/utils/order.js.map +0 -1
  539. package/dist/modules/order/utils/slot.d.ts.map +0 -1
  540. package/dist/modules/order/utils/slot.js.map +0 -1
  541. package/dist/modules/order/utils/system.d.ts.map +0 -1
  542. package/dist/modules/order/utils/system.js.map +0 -1
  543. package/dist/modules/order/utils/timeout.d.ts.map +0 -1
  544. package/dist/modules/order/utils/timeout.js.map +0 -1
  545. package/dist/modules/order/utils/validate.d.ts.map +0 -1
  546. package/dist/modules/order/utils/validate.js.map +0 -1
  547. package/dist/modules/order/utils/withPoolRef.d.ts.map +0 -1
  548. package/dist/modules/order/utils/withPoolRef.js.map +0 -1
  549. package/dist/modules/order/working_grid.d.ts.map +0 -1
  550. package/dist/modules/order/working_grid.js.map +0 -1
  551. package/dist/modules/path_api.d.ts.map +0 -1
  552. package/dist/modules/path_api.js.map +0 -1
  553. package/dist/modules/paths.d.ts.map +0 -1
  554. package/dist/modules/paths.js.map +0 -1
  555. package/dist/modules/process_discovery.d.ts.map +0 -1
  556. package/dist/modules/process_discovery.js.map +0 -1
  557. package/dist/modules/runtime.d.ts.map +0 -1
  558. package/dist/modules/runtime.js.map +0 -1
  559. package/dist/modules/runtime_settings.d.ts.map +0 -1
  560. package/dist/modules/runtime_settings.js.map +0 -1
  561. package/dist/modules/settings_merge.d.ts.map +0 -1
  562. package/dist/modules/settings_merge.js.map +0 -1
  563. package/dist/modules/socket_json_client.d.ts.map +0 -1
  564. package/dist/modules/socket_json_client.js.map +0 -1
  565. package/dist/modules/storage/browser_adapter.d.ts.map +0 -1
  566. package/dist/modules/storage/browser_adapter.js.map +0 -1
  567. package/dist/modules/storage/index.d.ts.map +0 -1
  568. package/dist/modules/storage/index.js.map +0 -1
  569. package/dist/modules/storage/node_adapter.d.ts.map +0 -1
  570. package/dist/modules/storage/node_adapter.js.map +0 -1
  571. package/dist/modules/storage/types.d.ts.map +0 -1
  572. package/dist/modules/storage/types.js.map +0 -1
  573. package/dist/modules/types.d.ts.map +0 -1
  574. package/dist/modules/types.js.map +0 -1
  575. package/dist/modules/utils/base58check.d.ts.map +0 -1
  576. package/dist/modules/utils/base58check.js.map +0 -1
  577. package/dist/modules/utils/build_dir.d.ts.map +0 -1
  578. package/dist/modules/utils/build_dir.js.map +0 -1
  579. package/dist/modules/utils/chain_logs.d.ts.map +0 -1
  580. package/dist/modules/utils/chain_logs.js.map +0 -1
  581. package/dist/modules/utils/errors.d.ts.map +0 -1
  582. package/dist/modules/utils/errors.js.map +0 -1
  583. package/dist/modules/utils/sanitize_key.d.ts.map +0 -1
  584. package/dist/modules/utils/sanitize_key.js.map +0 -1
  585. package/dist/modules/validate_profiles.d.ts.map +0 -1
  586. package/dist/modules/validate_profiles.js.map +0 -1
  587. package/dist/pm2.d.ts.map +0 -1
  588. package/dist/pm2.js.map +0 -1
  589. package/dist/scripts/analyze-credit.d.ts.map +0 -1
  590. package/dist/scripts/analyze-credit.js.map +0 -1
  591. package/dist/scripts/analyze-git.d.ts.map +0 -1
  592. package/dist/scripts/analyze-git.js.map +0 -1
  593. package/dist/scripts/analyze-orders.d.ts.map +0 -1
  594. package/dist/scripts/analyze-orders.js.map +0 -1
  595. package/dist/scripts/chart_command.d.ts.map +0 -1
  596. package/dist/scripts/chart_command.js.map +0 -1
  597. package/dist/scripts/diagnose-kibana-candles.d.ts.map +0 -1
  598. package/dist/scripts/diagnose-kibana-candles.js.map +0 -1
  599. package/dist/scripts/diagnose-pool-history.d.ts.map +0 -1
  600. package/dist/scripts/diagnose-pool-history.js.map +0 -1
  601. package/dist/scripts/divergence-calc.d.ts.map +0 -1
  602. package/dist/scripts/divergence-calc.js.map +0 -1
  603. package/dist/scripts/dw.d.ts.map +0 -1
  604. package/dist/scripts/dw.js.map +0 -1
  605. package/dist/scripts/generate_lp_chart.d.ts.map +0 -1
  606. package/dist/scripts/generate_lp_chart.js.map +0 -1
  607. package/dist/scripts/generate_mainnet_corpus_report.d.ts.map +0 -1
  608. package/dist/scripts/generate_mainnet_corpus_report.js.map +0 -1
  609. package/dist/scripts/native_release_gates.d.ts.map +0 -1
  610. package/dist/scripts/native_release_gates.js.map +0 -1
  611. package/dist/scripts/print_grid.d.ts.map +0 -1
  612. package/dist/scripts/print_grid.js.map +0 -1
  613. package/dist/scripts/run-tests.d.ts.map +0 -1
  614. package/dist/scripts/run-tests.js.map +0 -1
  615. package/dist/scripts/runner.d.ts.map +0 -1
  616. package/dist/scripts/runner.js.map +0 -1
  617. package/dist/scripts/sync-version.d.ts.map +0 -1
  618. package/dist/scripts/sync-version.js.map +0 -1
  619. package/dist/scripts/test-credit-renewal.d.ts.map +0 -1
  620. package/dist/scripts/test-credit-renewal.js.map +0 -1
  621. package/dist/scripts/tv.d.ts.map +0 -1
  622. package/dist/scripts/tv.js.map +0 -1
  623. package/dist/scripts/update.d.ts.map +0 -1
  624. package/dist/scripts/update.js.map +0 -1
  625. package/dist/scripts/update_dist_freshness.d.ts.map +0 -1
  626. package/dist/scripts/update_dist_freshness.js.map +0 -1
  627. package/dist/scripts/validate_bots.d.ts.map +0 -1
  628. package/dist/scripts/validate_bots.js.map +0 -1
  629. package/dist/scripts/verify-browser-bundle.d.ts.map +0 -1
  630. package/dist/scripts/verify-browser-bundle.js.map +0 -1
  631. package/dist/unlock.d.ts.map +0 -1
  632. package/dist/unlock.js.map +0 -1
@@ -13,8 +13,8 @@ const { readOpenOrdersWithMetaSafe } = chainOrdersModule;
13
13
  import { BroadcastUncertainError as BroadcastUncertainErrorBinding } from './dexbot_credential_client.js';
14
14
  const BroadcastUncertainError = BroadcastUncertainErrorBinding;
15
15
  import * as orderUtils from './order/utils/order.js';
16
- import { sleep } from './order/utils/system.js';
17
- const { buildCreateOrderArgs, buildCreateOpFingerprint, extractBatchOperationResults, formatUnmatchedChainOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, buildOutsideInPairGroups, isOrderPlaced, findLiveOrderOwnerByChainId, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, } = orderUtils;
16
+ import { sleep, setLastFillPivot } from './order/utils/system.js';
17
+ const { buildCreateOrderArgs, buildCreateOpFingerprint, extractBatchOperationResults, formatUnmatchedChainOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, buildOutsideInPairGroups, isOrderPlaced, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, } = orderUtils;
18
18
  import * as validate from './order/utils/validate.js';
19
19
  const { validateCreateTargetSlots, evaluateCommit, hasExecutableActions, stampGapEvacuationRotation } = validate;
20
20
  import * as math from './order/utils/math.js';
@@ -156,18 +156,6 @@ function getPendingBroadcasts(bot) {
156
156
  ? Array.from(bot.manager._pendingBroadcasts.values())
157
157
  : [];
158
158
  }
159
- /**
160
- * Count pending-broadcast entries without materializing the array.
161
- * Same instanceof Map guard as getPendingBroadcasts, for hot paths that
162
- * only need the count (e.g. the orphan auto-cancel gate).
163
- * @param {import('./dexbot_class.js').DEXBot} bot
164
- * @returns {number}
165
- */
166
- function countPendingBroadcasts(bot) {
167
- return (bot.manager && bot.manager._pendingBroadcasts instanceof Map)
168
- ? bot.manager._pendingBroadcasts.size
169
- : 0;
170
- }
171
159
  /**
172
160
  * Probe the chain snapshot for a pending-broadcast entry's slot.
173
161
  * Single spelling of the findChainOrderForSlot probe literal used by
@@ -1021,76 +1009,6 @@ async function reconcileAfterUncertainBroadcastImpl(bot, err, opContexts, _optio
1021
1009
  await resyncIfUnreconciled(bot, err, pending, chainSnapshot, adopted, adoptedCount, discardedCount);
1022
1010
  return { executed: false, hadRotation: false, uncertain: true, adoptedCount, discardedCount };
1023
1011
  }
1024
- /**
1025
- * Auto-cancel one unmatched orphan (price-drift orphan) per cycle.
1026
- * @param {import('./dexbot_class.js').DEXBot} bot
1027
- * @returns {Promise<{cancelled: boolean, reason?: string, orderId?: string}>}
1028
- */
1029
- async function autoCancelOneUnmatchedOrphan(bot) {
1030
- const cycleId = bot._currentCycleId || 0;
1031
- const recoveryActive = bot.manager?._recoveryState?.structuralResyncRequested === true;
1032
- const cycleCap = recoveryActive ? 5 : 1;
1033
- if (bot._autoCancelOrphanCycleMarker === cycleId) {
1034
- if (bot._autoCancelOrphanSubCount >= cycleCap) {
1035
- return { cancelled: false, reason: 'cap-reached-this-cycle', subCount: bot._autoCancelOrphanSubCount };
1036
- }
1037
- }
1038
- else {
1039
- bot._autoCancelOrphanCycleMarker = cycleId;
1040
- bot._autoCancelOrphanSubCount = 0;
1041
- }
1042
- const pending = countPendingBroadcasts(bot);
1043
- if (pending > 0) {
1044
- return { cancelled: false, reason: 'pending-broadcasts-active' };
1045
- }
1046
- const unmatched = Array.isArray(bot.manager?._lastUnmatchedChainOrders)
1047
- ? bot.manager._lastUnmatchedChainOrders
1048
- : [];
1049
- if (unmatched.length === 0) {
1050
- return { cancelled: false, reason: 'no-unmatched' };
1051
- }
1052
- const fingerprinted = unmatched.find((u) => u && u.fingerprint);
1053
- if (fingerprinted) {
1054
- return { cancelled: false, reason: 'fingerprinted-handle-via-recovery' };
1055
- }
1056
- const target = unmatched.find((u) => u && u.reason === 'price-drift-orphan');
1057
- if (!target) {
1058
- return { cancelled: false, reason: 'no-price-drift-orphan', message: 'no price-drift orphan to cancel; remaining unmatched orders need no cancellation (adoptable or deferred holds)' };
1059
- }
1060
- const orderId = target.id || target.orderId || target.chainOrderId;
1061
- if (!orderId) {
1062
- return { cancelled: false, reason: 'no-orderId' };
1063
- }
1064
- // _lastUnmatchedChainOrders is a cached snapshot. A sync/reconcile may
1065
- // have adopted this same chain id after the snapshot was recorded, so a
1066
- // direct cancel here would destroy a now-live grid order. The pending
1067
- // broadcast gate does not cover this case.
1068
- const liveOwner = findLiveOrderOwnerByChainId(bot.manager, orderId);
1069
- if (liveOwner) {
1070
- bot.manager._lastUnmatchedChainOrders = unmatched.filter((u) => {
1071
- const id = u?.id || u?.orderId || u?.chainOrderId;
1072
- return id !== orderId;
1073
- });
1074
- return { cancelled: false, reason: 'now-owned', slotId: liveOwner.id };
1075
- }
1076
- if (!chainOrders?.cancelOrder) {
1077
- return { cancelled: false, reason: 'cancelOrder-unavailable' };
1078
- }
1079
- try {
1080
- await chainOrders.cancelOrder(bot.account, bot.privateKey, orderId);
1081
- if (typeof chainOrders.recordOwnCancel === 'function') {
1082
- chainOrders.recordOwnCancel(orderId);
1083
- }
1084
- bot._autoCancelOrphanSubCount++;
1085
- bot.manager.logger.log(`[COW] Auto-cancelled ${bot._autoCancelOrphanSubCount}/${unmatched.length} unmatched chain order ` +
1086
- `(${formatUnmatchedChainOrderForLog(target)}) — per-cycle cap=${cycleCap}.`, 'warn');
1087
- return { cancelled: true, orderId };
1088
- }
1089
- catch (err) {
1090
- bot.manager.logger.log(`[COW] Auto-cancel of unmatched chain order ${orderId} failed: ${err?.message || err}`, 'error');
1091
- return { cancelled: false, reason: 'cancel-failed', error: err?.message || String(err) };
1092
- }
1093
- }
1094
1012
  /**
1095
1013
  * Check whether to execute creates in outside-in pair mode.
1096
1014
  * @param {import('./dexbot_class.js').DEXBot} bot
@@ -1639,11 +1557,11 @@ function checkGridPriceInvariant(slotId, price, genesis) {
1639
1557
  * copies from the destination hole's `order.price` and which is therefore only
1640
1558
  * as sound as whatever last wrote that object. Deriving the emitted price here
1641
1559
  * means a planner bug cannot produce a mis-priced UPDATE on its own; the
1642
- * invariant check remains as the backstop for the no-genesis case.
1560
+ * invariant check remains as the backstop.
1643
1561
  *
1644
1562
  * @returns {number} the destination's genesis level, or NaN when there is no
1645
1563
  * genesis ladder / no parseable destination index (caller falls back to the
1646
- * planned price, which is the migration case the checker fails open on).
1564
+ * planned price — an undefined grid, which the load and sync gates refuse).
1647
1565
  */
1648
1566
  function deriveRotationPrice(bot, newGridId) {
1649
1567
  try {
@@ -1938,14 +1856,11 @@ function refreshLastFillPivotFromQueue(bot) {
1938
1856
  }
1939
1857
  if (!latest)
1940
1858
  return false;
1941
- mgr._lastFilledPrice = latest.price;
1942
- mgr._lastFilledType = latest.type;
1943
- if (latest.type === ORDER_TYPES.BUY) {
1944
- mgr._lastFilledBuyPrice = latest.price;
1945
- }
1946
- else {
1947
- mgr._lastFilledSellPrice = latest.price;
1948
- }
1859
+ // Shared free writer (utils/system) — the same implementation the
1860
+ // manager's _setLastFillPivot method delegates to and restoreLast-
1861
+ // FillPivot uses, so the queued-fill refresh cannot write a different
1862
+ // scalar-family shape than any other pivot writer.
1863
+ setLastFillPivot(mgr, latest.type, latest.price, 'fill');
1949
1864
  try {
1950
1865
  mgr.logger?.log?.(`[LAST-FILL-GUARD] Pivot refreshed from ${queue.length} pending queued fill(s): ` +
1951
1866
  `${latest.type} @${Format.formatPrice6(latest.price)}`, 'debug');
@@ -3951,6 +3866,13 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3951
3866
  }
3952
3867
  // Fall through: proceed with the current plan (bounded policy).
3953
3868
  }
3869
+ // True when the plan was still valid against the master at this point.
3870
+ // Only then can a later version change be attributed to the in-flight
3871
+ // broadcast we are about to wait on (see the post-wait recheck). If the
3872
+ // re-plan above already ran and fell through, re-raising the same
3873
+ // staleness after the wait would double the structural-resync request
3874
+ // for one event.
3875
+ const preBroadcastWasFresh = preBroadcastGuard.canCommit;
3954
3876
  // Single-flight broadcast slot (authoritative, atomic check-and-set):
3955
3877
  // by this point this batch finished planning; any other batch that
3956
3878
  // started planning concurrently and beat us here holds the slot. Wait
@@ -3963,6 +3885,42 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3963
3885
  }
3964
3886
  bot._cowBroadcastInFlight = true;
3965
3887
  heldBroadcastSlot = true;
3888
+ // Re-validate the plan AFTER winning the broadcast slot, but only when
3889
+ // the plan was fresh before the wait. The version check above ran BEFORE
3890
+ // the single-flight wait, so it cannot see a master-grid advance
3891
+ // committed by the batch that just held the slot. Broadcasting such a
3892
+ // plan places rails the winner already placed (the commit-time guard
3893
+ // refuses the commit, but the duplicate orders are already on-chain and
3894
+ // must be cancelled). The 2026-09-25 restart produced exactly this: two
3895
+ // 4-op CREATEs of slots 203/204/205 landed ~2.4s apart, then three
3896
+ // duplicate orders had to be cancelled. Re-plan from the fresh master
3897
+ // instead. Release the slot first so the re-plan recursion (which uses
3898
+ // skipBroadcastWait) does not wait on a flag this frame still holds.
3899
+ if (preBroadcastWasFresh) {
3900
+ const postWaitGuard = evaluateCommit(workingGrid, {
3901
+ hasLock: false,
3902
+ currentVersion: bot.manager._gridVersion
3903
+ });
3904
+ if (!postWaitGuard.canCommit) {
3905
+ bot.manager.logger.log(`[COW] Plan went stale while waiting for an in-flight broadcast ` +
3906
+ `(${postWaitGuard.reason}); releasing the broadcast slot and re-planning from fresh master`, 'warn');
3907
+ bot._cowBroadcastInFlight = false;
3908
+ heldBroadcastSlot = false;
3909
+ const replan = await replanStaleBatch(bot, cowResult, replanDepth, postWaitGuard, seamPollIntervalMs);
3910
+ if (replan.handled) {
3911
+ return replan.result;
3912
+ }
3913
+ // No fill context for a re-plan (or the re-plan limit was
3914
+ // reached). The stale policy proceeds with the original plan, so
3915
+ // re-claim the broadcast slot before shipping it.
3916
+ if (await waitForCowBroadcastSingleFlight(bot, 'post-stale-replan')) {
3917
+ popPushedWorkingGrid(bot, cowResult);
3918
+ return { executed: false, aborted: true, reason: 'SHUTDOWN_IN_PROGRESS', hadRotation: false };
3919
+ }
3920
+ bot._cowBroadcastInFlight = true;
3921
+ heldBroadcastSlot = true;
3922
+ }
3923
+ }
3966
3924
  await bot._ensureCredentialDaemonWritable('COW batch broadcast');
3967
3925
  bot.manager.logger.log(`[COW] Broadcasting batch with ${operations.length} operations...`, 'info');
3968
3926
  bot._lastBroadcastHeartbeatAt = Date.now();
@@ -5195,7 +5153,7 @@ async function processBatchResults(bot, result, opContexts) {
5195
5153
  updateOperationCount
5196
5154
  };
5197
5155
  }
5198
- export { isLastFillGuardBlocked, resolveOnGridPivot, checkGridPriceInvariant, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast, reconcileAfterUncertainBroadcastImpl, autoCancelOneUnmatchedOrphan, executeWithRetryOnUncertain, executeChunkedWithRetryOnUncertain, formatPartialBroadcastSummary, executeOperationsWithStrategy, buildActionsFromPlan, buildCowResultFromPlan, applyRotationTransitionsToWorkingGrid, pollChainForConfirmation, updateOrdersOnChainBatchCOW, processBatchResults, adoptPlacedBatchFromChain, resolveRefillBoundaryHold, toRefillSlotIdSet, trackBoundaryHold };
5156
+ export { isLastFillGuardBlocked, resolveOnGridPivot, checkGridPriceInvariant, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast, reconcileAfterUncertainBroadcastImpl, executeWithRetryOnUncertain, executeChunkedWithRetryOnUncertain, formatPartialBroadcastSummary, executeOperationsWithStrategy, buildActionsFromPlan, buildCowResultFromPlan, applyRotationTransitionsToWorkingGrid, pollChainForConfirmation, updateOrdersOnChainBatchCOW, processBatchResults, adoptPlacedBatchFromChain, resolveRefillBoundaryHold, toRefillSlotIdSet, trackBoundaryHold };
5199
5157
  // Exported for regression tests (issue #23 sibling): the uncertain-broadcast
5200
5158
  // discard path must never drop a placement silently when master lost the slot.
5201
5159
  export { restoreDiscardedCreates };
@@ -5215,7 +5173,6 @@ export default {
5215
5173
  findChainOrderForSlot,
5216
5174
  reconcileAfterUncertainBroadcast,
5217
5175
  reconcileAfterUncertainBroadcastImpl,
5218
- autoCancelOneUnmatchedOrphan,
5219
5176
  shouldExecuteCreatePairMode,
5220
5177
  executeWithRetryOnUncertain,
5221
5178
  executeChunkedWithRetryOnUncertain,
@@ -202,7 +202,12 @@ export declare function consumeDeferredDrainMarker(bot: any): boolean;
202
202
  * through ({ defer: false, stuckFallback: true }) to the legacy path whose
203
203
  * in-lock wait still caps at 30s and proceeds — a leaked flag can delay
204
204
  * fills, never starve them. The marker resets whenever the consumer
205
- * proceeds, so only continuous deferral counts toward the bound.
205
+ * proceeds, so only continuous deferral counts toward the bound. The bound
206
+ * is also re-armed whenever the active region advances its start timestamp
207
+ * (manager._broadcastingStartedAt), so a legitimately long region — startup
208
+ * reconcile Phase 2 with many create groups — cannot accumulate deferral
209
+ * time across the whole region and trip the bound mid-flight; only a
210
+ * genuinely frozen flag (timestamp never advances) reaches the fallback.
206
211
  * @param {import('./dexbot_class.js').DEXBot} bot
207
212
  * @param {number} [nowMs] - Clock override (tests)
208
213
  * @returns {{ defer: boolean; stuckFallback: boolean }} defer=true means the
@@ -426,7 +426,12 @@ export function consumeDeferredDrainMarker(bot) {
426
426
  * through ({ defer: false, stuckFallback: true }) to the legacy path whose
427
427
  * in-lock wait still caps at 30s and proceeds — a leaked flag can delay
428
428
  * fills, never starve them. The marker resets whenever the consumer
429
- * proceeds, so only continuous deferral counts toward the bound.
429
+ * proceeds, so only continuous deferral counts toward the bound. The bound
430
+ * is also re-armed whenever the active region advances its start timestamp
431
+ * (manager._broadcastingStartedAt), so a legitimately long region — startup
432
+ * reconcile Phase 2 with many create groups — cannot accumulate deferral
433
+ * time across the whole region and trip the bound mid-flight; only a
434
+ * genuinely frozen flag (timestamp never advances) reaches the fallback.
430
435
  * @param {import('./dexbot_class.js').DEXBot} bot
431
436
  * @param {number} [nowMs] - Clock override (tests)
432
437
  * @returns {{ defer: boolean; stuckFallback: boolean }} defer=true means the
@@ -442,10 +447,23 @@ function shouldDeferFillForBroadcast(bot, nowMs) {
442
447
  active = false;
443
448
  }
444
449
  if (!active) {
445
- if (bot?._fillBroadcastDeferSince)
446
- bot._fillBroadcastDeferSince = 0;
450
+ if (bot) {
451
+ if (bot._fillBroadcastDeferSince)
452
+ bot._fillBroadcastDeferSince = 0;
453
+ bot._fillBroadcastDeferRegionAt = 0;
454
+ }
447
455
  return { defer: false, stuckFallback: false };
448
456
  }
457
+ // Region-change detection: startBroadcasting() refreshes
458
+ // _broadcastingStartedAt on every increment, so an advancing timestamp
459
+ // proves the region is live and re-arms the bound. A frozen flag does
460
+ // not advance it and still falls through at the bound.
461
+ const regionStartedAt = Number(bot?.manager?._broadcastingStartedAt) || 0;
462
+ const lastRegionAt = Number(bot?._fillBroadcastDeferRegionAt) || 0;
463
+ if (regionStartedAt && regionStartedAt !== lastRegionAt) {
464
+ bot._fillBroadcastDeferRegionAt = regionStartedAt;
465
+ bot._fillBroadcastDeferSince = now;
466
+ }
449
467
  const deferMaxMs = Number(TIMING?.FILL_BROADCAST_DEFER_MAX_MS) > 0
450
468
  ? Number(TIMING.FILL_BROADCAST_DEFER_MAX_MS)
451
469
  : 60000;
@@ -454,6 +472,7 @@ function shouldDeferFillForBroadcast(bot, nowMs) {
454
472
  bot._fillBroadcastDeferSince = now;
455
473
  if (since && (now - since) >= deferMaxMs) {
456
474
  bot._fillBroadcastDeferSince = 0;
475
+ bot._fillBroadcastDeferRegionAt = 0;
457
476
  return { defer: false, stuckFallback: true };
458
477
  }
459
478
  return { defer: true, stuckFallback: false };
@@ -279,6 +279,41 @@ declare function releaseMarketAdapterRuntime(_bot: any, botId: any, context?: an
279
279
  * @returns {boolean} True if the message indicates a nonexistent order
280
280
  */
281
281
  declare function isOrderDoesNotExistError(message: any, orderId: any): any;
282
+ /**
283
+ * 7a: pre-acquire broadcast deferral for timer-driven lock waiters.
284
+ *
285
+ * The fill consumer already defers before acquiring _fillProcessingLock (see
286
+ * shouldDeferFillForBroadcast in dexbot_fill_runtime); the maintenance timer
287
+ * loops do not. While a long broadcast/placement region holds work on the
288
+ * lock (or holds the broadcasting flag between per-op acquisitions), they
289
+ * queue behind it and can die at the 20s acquisition timeout. These loops
290
+ * are timer-driven, so skipping a tick is safe: the next tick retries once
291
+ * the region ends.
292
+ *
293
+ * Deadlock guard: these loops also run the periodic maintenance that calls
294
+ * _clearStaleBroadcastFlag, so deferring on a genuinely STALE (leaked) flag
295
+ * would prevent the only watchdog that clears it — the flag would never
296
+ * clear and every tick would defer forever. A live region refreshes
297
+ * manager._broadcastingStartedAt on every holder, so its age stays small;
298
+ * a frozen timestamp ages past BROADCAST_STALE_CLEAR_MS and we let the tick
299
+ * through so maintenance can hard-reset the flag.
300
+ * @param {any} bot
301
+ * @returns {boolean} true when the caller should skip this tick
302
+ */
303
+ declare function shouldDeferMaintenanceForBroadcast(bot: any): boolean;
304
+ /**
305
+ * Observability watchdog for _gridLock hold duration. _gridLock has no
306
+ * acquisition timeout and its callers cannot safely recover from a rejected
307
+ * acquire (grid mutations are not idempotent, and forceRelease would let a new
308
+ * acquirer run alongside the orphaned callback), so an over-long critical
309
+ * section cannot be timed out — it must be bounded at the source. This makes
310
+ * any such section visible: when the live hold crosses
311
+ * TIMING.GRID_LOCK_HOLD_WARN_MS it emits a rate-limited warn. Called from the
312
+ * maintenance tick so holds outside a broadcast region are observed too.
313
+ * @param {any} bot
314
+ * @returns {number} Observed hold duration in ms (0 when not held)
315
+ */
316
+ declare function checkGridLockHoldDuration(bot: any): number;
282
317
  /**
283
318
  * Execute the core maintenance logic: recalculate funds, check pipeline,
284
319
  * refresh dynamic weights, check grid health, cancel dust orders,
@@ -432,7 +467,7 @@ declare function syncOpenOrdersAndProcessFills(bot: any, tag: any): Promise<{
432
467
  hasUnmatched: any;
433
468
  openOrders: any[];
434
469
  }>;
435
- 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 };
470
+ 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 };
436
471
  declare const _default: {
437
472
  loadBotsConfigSnapshot: typeof loadBotsConfigSnapshot;
438
473
  isWrapperAdapterOwner: typeof isWrapperAdapterOwner;
@@ -475,6 +510,8 @@ declare const _default: {
475
510
  markGridActivity: typeof markGridActivity;
476
511
  getMetrics: typeof getMetrics;
477
512
  syncOpenOrdersAndProcessFills: typeof syncOpenOrdersAndProcessFills;
513
+ shouldDeferMaintenanceForBroadcast: typeof shouldDeferMaintenanceForBroadcast;
514
+ checkGridLockHoldDuration: typeof checkGridLockHoldDuration;
478
515
  _internalDeferredHold: {
479
516
  logDeferredHoldSummary: typeof logDeferredHoldSummary;
480
517
  describeDeferredHolds: typeof describeDeferredHolds;
@@ -1704,6 +1704,7 @@ function startOpenOrdersSyncLoop(bot) {
1704
1704
  // grid. Same isolation the fill consumer gets via
1705
1705
  // _recoverySyncInFlight.
1706
1706
  if (!bot._recoverySyncInFlight &&
1707
+ !shouldDeferMaintenanceForBroadcast(bot) &&
1707
1708
  !bot.manager._fillProcessingLock.isLocked() &&
1708
1709
  bot.manager._fillProcessingLock.getQueueLength() === 0) {
1709
1710
  await bot.manager._fillProcessingLock.acquire(async () => {
@@ -1814,6 +1815,11 @@ function setupBlockchainFetchInterval(bot) {
1814
1815
  // during shutdown.
1815
1816
  if (bot._shuttingDown)
1816
1817
  return;
1818
+ // 7a: never queue on _fillProcessingLock while a broadcast/placement
1819
+ // region is active. The fill consumer pre-defers on the same signal;
1820
+ // the timer retries next interval once the region ends.
1821
+ if (shouldDeferMaintenanceForBroadcast(bot))
1822
+ return;
1817
1823
  // Guard against overlapping ticks: if the previous tick is still in
1818
1824
  // flight (slow chain / stall), skip rather than queue a second
1819
1825
  // periodic fetch. The fill lock below would still serialize the
@@ -2015,6 +2021,85 @@ async function releaseMarketAdapterRuntime(_bot, botId, context = 'shutdown') {
2015
2021
  function isOrderDoesNotExistError(message, orderId) {
2016
2022
  return require('./order/utils/order').isOrderGoneErrorMessage(message, orderId);
2017
2023
  }
2024
+ /**
2025
+ * 7a: pre-acquire broadcast deferral for timer-driven lock waiters.
2026
+ *
2027
+ * The fill consumer already defers before acquiring _fillProcessingLock (see
2028
+ * shouldDeferFillForBroadcast in dexbot_fill_runtime); the maintenance timer
2029
+ * loops do not. While a long broadcast/placement region holds work on the
2030
+ * lock (or holds the broadcasting flag between per-op acquisitions), they
2031
+ * queue behind it and can die at the 20s acquisition timeout. These loops
2032
+ * are timer-driven, so skipping a tick is safe: the next tick retries once
2033
+ * the region ends.
2034
+ *
2035
+ * Deadlock guard: these loops also run the periodic maintenance that calls
2036
+ * _clearStaleBroadcastFlag, so deferring on a genuinely STALE (leaked) flag
2037
+ * would prevent the only watchdog that clears it — the flag would never
2038
+ * clear and every tick would defer forever. A live region refreshes
2039
+ * manager._broadcastingStartedAt on every holder, so its age stays small;
2040
+ * a frozen timestamp ages past BROADCAST_STALE_CLEAR_MS and we let the tick
2041
+ * through so maintenance can hard-reset the flag.
2042
+ * @param {any} bot
2043
+ * @returns {boolean} true when the caller should skip this tick
2044
+ */
2045
+ function shouldDeferMaintenanceForBroadcast(bot) {
2046
+ try {
2047
+ if (bot?.manager?.isBroadcastingActive?.() !== true)
2048
+ return false;
2049
+ const startedAt = Number(bot?.manager?._broadcastingStartedAt) || 0;
2050
+ if (!startedAt)
2051
+ return false;
2052
+ const staleMs = Number(TIMING?.BROADCAST_STALE_CLEAR_MS) > 0
2053
+ ? Number(TIMING.BROADCAST_STALE_CLEAR_MS)
2054
+ : 120000;
2055
+ return (Date.now() - startedAt) < staleMs;
2056
+ }
2057
+ catch {
2058
+ return false;
2059
+ }
2060
+ }
2061
+ /**
2062
+ * Observability watchdog for _gridLock hold duration. _gridLock has no
2063
+ * acquisition timeout and its callers cannot safely recover from a rejected
2064
+ * acquire (grid mutations are not idempotent, and forceRelease would let a new
2065
+ * acquirer run alongside the orphaned callback), so an over-long critical
2066
+ * section cannot be timed out — it must be bounded at the source. This makes
2067
+ * any such section visible: when the live hold crosses
2068
+ * TIMING.GRID_LOCK_HOLD_WARN_MS it emits a rate-limited warn. Called from the
2069
+ * maintenance tick so holds outside a broadcast region are observed too.
2070
+ * @param {any} bot
2071
+ * @returns {number} Observed hold duration in ms (0 when not held)
2072
+ */
2073
+ function checkGridLockHoldDuration(bot) {
2074
+ try {
2075
+ const lock = bot?.manager?._gridLock;
2076
+ if (!lock || typeof lock.heldForMs !== 'function')
2077
+ return 0;
2078
+ const heldMs = Number(lock.heldForMs()) || 0;
2079
+ if (heldMs <= 0)
2080
+ return 0;
2081
+ const warnMs = Number(TIMING?.GRID_LOCK_HOLD_WARN_MS) > 0
2082
+ ? Number(TIMING.GRID_LOCK_HOLD_WARN_MS)
2083
+ : 15000;
2084
+ if (heldMs >= warnMs) {
2085
+ const now = Date.now();
2086
+ const rateLimitMs = Number(TIMING?.STALE_TOTALS_WARN_RATE_LIMIT_MS) > 0
2087
+ ? Number(TIMING.STALE_TOTALS_WARN_RATE_LIMIT_MS)
2088
+ : 60000;
2089
+ const lastWarnAt = Number(bot?._gridLockHoldWarnAt) || 0;
2090
+ if (now - lastWarnAt >= rateLimitMs) {
2091
+ bot._gridLockHoldWarnAt = now;
2092
+ bot?._warn?.(`[GRID-LOCK] _gridLock held for ${Math.round(heldMs)}ms (threshold ${warnMs}ms). ` +
2093
+ `A critical section is running long and may starve lock waiters; bound the holder ` +
2094
+ `at the source rather than force-releasing a mutating lock.`);
2095
+ }
2096
+ }
2097
+ return heldMs;
2098
+ }
2099
+ catch {
2100
+ return 0;
2101
+ }
2102
+ }
2018
2103
  /**
2019
2104
  * Calculate the remaining idle delay (ms) before grid maintenance can proceed.
2020
2105
  * Waits for fill queue to drain and for recent grid activity to settle.
@@ -2114,6 +2199,9 @@ function scheduleDeferredGridResync(ctx, options = {}) {
2114
2199
  * @returns {Promise<void>}
2115
2200
  */
2116
2201
  async function executeMaintenanceLogic(bot, context) {
2202
+ // Surface any over-long _gridLock hold first — observational only, and it
2203
+ // must run even when the rest of the tick defers on a broadcast region.
2204
+ checkGridLockHoldDuration(bot);
2117
2205
  // Clear stale broadcast flag first so any downstream gating on
2118
2206
  // isBroadcastingActive() (e.g. recalculateFunds, BTS balance check)
2119
2207
  // sees the freshest state rather than a hung flag.
@@ -2242,16 +2330,10 @@ async function executeMaintenanceLogic(bot, context) {
2242
2330
  return;
2243
2331
  healthResult = freshHealth;
2244
2332
  }
2245
- if (!repairedFromTarget) {
2246
- const autoCancelResult = await bot._autoCancelOneUnmatchedOrphan();
2247
- if (autoCancelResult?.cancelled) {
2248
- bot._log(`[MAINT] Auto-cancelled unmatched price-drift orphan ${autoCancelResult.orderId} during ${context} ` +
2249
- `(unblocking CREATE pipeline that targeted-drift reconcile could not adopt).`, 'warn');
2250
- }
2251
- else if (autoCancelResult?.reason) {
2252
- bot._log(`[MAINT] Skipped unmatched-orphan auto-cancel during ${context}: ${autoCancelResult.reason}`, 'debug');
2253
- }
2254
- }
2333
+ // NOTE: no unmatched-orphan auto-cancel here any more. The
2334
+ // price-drift-orphan tag came from the legacy tolerance band, which no
2335
+ // longer exists: an off-grid chain order is HELD (out-of-grid-deferred)
2336
+ // and resolved structurally, never cancelled off a fuzzy price diff.
2255
2337
  refreshDynamicWeightDistribution(bot, context);
2256
2338
  const dustCancelResult = await cancelDustOrders(bot, {
2257
2339
  buy: healthResult.buyDustOrders,
@@ -2945,6 +3027,14 @@ function wireStructuralGridResyncRequest(bot) {
2945
3027
  }
2946
3028
  return;
2947
3029
  }
3030
+ if (persistedResult.halt) {
3031
+ // Missing-genesis policy 'halt': the operator must reset the
3032
+ // grid manually. Do not fall through to the automatic
3033
+ // structural resync below (docs/GRID_PRICE_INVARIANT.md).
3034
+ bot._warn(`[RECOVERY] Missing-genesis policy='halt' — suppressing the automatic structural ` +
3035
+ `resync for ${reason}. Run a manual grid reset for this bot.`);
3036
+ return;
3037
+ }
2948
3038
  const suffix = unmatchedCount > 0 ? ` (${unmatchedCount} unmatched chain order(s))` : '';
2949
3039
  bot._warn(`[RECOVERY] Running structural full grid resync for ${reason}${suffix}`);
2950
3040
  // Same protection as the persisted-grid reload above: the
@@ -3113,7 +3203,7 @@ async function syncOpenOrdersAndProcessFillsImpl(bot, tag) {
3113
3203
  return { syncResult: null, aborted: true, hasUnmatched: -1, openOrders: null };
3114
3204
  }
3115
3205
  }
3116
- 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 };
3206
+ export { loadBotsConfigSnapshot, isWrapperAdapterOwner, checkAndApplyBotConfigChanges, buildBotConfigFingerprint, refreshDynamicWeightDistribution, performGridResync, updateBotGridResetMetadata, handlePendingTriggerReset, setupTriggerFileDetection, performPeriodicGridChecks, isOpenOrdersSyncLoopEnabled, startOpenOrdersSyncLoop, stopOpenOrdersSyncLoop, setupBlockchainFetchInterval, stopBlockchainFetchInterval, setupBotsConfigPollInterval, stopBotsConfigPollInterval, executeMaintenanceLogic, getTargetedSyncReason, countLiveReserveOrders, cancelDustOrders, isOrderDoesNotExistError, runGridMaintenance, releaseMarketAdapterRuntime, syncMarketAdapterOnPeriodicConfigCheck, usesAmaGridPrice, runDustHealthCheck, setupDustHealthCheckInterval, requestGridReset, wireStructuralGridResyncRequest, getPipelineSignals, markGridActivity, getMetrics, syncOpenOrdersAndProcessFills, shouldDeferMaintenanceForBroadcast, checkGridLockHoldDuration };
3117
3207
  export default {
3118
3208
  loadBotsConfigSnapshot,
3119
3209
  isWrapperAdapterOwner,
@@ -3156,6 +3246,8 @@ export default {
3156
3246
  markGridActivity,
3157
3247
  getMetrics,
3158
3248
  syncOpenOrdersAndProcessFills,
3249
+ shouldDeferMaintenanceForBroadcast,
3250
+ checkGridLockHoldDuration,
3159
3251
  _internalDeferredHold: { logDeferredHoldSummary, describeDeferredHolds, considerDeferredHoldEscalation },
3160
3252
  };
3161
3253
  //# sourceMappingURL=dexbot_maintenance_runtime.js.map
@@ -14,6 +14,7 @@ import { BitShares, onReconnect as registerReconnectHook } from './bitshares_cli
14
14
  import orderModule from './order/index.js';
15
15
  import { getErrorMessage } from './utils/errors.js';
16
16
  import { processSweepOrphanFill } from './dexbot_fill_runtime.js';
17
+ import { ON_MISSING_GENESIS, recordMissingGenesisFault, resolvePersistedGenesis } from './order/genesis_policy.js';
17
18
  const { OrderManager, grid: Grid } = orderModule;
18
19
  function initializeFeeCache(...args) { return require('./order/utils/system').initializeFeeCache(...args); }
19
20
  function parseJsonWithComments(...args) { return require('./order/utils/system').parseJsonWithComments(...args); }
@@ -141,6 +142,46 @@ async function initializeStartupState(bot) {
141
142
  persistedGapEvacStreaks,
142
143
  };
143
144
  }
145
+ /**
146
+ * E3 startup gate: decide whether the persisted grid can be resumed at all.
147
+ *
148
+ * A snapshot with orders but no usable price ladder is refused (the same
149
+ * `resolvePersistedGenesis` verdict `loadGrid` enforces, so the two cannot
150
+ * drift) and the configured policy decides what happens next:
151
+ * 'rebuild' (default) -> return `{ needsRebuild: true }`; the caller takes
152
+ * the regeneration branch, where `initializeGrid` re-derives prices
153
+ * (resolving mode strings such as "pool") and builds a fresh ladder
154
+ * before the first sync. Live orders are reconciled update-first, so
155
+ * only true surplus is cancelled.
156
+ * 'halt' -> throw the fault; the startup sequence's catch logs it, shuts the
157
+ * bot down and rethrows. Nothing is cancelled without an operator.
158
+ *
159
+ * @param {import('./dexbot_class.js').DEXBot} bot
160
+ * @param {any[]} persistedGrid - Persisted grid array (non-empty).
161
+ * @param {any} persistedGenesis - Persisted ladder row (may be null).
162
+ * @returns {{needsRebuild: boolean}}
163
+ */
164
+ function evaluateStartupGenesisGate(bot, persistedGrid, persistedGenesis) {
165
+ const config = bot.manager?.config || bot.config;
166
+ const resolution = resolvePersistedGenesis({
167
+ config,
168
+ grid: persistedGrid,
169
+ genesisInput: persistedGenesis,
170
+ log: (msg, level) => bot._log(msg, level)
171
+ });
172
+ if (resolution.ok)
173
+ return { needsRebuild: false };
174
+ // Records the fault on the manager (so the E2 sync-entry assert and any
175
+ // later read can name the reason) and logs the policy-specific guidance.
176
+ const fault = recordMissingGenesisFault(bot.manager, { ...resolution });
177
+ if (fault.policy === ON_MISSING_GENESIS.HALT) {
178
+ throw fault;
179
+ }
180
+ bot._log(`[GENESIS] Persisted grid cannot be resumed without a price ladder — regenerating the grid from live ` +
181
+ `config (missing-genesis policy='${fault.policy}'); the rebuild re-derives prices ` +
182
+ `and reconciles against the live book update-first`, 'warn');
183
+ return { needsRebuild: true };
184
+ }
144
185
  /**
145
186
  * Finish the startup sequence: activate fill listener, reconcile grid, place initial orders.
146
187
  * @param {import('./dexbot_class.js').DEXBot} bot
@@ -456,27 +497,39 @@ async function finishStartupSequence(bot, startupState) {
456
497
  bot._log('No persisted grid found. Generating new grid.');
457
498
  }
458
499
  else {
459
- await bot.manager._initializeAssets();
460
- const decision = await reconcileMod.decideStartupGridAction({
461
- persistedGrid,
462
- chainOpenOrders,
463
- manager: bot.manager,
464
- logger: botRetryLogger(bot),
465
- storeGrid: async (orders) => {
466
- await bot.manager.persistGrid(orders);
467
- },
468
- boundaryIdx: persistedBoundaryIdx,
469
- genesis: persistedGenesis,
470
- attemptResumeFn: reconcileMod.attemptResumePersistedGridByPriceMatch,
471
- });
472
- shouldRegenerate = decision.shouldRegenerate;
473
- if (shouldRegenerate && chainOpenOrders.length === 0) {
474
- bot._log('Persisted grid found, but no matching active orders on-chain. Generating new grid.');
500
+ // E3 STARTUP GATE (docs/GRID_PRICE_INVARIANT.md): a persisted grid with
501
+ // no usable price ladder must never reach the first sync — every
502
+ // slot-price consumer degrades to a tolerance matcher from there on.
503
+ // Ask the SAME question loadGrid asks (one resolver, two callers) and
504
+ // take the configured action BEFORE deciding resume-vs-regenerate, so
505
+ // a genesis-less snapshot is rebuilt instead of half-loaded.
506
+ const genesisGate = evaluateStartupGenesisGate(bot, persistedGrid, persistedGenesis);
507
+ if (genesisGate.needsRebuild) {
508
+ shouldRegenerate = true;
475
509
  }
476
- if (shouldRegenerate && chainOpenOrders.length > 0 && bot.manager?.assets) {
477
- const orderCount = chainOpenOrders.filter((o) => parseChainOrder(o, bot.manager.assets) !== null).length;
478
- if (orderCount === 0) {
479
- bot._log(`Persisted grid found with no matching orders (${chainOpenOrders.length} other-pair order(s) on account). Generating new grid.`);
510
+ else {
511
+ await bot.manager._initializeAssets();
512
+ const decision = await reconcileMod.decideStartupGridAction({
513
+ persistedGrid,
514
+ chainOpenOrders,
515
+ manager: bot.manager,
516
+ logger: botRetryLogger(bot),
517
+ storeGrid: async (orders) => {
518
+ await bot.manager.persistGrid(orders);
519
+ },
520
+ boundaryIdx: persistedBoundaryIdx,
521
+ genesis: persistedGenesis,
522
+ attemptResumeFn: reconcileMod.attemptResumePersistedGridByPriceMatch,
523
+ });
524
+ shouldRegenerate = decision.shouldRegenerate;
525
+ if (shouldRegenerate && chainOpenOrders.length === 0) {
526
+ bot._log('Persisted grid found, but no matching active orders on-chain. Generating new grid.');
527
+ }
528
+ if (shouldRegenerate && chainOpenOrders.length > 0 && bot.manager?.assets) {
529
+ const orderCount = chainOpenOrders.filter((o) => parseChainOrder(o, bot.manager.assets) !== null).length;
530
+ if (orderCount === 0) {
531
+ bot._log(`Persisted grid found with no matching orders (${chainOpenOrders.length} other-pair order(s) on account). Generating new grid.`);
532
+ }
480
533
  }
481
534
  }
482
535
  }
@@ -87,9 +87,15 @@ declare function recoverBatchSizeDrift(bot: any, err: any, opContexts?: any): Pr
87
87
  declare function recoverFromPersistedGrid(bot: any): Promise<{
88
88
  success: boolean;
89
89
  reason: string;
90
+ halt?: undefined;
90
91
  } | {
91
92
  success: boolean;
92
93
  reason?: undefined;
94
+ halt?: undefined;
95
+ } | {
96
+ success: boolean;
97
+ reason: string;
98
+ halt: boolean;
93
99
  }>;
94
100
  /**
95
101
  * Schedule a best-effort target-grid rebalance after a recovery sync.