dexbot 1.6.10 → 1.6.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (365) hide show
  1. package/CHANGELOG.md +50 -3
  2. package/README.md +3 -1
  3. package/analysis/README.md +51 -11
  4. package/analysis/bot_fitting/README.md +12 -0
  5. package/analysis/tradingview/README.md +3 -3
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +11 -37
  7. package/analysis/trend_detection/README.md +31 -0
  8. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  9. package/claw/modules/chain_broadcast.ts +7 -1
  10. package/claw/modules/claw_launcher.ts +1 -1
  11. package/claw/modules/launcher_mode_detector.ts +9 -2
  12. package/claw/package.json +1 -1
  13. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  14. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  15. package/dist/analysis/account_resolver.d.ts +1 -1
  16. package/dist/analysis/account_resolver.js +15 -2
  17. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  18. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -7
  19. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  20. package/dist/analysis/ama_fitting/fetch_lp_candles.js +4 -4
  21. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +20 -4
  22. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +9 -6
  23. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +16 -12
  24. package/dist/analysis/analyze_args.d.ts +31 -0
  25. package/dist/analysis/analyze_args.js +41 -0
  26. package/dist/analysis/analyze_dynamic_weight.js +7 -20
  27. package/dist/analysis/analyze_kalman.js +7 -17
  28. package/dist/analysis/analyze_regime.js +7 -17
  29. package/dist/analysis/analyze_regime_windows.js +8 -18
  30. package/dist/analysis/analyze_risk_profile.js +8 -18
  31. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  32. package/dist/analysis/analyze_volatility.js +7 -17
  33. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +220 -12
  34. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +55 -10
  35. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  36. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +72 -66
  37. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.d.ts +21 -0
  38. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +315 -0
  39. package/dist/analysis/bot_fitting/shared_utils.d.ts +7 -7
  40. package/dist/analysis/bot_fitting/shared_utils.js +2 -2
  41. package/dist/analysis/bot_key_utils.d.ts +18 -10
  42. package/dist/analysis/bot_key_utils.js +10 -17
  43. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  44. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  45. package/dist/analysis/chain_pool.d.ts +3 -1
  46. package/dist/analysis/chart_ui.d.ts +5 -2
  47. package/dist/analysis/chart_ui.js +6 -3
  48. package/dist/analysis/chart_utils.d.ts +5 -5
  49. package/dist/analysis/chart_utils.js +9 -0
  50. package/dist/analysis/fills_cache.d.ts +64 -0
  51. package/dist/analysis/fills_cache.js +254 -0
  52. package/dist/analysis/fills_source.d.ts +2 -2
  53. package/dist/analysis/fills_source.js +19 -14
  54. package/dist/analysis/grid_correction_check.d.ts +1 -1
  55. package/dist/analysis/grid_correction_check.js +12 -11
  56. package/dist/analysis/math_utils.d.ts +7 -6
  57. package/dist/analysis/math_utils.js +5 -8
  58. package/dist/analysis/pnl_report.d.ts +39 -0
  59. package/dist/analysis/pnl_report.js +325 -0
  60. package/dist/analysis/price_sources.d.ts +8 -8
  61. package/dist/analysis/price_sources.js +5 -4
  62. package/dist/analysis/resolve_bot_accounts.js +2 -2
  63. package/dist/analysis/resolve_source.d.ts +1 -2
  64. package/dist/analysis/trade_profitability.d.ts +32 -2
  65. package/dist/analysis/trade_profitability.js +232 -106
  66. package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
  67. package/dist/analysis/tradingview/analyze_tradingview.js +9 -10
  68. package/dist/analysis/tradingview/grid_reset_config.d.ts +42 -31
  69. package/dist/analysis/tradingview/grid_reset_config.js +35 -6
  70. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -8
  71. package/dist/analysis/tradingview/grid_reset_sim.js +42 -5
  72. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  73. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -20
  74. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +102 -0
  75. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +725 -0
  76. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  77. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +27 -112
  78. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +40 -0
  79. package/dist/analysis/trend_detection/huber_scale_variants.js +176 -0
  80. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  81. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  82. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  83. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  84. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  85. package/dist/credential-daemon.js +34 -20
  86. package/dist/dexbot.js +17 -14
  87. package/dist/market_adapter/candle_utils.d.ts +22 -18
  88. package/dist/market_adapter/candle_utils.js +24 -20
  89. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  90. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  91. package/dist/market_adapter/core/kibana_candles.d.ts +53 -18
  92. package/dist/market_adapter/core/kibana_candles.js +9 -7
  93. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  94. package/dist/market_adapter/core/kibana_client.js +8 -7
  95. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  96. package/dist/market_adapter/core/market_adapter_service.d.ts +297 -115
  97. package/dist/market_adapter/core/market_adapter_service.js +184 -101
  98. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  99. package/dist/market_adapter/core/strategies/ama.js +7 -32
  100. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  101. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  102. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  103. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  104. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  105. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  106. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +36 -8
  107. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +9 -9
  108. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  109. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  110. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  111. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  112. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  113. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  114. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  115. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  116. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  117. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  118. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +97 -226
  119. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +42 -7
  120. package/dist/market_adapter/inputs/fetch_lp_data.js +22 -15
  121. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  122. package/dist/market_adapter/inputs/kibana_feed_source.js +29 -22
  123. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  124. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  125. package/dist/market_adapter/inputs/window_cache.d.ts +99 -94
  126. package/dist/market_adapter/inputs/window_cache.js +8 -8
  127. package/dist/market_adapter/interval_utils.d.ts +4 -4
  128. package/dist/market_adapter/log_format.d.ts +6 -6
  129. package/dist/market_adapter/log_format.js +28 -22
  130. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  131. package/dist/market_adapter/lp_chart_core.js +26 -192
  132. package/dist/market_adapter/lp_chart_runner.d.ts +7 -7
  133. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  134. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  135. package/dist/market_adapter/market_adapter.d.ts +94 -33
  136. package/dist/market_adapter/market_adapter.js +69 -75
  137. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  138. package/dist/market_adapter/utils/adapter_client.js +2 -2
  139. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  140. package/dist/market_adapter/utils/chain.d.ts +50 -41
  141. package/dist/market_adapter/utils/chain.js +40 -46
  142. package/dist/market_adapter/utils/data_discovery.d.ts +4 -1
  143. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  144. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  145. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  146. package/dist/market_adapter/utils/file_lock.js +36 -32
  147. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  148. package/dist/market_adapter/utils/native_history.js +35 -28
  149. package/dist/modules/account_bots.d.ts +577 -21
  150. package/dist/modules/account_bots.js +182 -158
  151. package/dist/modules/account_orders.d.ts +66 -30
  152. package/dist/modules/account_orders.js +22 -20
  153. package/dist/modules/authority_resolver.d.ts +12 -2
  154. package/dist/modules/authority_resolver.js +15 -8
  155. package/dist/modules/bitshares-native/chain_client.d.ts +38 -3
  156. package/dist/modules/bitshares-native/chain_client.js +45 -46
  157. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  158. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  159. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  160. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  161. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  162. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  163. package/dist/modules/bitshares-native/index.d.ts +1 -1
  164. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  165. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  166. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  167. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  168. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  169. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  170. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  171. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  172. package/dist/modules/bitshares-native/serial/types.js +55 -62
  173. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  174. package/dist/modules/bitshares-native/signing_client.js +19 -14
  175. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  176. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  177. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  178. package/dist/modules/bitshares-native/transport.js +5 -4
  179. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  180. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  181. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  182. package/dist/modules/bitshares_client.d.ts +45 -13
  183. package/dist/modules/bitshares_client.js +28 -19
  184. package/dist/modules/bot_defaults.d.ts +6 -15
  185. package/dist/modules/bot_defaults.js +1 -5
  186. package/dist/modules/bot_settings.d.ts +44 -10
  187. package/dist/modules/bot_settings.js +11 -8
  188. package/dist/modules/bots_file_lock.d.ts +6 -6
  189. package/dist/modules/bots_file_lock.js +16 -12
  190. package/dist/modules/broadcast_failure.d.ts +2 -2
  191. package/dist/modules/broadcast_failure.js +5 -4
  192. package/dist/modules/chain_keys.d.ts +42 -40
  193. package/dist/modules/chain_keys.js +53 -45
  194. package/dist/modules/chain_orders.d.ts +93 -59
  195. package/dist/modules/chain_orders.js +31 -23
  196. package/dist/modules/constants.d.ts +530 -32
  197. package/dist/modules/constants.js +52 -60
  198. package/dist/modules/cr_planner.d.ts +40 -2
  199. package/dist/modules/credential_policy.d.ts +68 -8
  200. package/dist/modules/credential_policy.js +37 -31
  201. package/dist/modules/credential_session_cache.d.ts +2 -2
  202. package/dist/modules/credit_pricing.d.ts +42 -6
  203. package/dist/modules/credit_pricing.js +44 -30
  204. package/dist/modules/credit_runtime.d.ts +276 -118
  205. package/dist/modules/credit_runtime.js +462 -165
  206. package/dist/modules/crypto/browser_provider.js +6 -4
  207. package/dist/modules/crypto/node_provider.js +1 -1
  208. package/dist/modules/crypto/pure_scrypt.js +35 -4
  209. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  210. package/dist/modules/crypto/sync.d.ts +9 -9
  211. package/dist/modules/crypto/sync.js +16 -9
  212. package/dist/modules/dexbot_class.d.ts +195 -139
  213. package/dist/modules/dexbot_class.js +78 -28
  214. package/dist/modules/dexbot_cow_runtime.d.ts +167 -87
  215. package/dist/modules/dexbot_cow_runtime.js +248 -206
  216. package/dist/modules/dexbot_credential_client.d.ts +19 -11
  217. package/dist/modules/dexbot_fill_runtime.d.ts +63 -48
  218. package/dist/modules/dexbot_fill_runtime.js +48 -41
  219. package/dist/modules/dexbot_maintenance_runtime.d.ts +109 -70
  220. package/dist/modules/dexbot_maintenance_runtime.js +117 -80
  221. package/dist/modules/dexbot_startup_runtime.d.ts +11 -10
  222. package/dist/modules/dexbot_startup_runtime.js +43 -43
  223. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  224. package/dist/modules/dexbot_state_recovery.js +18 -13
  225. package/dist/modules/fund_registry.d.ts +4 -2
  226. package/dist/modules/fund_registry.js +10 -10
  227. package/dist/modules/general_settings.d.ts +30 -4
  228. package/dist/modules/graceful_shutdown.d.ts +3 -3
  229. package/dist/modules/graceful_shutdown.js +2 -2
  230. package/dist/modules/grid_price_source.d.ts +1 -1
  231. package/dist/modules/key_store.d.ts +14 -8
  232. package/dist/modules/key_store.js +7 -6
  233. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  234. package/dist/modules/launcher/adapter_requirement.js +5 -5
  235. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  236. package/dist/modules/launcher/bot_supervisor.js +12 -11
  237. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  238. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  239. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  240. package/dist/modules/launcher/credential_daemon.js +2 -2
  241. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  242. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  243. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  244. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  245. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  246. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  247. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  248. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  249. package/dist/modules/launcher/supervisor_control.js +4 -2
  250. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  251. package/dist/modules/market_adapter_whitelist.js +15 -3
  252. package/dist/modules/node_manager.d.ts +41 -11
  253. package/dist/modules/node_manager.js +5 -4
  254. package/dist/modules/order/accounting.d.ts +53 -24
  255. package/dist/modules/order/accounting.js +40 -14
  256. package/dist/modules/order/async_lock.d.ts +5 -2
  257. package/dist/modules/order/async_lock.js +1 -1
  258. package/dist/modules/order/export.d.ts +7 -6
  259. package/dist/modules/order/export.js +1 -7
  260. package/dist/modules/order/format.d.ts +39 -19
  261. package/dist/modules/order/format.js +62 -16
  262. package/dist/modules/order/genesis_policy.d.ts +21 -18
  263. package/dist/modules/order/genesis_policy.js +12 -8
  264. package/dist/modules/order/grid.d.ts +142 -36
  265. package/dist/modules/order/grid.js +148 -123
  266. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  267. package/dist/modules/order/grid_reconcile.js +13 -12
  268. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  269. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  270. package/dist/modules/order/index.d.ts +263 -1
  271. package/dist/modules/order/logger.d.ts +45 -11
  272. package/dist/modules/order/logger.js +38 -40
  273. package/dist/modules/order/logger_state.d.ts +4 -4
  274. package/dist/modules/order/manager.d.ts +226 -180
  275. package/dist/modules/order/manager.js +101 -83
  276. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  277. package/dist/modules/order/processed_fill_store.js +16 -27
  278. package/dist/modules/order/strategy.d.ts +21 -13
  279. package/dist/modules/order/strategy.js +5 -6
  280. package/dist/modules/order/sync_engine.d.ts +91 -33
  281. package/dist/modules/order/sync_engine.js +99 -54
  282. package/dist/modules/order/utils/math.d.ts +157 -102
  283. package/dist/modules/order/utils/math.js +77 -38
  284. package/dist/modules/order/utils/order.d.ts +326 -106
  285. package/dist/modules/order/utils/order.js +200 -99
  286. package/dist/modules/order/utils/slot.d.ts +1 -1
  287. package/dist/modules/order/utils/system.d.ts +176 -26
  288. package/dist/modules/order/utils/system.js +86 -69
  289. package/dist/modules/order/utils/validate.d.ts +89 -41
  290. package/dist/modules/order/utils/validate.js +24 -22
  291. package/dist/modules/order/utils/withPoolRef.d.ts +4 -3
  292. package/dist/modules/order/utils/withPoolRef.js +18 -12
  293. package/dist/modules/order/working_grid.d.ts +14 -13
  294. package/dist/modules/paths.d.ts +3 -4
  295. package/dist/modules/paths.js +3 -27
  296. package/dist/modules/process_discovery.d.ts +1 -1
  297. package/dist/modules/process_discovery.js +2 -1
  298. package/dist/modules/runtime.d.ts +7 -3
  299. package/dist/modules/runtime.js +4 -3
  300. package/dist/modules/runtime_settings.d.ts +15 -10
  301. package/dist/modules/runtime_settings.js +30 -24
  302. package/dist/modules/settings_merge.d.ts +29 -3
  303. package/dist/modules/settings_merge.js +56 -78
  304. package/dist/modules/socket_json_client.d.ts +7 -4
  305. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  306. package/dist/modules/storage/browser_adapter.js +7 -30
  307. package/dist/modules/storage/index.d.ts +1 -1
  308. package/dist/modules/storage/node_adapter.d.ts +45 -27
  309. package/dist/modules/storage/node_adapter.js +9 -9
  310. package/dist/modules/storage/types.d.ts +5 -4
  311. package/dist/modules/types.d.ts +1071 -2
  312. package/dist/modules/types.js +4 -1
  313. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  314. package/dist/modules/utils/asset_symbols.js +2 -1
  315. package/dist/modules/utils/errors.d.ts +9 -0
  316. package/dist/modules/utils/errors.js +23 -1
  317. package/dist/modules/utils/time_range.d.ts +4 -0
  318. package/dist/modules/utils/time_range.js +18 -0
  319. package/dist/modules/validate_profiles.js +53 -43
  320. package/dist/modules/version_notice.d.ts +14 -3
  321. package/dist/modules/version_notice.js +6 -4
  322. package/dist/pm2.d.ts +29 -27
  323. package/dist/pm2.js +5 -5
  324. package/dist/scripts/analyze-credit.d.ts +2 -1
  325. package/dist/scripts/analyze-credit.js +23 -24
  326. package/dist/scripts/analyze-orders.d.ts +77 -9
  327. package/dist/scripts/analyze-orders.js +66 -84
  328. package/dist/scripts/chart_command.d.ts +27 -18
  329. package/dist/scripts/chart_command.js +16 -15
  330. package/dist/scripts/check_any.d.ts +18 -0
  331. package/dist/scripts/check_any.js +126 -0
  332. package/dist/scripts/diagnose-pool-history.js +12 -7
  333. package/dist/scripts/pnl.d.ts +3 -0
  334. package/dist/scripts/pnl.js +40 -0
  335. package/dist/scripts/print_grid.js +0 -1
  336. package/dist/scripts/run-tests.js +39 -7
  337. package/dist/scripts/runner.js +1 -1
  338. package/dist/scripts/test-credit-renewal.js +30 -21
  339. package/dist/scripts/update.d.ts +10 -5
  340. package/dist/scripts/update.js +168 -103
  341. package/dist/scripts/update_dist_freshness.js +1 -0
  342. package/dist/scripts/update_layout.d.ts +61 -0
  343. package/dist/scripts/update_layout.js +180 -0
  344. package/dist/scripts/validate_bots.js +2 -1
  345. package/dist/scripts/verify-browser-bundle.js +8 -0
  346. package/dist/unlock.d.ts +28 -3
  347. package/dist/unlock.js +72 -10
  348. package/docs/BITSHARES_ONBOARDING.md +2 -0
  349. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  350. package/docs/COW_INVARIANTS.md +13 -6
  351. package/docs/DEXBOT_COMPARISON.md +8 -8
  352. package/docs/EVOLUTION.md +12 -10
  353. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  354. package/docs/GRID_RECALCULATION.md +15 -16
  355. package/docs/GRID_RECONCILE.md +14 -3
  356. package/docs/LIFECYCLE.md +11 -11
  357. package/docs/MPA_CREDIT_USAGE.md +22 -3
  358. package/docs/README.md +15 -4
  359. package/docs/WORKFLOW.md +1 -0
  360. package/docs/architecture.md +12 -9
  361. package/docs/developer_guide.md +6 -6
  362. package/market_adapter/README.md +9 -26
  363. package/modules/README.md +4 -1
  364. package/package.json +4 -1
  365. package/scripts/README.md +14 -0
@@ -30,44 +30,9 @@ import { ORDER_TYPES, ORDER_STATES, REBALANCE_STATES, TIMING, LOG_LEVEL, PIPELIN
30
30
  import { seedBotRuntimeConfig } from '../bot_defaults.js';
31
31
  import { getMinOrderSize, computeChainFundTotals, hasValidAccountTotals, resolveConfigValueWithRegistry, isExplicitZeroAllocation, floatToBlockchainInt, validateBoundaryCommit, resolveGapSlots, resolveGapBand, isSlotInRail } from './utils/math.js';
32
32
  import { validateOrder, validateGridForPersistence, validateWorkingGridFunds, checkFundDrift, reconcileGrid, optimizeRebalanceActions, projectTargetToWorkingGrid, buildStateUpdates, buildAbortedResult, buildSuccessResult, evaluateCommit } from './utils/validate.js';
33
- import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveReserveCount, resolveLiveReserveEdgeAnchorPrice, compareReserveEdge, collectRefillSlotIds } from './utils/order.js';
34
- import { getErrorMessage } from '../utils/errors.js';
33
+ import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveReserveCount, resolveLiveReserveEdgeAnchorPrice, compareReserveEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder } from './utils/order.js';
34
+ import { getErrorMessage, getErrorCode } from '../utils/errors.js';
35
35
  const { toFiniteNumber } = Format;
36
- // ===============================================================================
37
- // SECTION 2: COW REBALANCE ENGINE
38
- // ===============================================================================
39
- /**
40
- * Stale-placement veto: whether a placement action crosses the plan's own
41
- * boundary and would fill immediately on stale market data.
42
- * - BUY create/update targeting a slot ABOVE the boundary is dropped; SELL
43
- * create/update targeting a slot BELOW the boundary is dropped. Strict
44
- * comparison: a placement AT the boundary is kept (the boundary slot is
45
- * the spread, which reconcile never targets).
46
- * - The reference is the PLAN'S OWN targetBoundary — and ONLY that: the
47
- * plan's slots derive from the same target grid, so a stale plan's
48
- * placements cross its own boundary while legitimate re-placements never
49
- * do (the boundary is capped, the fills are not). Fill-based veto lines
50
- * are deliberately NOT used — after a burst the fills sit beyond the
51
- * plan's legitimate re-place levels (e.g. SELL fills 5,6,7 with cap=1
52
- * moves the boundary only to slot 6), so ANY fill comparison can veto
53
- * valid placements, including the strategy's own rotations (a partial
54
- * SELL rotated into a slot below the last BUY fill after the boundary
55
- * crawled left). The guard is therefore "inert" for boundary-consistent
56
- * engine output by construction.
57
- * - Slot ids are compared within the plan's own grid generation
58
- * (targetBoundary and target slots are both from the current plan), so a
59
- * recenter between the fill capture and the plan cannot skew the
60
- * comparison. Both CREATE and UPDATE actions are guarded: the
61
- * cancel/create optimization can convert the same logical placement into
62
- * an UPDATE op (target slot = newGridId), which the CREATE-only check
63
- * would have missed.
64
- * - When no plan boundary is available (hand-built plans), nothing is
65
- * vetoed — fill evidence is not a reliable veto line. Non-placement
66
- * actions and non-grid-slot targets are never vetoed.
67
- * @param {Object} action - COW action
68
- * @param {number} planBoundary - The plan's target boundary slot index
69
- * @returns {string|null} Drop reason for the log, or null to keep the action
70
- */
71
36
  function stalePlacementDropReason(action, planBoundary) {
72
37
  const isPlacement = action?.type === COW_ACTIONS.CREATE || action?.type === COW_ACTIONS.UPDATE;
73
38
  if (!isPlacement)
@@ -134,7 +99,7 @@ class COWRebalanceEngine {
134
99
  this.assets = deps.assets;
135
100
  this.config = deps.config;
136
101
  }
137
- async execute({ masterGrid, gridVersion, boundaryIdx, funds, fills = [], excludeIds = new Set(), gapSlots = null, evacStreaks = null, reserveEdgeAnchors = null }) {
102
+ async execute({ masterGrid, gridVersion, boundaryIdx, funds, manager = null, fills = [], excludeIds = new Set(), gapSlots = null, evacStreaks = null, reserveEdgeAnchors = null }) {
138
103
  const startTime = Date.now();
139
104
  const workingGrid = new WorkingGrid(masterGrid, { baseVersion: gridVersion });
140
105
  const strategyParams = {
@@ -172,15 +137,15 @@ class COWRebalanceEngine {
172
137
  const reconcileResult = reconcileGrid(masterGrid, targetGrid, targetBoundary, {
173
138
  logger: (msg, level) => this.logger?.log(msg, level),
174
139
  dustThresholdPercent,
175
- gapSlots,
176
- evacStreaks,
140
+ gapSlots: gapSlots ?? undefined,
141
+ evacStreaks: evacStreaks ?? undefined,
177
142
  assets: this.assets
178
143
  });
179
144
  // Gap-evacuation telemetry: evacReady is the streak-tick output of
180
145
  // reconcileGrid (stuck in-band candidates). It must survive both
181
146
  // abort and success so the manager can act on it even when the
182
147
  // rebalance plan itself aborts for an unrelated reason.
183
- const evacReady = Array.isArray(reconcileResult?.evacReady)
148
+ const evacReady = Array.isArray(reconcileResult.evacReady)
184
149
  ? reconcileResult.evacReady
185
150
  : [];
186
151
  if (reconcileResult.aborted) {
@@ -188,10 +153,40 @@ class COWRebalanceEngine {
188
153
  aborted.evacReady = evacReady;
189
154
  return aborted;
190
155
  }
191
- const optimizedActions = optimizeRebalanceActions(reconcileResult.actions, masterGrid, {
156
+ // Fresh-placement cancel guard. Reconcile runs on a target snapshot
157
+ // that can be a beat behind a just-placed order; cancelling it burns
158
+ // fees, empties a level and re-places the same thing next cycle. Hold
159
+ // the whole slot's action group (a type-mismatch CANCEL is paired with
160
+ // a CREATE on the same id) for the grace window. The surplus is
161
+ // re-derived next cycle once the order has had time to prove itself.
162
+ const deferredFreshCancelSlots = new Set();
163
+ for (const action of reconcileResult.actions) {
164
+ if (action.type !== COW_ACTIONS.CANCEL || !action.orderId)
165
+ continue;
166
+ if (!manager || !isFreshlyPlacedOrder(manager, action.orderId))
167
+ continue;
168
+ const slotId = String(action.id);
169
+ if (deferredFreshCancelSlots.has(slotId))
170
+ continue;
171
+ deferredFreshCancelSlots.add(slotId);
172
+ this.logger?.log(`[COW] Deferring cancel of freshly placed ${action.orderId} (${slotId}) — inside grace window`, 'info');
173
+ }
174
+ // Id-group drop is deliberate: dropping only the CANCEL would let
175
+ // optimizeRebalanceActions below fold the paired CREATE back into an
176
+ // UPDATE (cancelAction.id + newGridId) and re-materialize the
177
+ // placement. Safe because reconcile emits per slot either a CANCEL
178
+ // group or an UPDATE, never both ("no duplicate UPDATE+CANCEL for the
179
+ // same order" invariant), and an unpaired-surplus CANCEL by
180
+ // construction has no remaining same-type hole to fold into — so no
181
+ // needed repricing is discarded here. If a generator ever emits both,
182
+ // the symptom is only a one-cycle repricing deferral.
183
+ const plannedActions = deferredFreshCancelSlots.size > 0
184
+ ? reconcileResult.actions.filter((action) => !deferredFreshCancelSlots.has(String(action.id)))
185
+ : reconcileResult.actions;
186
+ const optimizedActions = optimizeRebalanceActions(plannedActions, masterGrid, {
192
187
  logger: (msg, level) => this.logger?.log(msg, level),
193
- boundaryIdx: targetBoundary,
194
- gapSlots,
188
+ boundaryIdx: targetBoundary ?? undefined,
189
+ gapSlots: gapSlots ?? undefined,
195
190
  assets: this.assets
196
191
  });
197
192
  // Stale-placement guard: drop placements crossing the plan's own
@@ -245,6 +240,13 @@ class COWRebalanceEngine {
245
240
  manager: this
246
241
  });
247
242
  projectTargetToWorkingGrid(workingGrid, targetGrid, { actions: optimizedActions });
243
+ // The projection above virtually applied every target-grid change,
244
+ // including the cancellations we just held back. Restore the freshly
245
+ // placed slots from master so committing the working grid does not
246
+ // virtualize a live order whose cancel was deferred.
247
+ for (const slotId of deferredFreshCancelSlots) {
248
+ workingGrid.syncFromMaster(masterGrid, slotId, gridVersion);
249
+ }
248
250
  const precisions = {
249
251
  buyPrecision: this.assets?.assetB?.precision,
250
252
  sellPrecision: this.assets?.assetA?.precision
@@ -417,6 +419,7 @@ class OrderManager {
417
419
  _committedOrderIds;
418
420
  _committedOrderIdsBuiltAt;
419
421
  _orderIdAssignedAt;
422
+ _placedAt;
420
423
  _gapSlots;
421
424
  _genesis;
422
425
  _missingGenesis;
@@ -438,6 +441,7 @@ class OrderManager {
438
441
  _deferredRebalanceAt;
439
442
  _lastHeldPlanSignature;
440
443
  _heldPlanSuppressionCount;
444
+ _onBroadcastRegionEnd;
441
445
  _onBroadcastRegionEndListeners;
442
446
  _lastBoundaryHoldResyncAt;
443
447
  _gapEvacStreaks;
@@ -540,6 +544,9 @@ class OrderManager {
540
544
  this._committedOrderIds = new Set();
541
545
  this._committedOrderIdsBuiltAt = 0;
542
546
  this._orderIdAssignedAt = new Map();
547
+ // Fresh-placement timestamps (chainOrderId -> Date.now) for the
548
+ // surplus-cancel grace window. See recordOrderPlacement.
549
+ this._placedAt = new Map();
543
550
  this._gapSlots = 0;
544
551
  // Genesis (price-ladder) state. `_genesis` is established by
545
552
  // loadGrid/initializeGrid; these records are the missing-genesis fault
@@ -573,6 +580,11 @@ class OrderManager {
573
580
  this._gapEvacStreaks = new Map();
574
581
  this._gapEvacCancelQueued = new Set();
575
582
  this._metrics = {
583
+ fillsProcessed: 0,
584
+ batchesExecuted: 0,
585
+ fillProcessingTimeMs: 0,
586
+ lockContentionEvents: 0,
587
+ maxQueueDepth: 0,
576
588
  fundRecalcCount: 0,
577
589
  lockAcquisitions: 0,
578
590
  lockContentionSkips: 0,
@@ -731,7 +743,7 @@ class OrderManager {
731
743
  this._bootstrapping++;
732
744
  }
733
745
  /**
734
- * @returns {any}
746
+ * @returns {unknown}
735
747
  */
736
748
  finishBootstrap() {
737
749
  const result = { hadDrift: false, driftInfo: null };
@@ -800,10 +812,10 @@ class OrderManager {
800
812
  */
801
813
  _fireBroadcastRegionEnd() {
802
814
  try {
803
- this._onBroadcastRegionEnd?.();
815
+ (this._onBroadcastRegionEnd)?.();
804
816
  }
805
817
  catch (err) {
806
- this.logger?.log?.(`[BROADCAST] Region-end hook failed: ${err?.message || err}`, 'warn');
818
+ this.logger?.log?.(`[BROADCAST] Region-end hook failed: ${getErrorMessage(err)}`, 'warn');
807
819
  }
808
820
  const listeners = this._onBroadcastRegionEndListeners;
809
821
  if (Array.isArray(listeners)) {
@@ -812,7 +824,7 @@ class OrderManager {
812
824
  listener?.();
813
825
  }
814
826
  catch (err) {
815
- this.logger?.log?.(`[BROADCAST] Region-end listener failed: ${err?.message || err}`, 'warn');
827
+ this.logger?.log?.(`[BROADCAST] Region-end listener failed: ${getErrorMessage(err)}`, 'warn');
816
828
  }
817
829
  }
818
830
  }
@@ -853,7 +865,7 @@ class OrderManager {
853
865
  * value can lag behind the actual orders state (virtualized orders
854
866
  * release committed capital via updateOptimisticFreeBalance without
855
867
  * triggering a recalc). Reading from the orders map avoids that race.
856
- * @returns {any}
868
+ * @returns {unknown}
857
869
  */
858
870
  getChainFundsSnapshot() {
859
871
  let committedBuy = 0, committedSell = 0;
@@ -996,7 +1008,7 @@ class OrderManager {
996
1008
  return await this.sync.fetchAccountBalancesAndSetTotals();
997
1009
  }
998
1010
  /**
999
- * @param {any} totals - Account balance totals
1011
+ * @param {unknown} totals - Account balance totals
1000
1012
  * @returns {Promise<void>}
1001
1013
  */
1002
1014
  async setAccountTotals(totals = { buy: null, sell: null, buyFree: null, sellFree: null }) {
@@ -1166,7 +1178,7 @@ class OrderManager {
1166
1178
  * @param {Object} info
1167
1179
  * @returns {Promise<any>}
1168
1180
  */
1169
- syncFromOpenOrders(orders, info) {
1181
+ syncFromOpenOrders(orders, info = {}) {
1170
1182
  return this.sync.syncFromOpenOrders(orders, info);
1171
1183
  }
1172
1184
  /**
@@ -1174,7 +1186,7 @@ class OrderManager {
1174
1186
  * @param {Object} [options]
1175
1187
  * @returns {Promise<any>}
1176
1188
  */
1177
- syncFromFillHistory(fill, options) {
1189
+ syncFromFillHistory(fill, options = {}) {
1178
1190
  return this.sync.syncFromFillHistory(fill, options);
1179
1191
  }
1180
1192
  /**
@@ -1182,7 +1194,7 @@ class OrderManager {
1182
1194
  * @param {Object} [options]
1183
1195
  * @returns {Promise<any>}
1184
1196
  */
1185
- syncFromFillHistoryBatch(fills, options) {
1197
+ syncFromFillHistoryBatch(fills, options = {}) {
1186
1198
  return this.sync.syncFromFillHistoryBatch(fills, options);
1187
1199
  }
1188
1200
  /**
@@ -1301,7 +1313,7 @@ class OrderManager {
1301
1313
  this.logger.log(warning.message, 'warn');
1302
1314
  }
1303
1315
  if (!validation.isValid && validation.errors.length > 0) {
1304
- const fatalError = validation.errors.find((e) => e.isFatal || e.code === 'ILLEGAL_SPREAD_STATE');
1316
+ const fatalError = validation.errors.find((e) => e.isFatal === true || getErrorCode(e) === 'ILLEGAL_SPREAD_STATE');
1305
1317
  if (fatalError) {
1306
1318
  this.logger.log(fatalError.message, 'error');
1307
1319
  this._lastIllegalState = {
@@ -1320,9 +1332,9 @@ class OrderManager {
1320
1332
  // Ensure a mutable copy before passing to updateOptimisticFreeBalance.
1321
1333
  // validation.normalizedOrder may reference a frozen master-grid order,
1322
1334
  // and _resolveBtsFeeLifecycle mutates btsFeeState on the order object.
1323
- let nextOrder = { ...validation.normalizedOrder };
1335
+ let nextOrder = { ...(validation.normalizedOrder ?? {}) };
1324
1336
  // Apply phantom order auto-correction to the normalized order
1325
- const phantomError = validation.errors.find((e) => e.code === 'PHANTOM_ORDER');
1337
+ const phantomError = validation.errors.find((e) => getErrorCode(e) === 'PHANTOM_ORDER');
1326
1338
  let accountingSkip = skipAccounting;
1327
1339
  if (phantomError && phantomError.autoCorrect) {
1328
1340
  nextOrder = { ...nextOrder, ...phantomError.autoCorrect };
@@ -1355,6 +1367,23 @@ class OrderManager {
1355
1367
  }
1356
1368
  this._orderIdAssignedAt.set(updatedOrder.orderId, Date.now());
1357
1369
  }
1370
+ // Fresh-placement timestamp for the surplus-cancel grace window: a
1371
+ // slot gaining an orderId it did not have is a new placement (create,
1372
+ // adopt, rotation target), and surplus sweeps must not cancel it
1373
+ // before it has had time to prove itself. Same-id updates do not
1374
+ // refresh the stamp, so grace cannot extend forever. Snapshot/grid
1375
+ // load paths are excluded: reloaded orders are old by definition, and
1376
+ // stamping them would neuter surplus sweeps for 15 minutes after every
1377
+ // restart.
1378
+ try {
1379
+ const prevId = oldOrder?.orderId != null ? String(oldOrder.orderId) : '';
1380
+ const nextId = updatedOrder.orderId != null ? String(updatedOrder.orderId) : '';
1381
+ const isLoadContext = context === 'grid-load' || context === 'grid-init';
1382
+ if (nextId && nextId !== prevId && !isLoadContext) {
1383
+ recordOrderPlacement(this, nextId);
1384
+ }
1385
+ }
1386
+ catch { /* bookkeeping must never break order updates */ }
1358
1387
  const newMap = cloneMap(this.orders);
1359
1388
  newMap.set(id, updatedOrder);
1360
1389
  this.orders = Object.freeze(newMap);
@@ -1366,18 +1395,6 @@ class OrderManager {
1366
1395
  this._markGridDirty();
1367
1396
  return true;
1368
1397
  }
1369
- /**
1370
- * Backward-compatible accessor for _currentWorkingGrid.
1371
- * Returns the top of the working grid stack (null if empty).
1372
- */
1373
- get _currentWorkingGrid() {
1374
- return this._peekWorkingGrid();
1375
- }
1376
- set _currentWorkingGrid(val) {
1377
- if (val !== null) {
1378
- this._currentWorkingGridStack.push(val);
1379
- }
1380
- }
1381
1398
  _peekWorkingGrid() {
1382
1399
  const stack = this._currentWorkingGridStack;
1383
1400
  return stack.length > 0 ? stack[stack.length - 1] : null;
@@ -1399,7 +1416,7 @@ class OrderManager {
1399
1416
  /**
1400
1417
  * @param {Array<import('./types').Order>} updates - Order updates to apply
1401
1418
  * @param {string} [context] - Update context label
1402
- * @param {any} [options]
1419
+ * @param {unknown} [options]
1403
1420
  * @returns {Promise<boolean>}
1404
1421
  */
1405
1422
  async applyGridUpdateBatch(updates, context = 'batch-update', options = {}) {
@@ -1472,7 +1489,7 @@ class OrderManager {
1472
1489
  return { skipped: true, suspended: true, reason: this._gridPersistenceSuspendedReason };
1473
1490
  }
1474
1491
  const result = await this.persistGrid(undefined);
1475
- if (result && result.skipped === true) {
1492
+ if (result && 'skipped' in result && result.skipped === true) {
1476
1493
  // Persistence was deferred (suspension, validation, etc.) — keep
1477
1494
  // the dirty flag so a later tick can retry.
1478
1495
  return result;
@@ -1703,22 +1720,21 @@ class OrderManager {
1703
1720
  */
1704
1721
  _logBoundaryDebug(source, newIdx) {
1705
1722
  try {
1706
- const self = this;
1707
- const boundary = newIdx == null ? self.boundaryIdx : newIdx;
1723
+ const boundary = newIdx == null ? this.boundaryIdx : newIdx;
1708
1724
  if (boundary == null)
1709
1725
  return;
1710
- const gapSlots = typeof self._gapSlots === 'number' ? self._gapSlots : 0;
1726
+ const gapSlots = typeof this._gapSlots === 'number' ? this._gapSlots : 0;
1711
1727
  const sellStart = boundary + 1 + gapSlots;
1712
1728
  const countActive = (type) => {
1713
1729
  let n = 0;
1714
- for (const o of (self.orders?.values?.() || [])) {
1730
+ for (const o of this.orders.values()) {
1715
1731
  if (o && o.type === type && o.orderId)
1716
1732
  n++;
1717
1733
  }
1718
1734
  return n;
1719
1735
  };
1720
1736
  this.logger?.log?.(`[BOUNDARY] ${source} boundary=${boundary} sellStart=${sellStart} gapSlots=${gapSlots} ` +
1721
- `spreadCount=${self.currentSpreadCount ?? self.initialSpreadCount ?? '?'} ` +
1737
+ `spreadCount=${this.currentSpreadCount ?? this.initialSpreadCount ?? '?'} ` +
1722
1738
  `activeBuy=${countActive(ORDER_TYPES.BUY)} activeSell=${countActive(ORDER_TYPES.SELL)}`, 'debug');
1723
1739
  }
1724
1740
  catch {
@@ -1800,7 +1816,7 @@ class OrderManager {
1800
1816
  let priceSrc = 'direct';
1801
1817
  if (!Number.isFinite(price) || price <= 0) {
1802
1818
  try {
1803
- const slot = f.id ? this.orders?.get?.(f.id) : null;
1819
+ const slot = f.id ? this.orders.get(f.id) : null;
1804
1820
  price = slot ? Number(slot.price) : null;
1805
1821
  if (Number.isFinite(price) && price > 0)
1806
1822
  priceSrc = 'slot-fallback';
@@ -1813,7 +1829,7 @@ class OrderManager {
1813
1829
  continue;
1814
1830
  this._setLastFillPivot(f.type, price, 'fill');
1815
1831
  recorded++;
1816
- lastKind = f?.isPartial === true ? 'partial' : (f?.isPartial === false ? 'full' : 'unknown');
1832
+ lastKind = f.isPartial === true ? 'partial' : (f.isPartial === false ? 'full' : 'unknown');
1817
1833
  lastPriceSrc = priceSrc;
1818
1834
  }
1819
1835
  // One line per fill batch (chunk): the pivot mutations above are otherwise
@@ -1933,14 +1949,14 @@ class OrderManager {
1933
1949
  * @param {Function} batchCb - Batch callback
1934
1950
  * @returns {Promise<Object>}
1935
1951
  */
1936
- async checkSpreadCondition(BitShares, batchCb) {
1952
+ async checkSpreadCondition(BitShares, batchCb = null) {
1937
1953
  return await checkSpreadCondition(this, BitShares, batchCb);
1938
1954
  }
1939
1955
  /**
1940
1956
  * @param {Function} batchCb - Batch callback
1941
1957
  * @returns {Promise<Object>}
1942
1958
  */
1943
- async checkGridHealth(batchCb) {
1959
+ async checkGridHealth(batchCb = null) {
1944
1960
  return await checkGridHealth(this, batchCb);
1945
1961
  }
1946
1962
  /**
@@ -1950,7 +1966,7 @@ class OrderManager {
1950
1966
  return calculateCurrentSpread(this);
1951
1967
  }
1952
1968
  /**
1953
- * @returns {any}
1969
+ * @returns {unknown}
1954
1970
  */
1955
1971
  checkFundDriftAfterFills() {
1956
1972
  if (!this.assets || !hasValidAccountTotals(this.accountTotals)) {
@@ -1960,7 +1976,7 @@ class OrderManager {
1960
1976
  }
1961
1977
  /**
1962
1978
  * @param {Object|number} [pipelineSignals] - Pipeline state signals or queue length
1963
- * @returns {any}
1979
+ * @returns {unknown}
1964
1980
  */
1965
1981
  isPipelineEmpty(pipelineSignals = 0) {
1966
1982
  const normalizedSignals = (typeof pipelineSignals === 'number')
@@ -2079,7 +2095,8 @@ class OrderManager {
2079
2095
  const boundary = this.boundaryIdx;
2080
2096
  const gapSlots = this._gapSlots;
2081
2097
  let queued = 0;
2082
- for (const candidate of candidates) {
2098
+ for (const raw of candidates) {
2099
+ const candidate = raw;
2083
2100
  const slotId = candidate?.id;
2084
2101
  const chainOrderId = candidate?.orderId;
2085
2102
  if (!slotId || !chainOrderId)
@@ -2255,6 +2272,7 @@ class OrderManager {
2255
2272
  gridVersion: this._gridVersion,
2256
2273
  boundaryIdx: this.boundaryIdx,
2257
2274
  funds: this.getChainFundsSnapshot(),
2275
+ manager: this,
2258
2276
  fills,
2259
2277
  excludeIds,
2260
2278
  gapSlots: this._gapSlots,
@@ -2466,7 +2484,7 @@ class OrderManager {
2466
2484
  /**
2467
2485
  * @param {Object} [options]
2468
2486
  * @param {boolean} [options.allowBootstrapTransient]
2469
- * @returns {any}
2487
+ * @returns {unknown}
2470
2488
  */
2471
2489
  validateGridStateForPersistence(options = {}) {
2472
2490
  const result = validateGridForPersistence(this.orders, this.accountTotals);
@@ -1,3 +1,7 @@
1
+ /**
2
+ * @enum {string}
3
+ */
4
+ import type { AccountOrdersLike } from '../types.js';
1
5
  declare const PROCESSED_FILL_PERSISTENCE_MODES: {
2
6
  readonly IMMEDIATE: string;
3
7
  readonly BATCHED: string;
@@ -23,11 +27,11 @@ declare class ProcessedFillStore {
23
27
  _warn: (msg: string) => void;
24
28
  _persistTimer: ReturnType<typeof setTimeout> | null;
25
29
  _flushPromise: Promise<void>;
26
- _accountOrders: any | null;
30
+ _accountOrders: AccountOrdersLike | null;
27
31
  _shuttingDown: boolean;
28
32
  /**
29
33
  * Create a ProcessedFillStore instance.
30
- * @param {any} [options] - Configuration
34
+ * @param {unknown} [options] - Configuration
31
35
  * @param {number} [options.batchMs] - Batch interval in ms for coalesced writes
32
36
  * @param {number} [options.batchSize] - Max batch size before auto-flush
33
37
  * @param {Function} [options.warn] - Warning logger function
@@ -43,7 +47,7 @@ declare class ProcessedFillStore {
43
47
  * @param {Object} [options.accountOrders] - AccountOrders instance for persistence
44
48
  */
45
49
  configure({ accountOrders }?: {
46
- accountOrders?: any;
50
+ accountOrders?: AccountOrdersLike;
47
51
  }): void;
48
52
  /**
49
53
  * Set the shutting down flag to prevent delayed writes during shutdown.
@@ -105,6 +109,17 @@ declare class ProcessedFillStore {
105
109
  flushKeys(fillKeys: string[] | Set<string>, reason?: string, { throwOnError }?: {
106
110
  throwOnError?: boolean;
107
111
  }): Promise<void>;
112
+ /**
113
+ * Persist a batch of already-dequeued fills, re-queuing entries when the
114
+ * write fails. Shared by flush() and flushKeys() so the retry/back-off
115
+ * path cannot drift apart.
116
+ * @param {Map<string, number>} batch - Dequeued fill keys to persist
117
+ * @param {string} reason - Reason label for logging
118
+ * @param {boolean} throwOnError - Re-throw on flush failure
119
+ * @param {string} descriptor - Noun describing the batch in the failure log
120
+ * @returns {Promise<void>}
121
+ */
122
+ _flushBatch(batch: Map<string, number>, reason: string, throwOnError: boolean, descriptor: string): Promise<void>;
108
123
  /**
109
124
  * Queue a fill key for batched persistence.
110
125
  * @param {string} fillKey - Fill deduplication key
@@ -1,6 +1,3 @@
1
- /**
2
- * @enum {string}
3
- */
4
1
  import { getErrorMessage } from '../utils/errors.js';
5
2
  const PROCESSED_FILL_PERSISTENCE_MODES = Object.freeze({
6
3
  IMMEDIATE: 'immediate',
@@ -40,7 +37,7 @@ class ProcessedFillStore {
40
37
  _shuttingDown;
41
38
  /**
42
39
  * Create a ProcessedFillStore instance.
43
- * @param {any} [options] - Configuration
40
+ * @param {unknown} [options] - Configuration
44
41
  * @param {number} [options.batchMs] - Batch interval in ms for coalesced writes
45
42
  * @param {number} [options.batchSize] - Max batch size before auto-flush
46
43
  * @param {Function} [options.warn] - Warning logger function
@@ -163,28 +160,7 @@ class ProcessedFillStore {
163
160
  }
164
161
  const batch = new Map(this.pendingWrites);
165
162
  this.pendingWrites.clear();
166
- let flushError = null;
167
- const flushWork = async () => {
168
- try {
169
- await this._accountOrders.updateProcessedFillsBatch(batch);
170
- }
171
- catch (err) {
172
- flushError = err;
173
- for (const [fillKey, timestamp] of batch) {
174
- const queuedTimestamp = this.pendingWrites.get(fillKey);
175
- if (queuedTimestamp === undefined || timestamp > queuedTimestamp) {
176
- this.pendingWrites.set(fillKey, timestamp);
177
- }
178
- }
179
- this._warn(`[FILL-DEDUP] Failed to flush ${batch.size} processed fill record(s) (${reason}): ${getErrorMessage(err)}`);
180
- this._schedule();
181
- }
182
- };
183
- this._flushPromise = this._flushPromise.then(flushWork, flushWork);
184
- await this._flushPromise;
185
- if (flushError && throwOnError) {
186
- throw flushError;
187
- }
163
+ await this._flushBatch(batch, reason, throwOnError, 'processed');
188
164
  }
189
165
  /**
190
166
  * Flush pending writes for specific fill keys.
@@ -208,6 +184,19 @@ class ProcessedFillStore {
208
184
  batch.set(fillKey, this.pendingWrites.get(fillKey));
209
185
  this.pendingWrites.delete(fillKey);
210
186
  }
187
+ await this._flushBatch(batch, reason, throwOnError, 'selected processed');
188
+ }
189
+ /**
190
+ * Persist a batch of already-dequeued fills, re-queuing entries when the
191
+ * write fails. Shared by flush() and flushKeys() so the retry/back-off
192
+ * path cannot drift apart.
193
+ * @param {Map<string, number>} batch - Dequeued fill keys to persist
194
+ * @param {string} reason - Reason label for logging
195
+ * @param {boolean} throwOnError - Re-throw on flush failure
196
+ * @param {string} descriptor - Noun describing the batch in the failure log
197
+ * @returns {Promise<void>}
198
+ */
199
+ async _flushBatch(batch, reason, throwOnError, descriptor) {
211
200
  if (batch.size === 0) {
212
201
  await this._flushPromise;
213
202
  return;
@@ -225,7 +214,7 @@ class ProcessedFillStore {
225
214
  this.pendingWrites.set(fillKey, timestamp);
226
215
  }
227
216
  }
228
- this._warn(`[FILL-DEDUP] Failed to flush ${batch.size} selected processed fill record(s) (${reason}): ${getErrorMessage(err)}`);
217
+ this._warn(`[FILL-DEDUP] Failed to flush ${batch.size} ${descriptor} fill record(s) (${reason}): ${getErrorMessage(err)}`);
229
218
  this._schedule();
230
219
  }
231
220
  };
@@ -46,12 +46,23 @@
46
46
  *
47
47
  * ===============================================================================
48
48
  */
49
+ import type { OrderManagerLike, ManagedOrder, GridConfig, AssetPair, ProjectedFunds } from "../types.js";
50
+ interface FillInput {
51
+ id?: string;
52
+ type?: string;
53
+ price?: number;
54
+ size?: number;
55
+ isPartial?: boolean;
56
+ isDelayedRotationTrigger?: boolean;
57
+ orderId?: string | null;
58
+ [key: string]: unknown;
59
+ }
49
60
  declare class StrategyEngine {
50
- manager: any;
61
+ manager: OrderManagerLike;
51
62
  /**
52
63
  * @param {Object} manager - OrderManager instance
53
64
  */
54
- constructor(manager: any);
65
+ constructor(manager: OrderManagerLike);
55
66
  /**
56
67
  * Process filled orders: handle fills and consolidate partials.
57
68
  * Does NOT trigger rebalancing (now decoupled from rebalance logic).
@@ -84,7 +95,7 @@ declare class StrategyEngine {
84
95
  * @returns {Promise<boolean>} True if processing completed successfully
85
96
  * @async
86
97
  */
87
- processFillsOnly(filledOrders: any, excludeOrderIds?: any): Promise<boolean>;
98
+ processFillsOnly(filledOrders: FillInput[], excludeOrderIds?: Set<string>): Promise<boolean>;
88
99
  /**
89
100
  * UNIFIED TARGET CALCULATION
90
101
  * Calculates the "Ideal State" grid based on current fills and market conditions.
@@ -136,18 +147,15 @@ declare class StrategyEngine {
136
147
  * - boundaryIdx {number}: New boundary index
137
148
  */
138
149
  calculateTargetGrid(params: {
139
- frozenMasterGrid: Map<string, any>;
140
- config: any;
141
- accountAssets: any;
142
- funds: any;
143
- fills: any[];
144
- currentBoundaryIdx: number;
150
+ frozenMasterGrid: Map<string, ManagedOrder>;
151
+ config: GridConfig;
152
+ accountAssets: AssetPair | null;
153
+ funds: ProjectedFunds | null;
154
+ fills: FillInput[];
155
+ currentBoundaryIdx: number | null;
145
156
  }): {
146
157
  targetGrid: Map<any, any>;
147
- boundaryIdx: number;
148
- } | {
149
- targetGrid: Map<any, any>;
150
- boundaryIdx: null;
158
+ boundaryIdx: number | null;
151
159
  };
152
160
  }
153
161
  export default StrategyEngine;
@@ -98,7 +98,7 @@ class StrategyEngine {
98
98
  return true;
99
99
  mgr.logger.log(`[STRATEGY] Processing batch of ${filledOrders.length} filled orders...`, 'info');
100
100
  for (const filledOrder of filledOrders) {
101
- if (excludeOrderIds?.has?.(filledOrder.id)) {
101
+ if (filledOrder.id != null && excludeOrderIds?.has?.(filledOrder.id)) {
102
102
  mgr.logger.log(`[STRATEGY] Skipping excluded fill for order ${filledOrder.id}`, 'debug');
103
103
  continue;
104
104
  }
@@ -141,7 +141,7 @@ class StrategyEngine {
141
141
  }
142
142
  }
143
143
  if (!isPartial || filledOrder.isDelayedRotationTrigger) {
144
- const currentSlot = mgr.orders.get(filledOrder.id);
144
+ const currentSlot = filledOrder.id != null ? mgr.orders.get(filledOrder.id) : undefined;
145
145
  const slotReused = currentSlot && hasOnChainId(currentSlot) && filledOrder.orderId && currentSlot.orderId !== filledOrder.orderId;
146
146
  if (currentSlot && !slotReused && isOrderPlaced(currentSlot) && currentSlot.size > 0) {
147
147
  mgr.logger.log(`[STRATEGY] Virtualizing filled slot ${filledOrder.id}`, 'debug');
@@ -152,7 +152,7 @@ class StrategyEngine {
152
152
  // never the stored type.
153
153
  let filledHole = null;
154
154
  try {
155
- const filledGeoType = geometryTypeForSlotIndex(parseSlotIndex(currentSlot?.id), mgr?.boundaryIdx, mgr?._gapSlots);
155
+ const filledGeoType = geometryTypeForSlotIndex(parseSlotIndex(currentSlot?.id), mgr.boundaryIdx, mgr._gapSlots);
156
156
  filledHole = (filledGeoType === ORDER_TYPES.BUY || filledGeoType === ORDER_TYPES.SELL)
157
157
  ? toRailHolePlaceholder(currentSlot, filledGeoType, 0)
158
158
  : convertToSpreadPlaceholder(currentSlot);
@@ -246,7 +246,7 @@ class StrategyEngine {
246
246
  // but not position, and an unanchored recovery fabricates a rail-edge
247
247
  // boundary (the slot-77→slot-192 teleport). The numeric config center
248
248
  // still wins when present.
249
- const genesisStart = Number(this.manager?._genesis?.startPrice);
249
+ const genesisStart = Number(this.manager._genesis?.startPrice);
250
250
  const boundaryConfig = (!Number.isFinite(Number(config?.startPrice)) && Number.isFinite(genesisStart))
251
251
  ? { ...config, genesisStartPrice: genesisStart }
252
252
  : config;
@@ -259,7 +259,7 @@ class StrategyEngine {
259
259
  buy: resolveLiveReserveEdgeAnchorPrice(this.manager, 'buy'),
260
260
  sell: resolveLiveReserveEdgeAnchorPrice(this.manager, 'sell'),
261
261
  };
262
- const { boundaryIdx: newBoundaryIdx, remainingBudget } = deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, boundaryConfig, gapSlots, crossChunkBudget, this.manager?._pendingFillCrawls, reserveEdgeAnchors);
262
+ const { boundaryIdx: newBoundaryIdx, remainingBudget } = deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, boundaryConfig, gapSlots, crossChunkBudget, this.manager._pendingFillCrawls, reserveEdgeAnchors);
263
263
  if (crossChunkBudget != null) {
264
264
  this.manager._boundaryShiftBudget = remainingBudget;
265
265
  }
@@ -354,7 +354,6 @@ class StrategyEngine {
354
354
  type: slot.type,
355
355
  size: size,
356
356
  idealSize: size,
357
- // If size > 0, we WANT it active. If size 0, we want it VIRTUAL/SPREAD
358
357
  state: size > 0 ? ORDER_STATES.ACTIVE : ORDER_STATES.VIRTUAL,
359
358
  committedSide: (slot.type === ORDER_TYPES.BUY || slot.type === ORDER_TYPES.SELL)
360
359
  ? slot.type