dexbot 1.6.11 → 1.6.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (398) hide show
  1. package/CHANGELOG.md +67 -4
  2. package/README.md +2 -1
  3. package/analysis/README.md +11 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/analysis/tradingview/README.md +1 -1
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
  7. package/claw/README.md +1 -0
  8. package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
  9. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  10. package/claw/modules/chain_broadcast.ts +7 -1
  11. package/claw/modules/claw_bridge.ts +0 -3
  12. package/claw/modules/claw_launcher.ts +1 -1
  13. package/claw/modules/claw_skill_md.ts +1 -0
  14. package/claw/modules/launcher_mode_detector.ts +9 -2
  15. package/claw/package.json +3 -3
  16. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  17. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/account_resolver.d.ts +1 -1
  20. package/dist/analysis/account_resolver.js +2 -1
  21. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  22. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +3 -21
  23. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  24. package/dist/analysis/ama_fitting/fetch_lp_candles.js +55 -45
  25. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -8
  26. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +45 -24
  27. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +34 -78
  28. package/dist/analysis/analyze_args.d.ts +43 -0
  29. package/dist/analysis/analyze_args.js +61 -0
  30. package/dist/analysis/analyze_dynamic_weight.js +7 -17
  31. package/dist/analysis/analyze_kalman.js +7 -17
  32. package/dist/analysis/analyze_regime.js +7 -17
  33. package/dist/analysis/analyze_regime_windows.js +8 -18
  34. package/dist/analysis/analyze_risk_profile.js +8 -18
  35. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  36. package/dist/analysis/analyze_volatility.js +7 -17
  37. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +221 -28
  38. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +23 -103
  39. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  40. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +32 -150
  41. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  42. package/dist/analysis/bot_fitting/shared_utils.d.ts +77 -9
  43. package/dist/analysis/bot_fitting/shared_utils.js +125 -9
  44. package/dist/analysis/bot_key_utils.d.ts +18 -10
  45. package/dist/analysis/bot_key_utils.js +7 -4
  46. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  47. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  48. package/dist/analysis/chain_pool.d.ts +3 -1
  49. package/dist/analysis/chart_ui.d.ts +35 -3
  50. package/dist/analysis/chart_ui.js +43 -4
  51. package/dist/analysis/chart_utils.d.ts +5 -5
  52. package/dist/analysis/chart_utils.js +9 -0
  53. package/dist/analysis/fills_cache.d.ts +4 -24
  54. package/dist/analysis/fills_cache.js +3 -84
  55. package/dist/analysis/fills_source.d.ts +33 -3
  56. package/dist/analysis/fills_source.js +83 -13
  57. package/dist/analysis/grid_correction_check.d.ts +2 -24
  58. package/dist/analysis/grid_correction_check.js +27 -69
  59. package/dist/analysis/math_utils.d.ts +91 -6
  60. package/dist/analysis/math_utils.js +119 -7
  61. package/dist/analysis/pnl_report.js +29 -29
  62. package/dist/analysis/price_sources.d.ts +30 -9
  63. package/dist/analysis/price_sources.js +28 -4
  64. package/dist/analysis/resolve_bot_accounts.js +2 -2
  65. package/dist/analysis/resolve_source.d.ts +1 -1
  66. package/dist/analysis/resolve_source.js +31 -10
  67. package/dist/analysis/trade_profitability.d.ts +29 -2
  68. package/dist/analysis/trade_profitability.js +73 -147
  69. package/dist/analysis/tradingview/analyze_tradingview.d.ts +3 -8
  70. package/dist/analysis/tradingview/analyze_tradingview.js +7 -6
  71. package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
  72. package/dist/analysis/tradingview/grid_reset_config.js +23 -11
  73. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
  74. package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
  75. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  76. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -34
  77. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  78. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +26 -84
  79. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  80. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +16 -41
  81. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
  82. package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
  83. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  84. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  85. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  86. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  87. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  88. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  89. package/dist/analysis/worker_pool.d.ts +38 -0
  90. package/dist/analysis/worker_pool.js +67 -0
  91. package/dist/credential-daemon.js +34 -20
  92. package/dist/dexbot.js +78 -59
  93. package/dist/market_adapter/ama_signal_runner.js +21 -54
  94. package/dist/market_adapter/candle_utils.d.ts +29 -19
  95. package/dist/market_adapter/candle_utils.js +35 -21
  96. package/dist/market_adapter/cli_args.d.ts +22 -0
  97. package/dist/market_adapter/cli_args.js +30 -0
  98. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  99. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  100. package/dist/market_adapter/core/config_normalizers.js +11 -6
  101. package/dist/market_adapter/core/kibana_candles.d.ts +56 -19
  102. package/dist/market_adapter/core/kibana_candles.js +12 -9
  103. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  104. package/dist/market_adapter/core/kibana_client.js +8 -7
  105. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  106. package/dist/market_adapter/core/market_adapter_service.d.ts +320 -153
  107. package/dist/market_adapter/core/market_adapter_service.js +228 -269
  108. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  109. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  110. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  111. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  112. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  113. package/dist/market_adapter/core/strategies/ama.js +2 -4
  114. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  115. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  116. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  117. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  118. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  119. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  120. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
  121. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
  122. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  123. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  124. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  125. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  126. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  127. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  128. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  129. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  130. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  131. package/dist/market_adapter/inputs/fetch_book_data.js +3 -2
  132. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +160 -332
  133. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +50 -8
  134. package/dist/market_adapter/inputs/fetch_lp_data.js +47 -22
  135. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  136. package/dist/market_adapter/inputs/kibana_feed_source.js +26 -41
  137. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  138. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  139. package/dist/market_adapter/inputs/window_cache.d.ts +93 -156
  140. package/dist/market_adapter/inputs/window_cache.js +59 -184
  141. package/dist/market_adapter/interval_utils.d.ts +15 -5
  142. package/dist/market_adapter/interval_utils.js +16 -1
  143. package/dist/market_adapter/log_format.d.ts +6 -6
  144. package/dist/market_adapter/log_format.js +28 -21
  145. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  146. package/dist/market_adapter/lp_chart_core.js +26 -192
  147. package/dist/market_adapter/lp_chart_runner.d.ts +10 -7
  148. package/dist/market_adapter/lp_chart_runner.js +37 -19
  149. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  150. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  151. package/dist/market_adapter/market_adapter.d.ts +94 -32
  152. package/dist/market_adapter/market_adapter.js +94 -120
  153. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  154. package/dist/market_adapter/utils/adapter_client.js +2 -2
  155. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  156. package/dist/market_adapter/utils/chain.d.ts +50 -41
  157. package/dist/market_adapter/utils/chain.js +40 -46
  158. package/dist/market_adapter/utils/data_discovery.d.ts +49 -2
  159. package/dist/market_adapter/utils/data_discovery.js +220 -27
  160. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  161. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  162. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  163. package/dist/market_adapter/utils/file_lock.js +36 -32
  164. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  165. package/dist/market_adapter/utils/month_shards.js +237 -0
  166. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  167. package/dist/market_adapter/utils/native_history.js +35 -28
  168. package/dist/modules/account_bots.d.ts +578 -21
  169. package/dist/modules/account_bots.js +272 -267
  170. package/dist/modules/account_orders.d.ts +79 -30
  171. package/dist/modules/account_orders.js +60 -64
  172. package/dist/modules/authority_resolver.d.ts +12 -2
  173. package/dist/modules/authority_resolver.js +15 -8
  174. package/dist/modules/bitshares-native/chain_client.d.ts +39 -4
  175. package/dist/modules/bitshares-native/chain_client.js +59 -59
  176. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  177. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  178. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  179. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  180. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  181. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  182. package/dist/modules/bitshares-native/index.d.ts +1 -1
  183. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  184. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  185. package/dist/modules/bitshares-native/resolvers.js +22 -25
  186. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  187. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  188. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  189. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  190. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  191. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  192. package/dist/modules/bitshares-native/serial/types.js +73 -108
  193. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  194. package/dist/modules/bitshares-native/signing_client.js +19 -14
  195. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  196. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  197. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  198. package/dist/modules/bitshares-native/transport.js +5 -4
  199. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  200. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  201. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  202. package/dist/modules/bitshares_client.d.ts +45 -13
  203. package/dist/modules/bitshares_client.js +28 -19
  204. package/dist/modules/bot_defaults.d.ts +8 -16
  205. package/dist/modules/bot_defaults.js +1 -5
  206. package/dist/modules/bot_settings.d.ts +44 -10
  207. package/dist/modules/bot_settings.js +11 -8
  208. package/dist/modules/bots_file_lock.d.ts +6 -6
  209. package/dist/modules/bots_file_lock.js +16 -12
  210. package/dist/modules/broadcast_failure.d.ts +4 -3
  211. package/dist/modules/broadcast_failure.js +5 -4
  212. package/dist/modules/chain_keys.d.ts +42 -40
  213. package/dist/modules/chain_keys.js +53 -45
  214. package/dist/modules/chain_orders.d.ts +94 -60
  215. package/dist/modules/chain_orders.js +81 -118
  216. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  217. package/dist/modules/constants.d.ts +534 -32
  218. package/dist/modules/constants.js +35 -48
  219. package/dist/modules/cr_planner.d.ts +41 -3
  220. package/dist/modules/cr_planner.js +1 -5
  221. package/dist/modules/credential_policy.d.ts +68 -8
  222. package/dist/modules/credential_policy.js +37 -31
  223. package/dist/modules/credential_session_cache.d.ts +2 -2
  224. package/dist/modules/credit_pricing.d.ts +43 -6
  225. package/dist/modules/credit_pricing.js +70 -60
  226. package/dist/modules/credit_runtime.d.ts +283 -118
  227. package/dist/modules/credit_runtime.js +500 -231
  228. package/dist/modules/crypto/browser_provider.js +6 -4
  229. package/dist/modules/crypto/node_provider.js +1 -1
  230. package/dist/modules/crypto/pure_scrypt.js +35 -4
  231. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  232. package/dist/modules/crypto/sync.d.ts +9 -9
  233. package/dist/modules/crypto/sync.js +16 -9
  234. package/dist/modules/daemon_node_health.d.ts +4 -3
  235. package/dist/modules/dexbot_class.d.ts +213 -146
  236. package/dist/modules/dexbot_class.js +183 -86
  237. package/dist/modules/dexbot_cow_runtime.d.ts +160 -87
  238. package/dist/modules/dexbot_cow_runtime.js +302 -234
  239. package/dist/modules/dexbot_credential_client.d.ts +19 -18
  240. package/dist/modules/dexbot_credential_client.js +1 -2
  241. package/dist/modules/dexbot_fill_runtime.d.ts +63 -49
  242. package/dist/modules/dexbot_fill_runtime.js +53 -47
  243. package/dist/modules/dexbot_maintenance_runtime.d.ts +127 -71
  244. package/dist/modules/dexbot_maintenance_runtime.js +187 -147
  245. package/dist/modules/dexbot_startup_runtime.d.ts +11 -11
  246. package/dist/modules/dexbot_startup_runtime.js +56 -57
  247. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  248. package/dist/modules/dexbot_state_recovery.js +18 -13
  249. package/dist/modules/fund_registry.d.ts +4 -2
  250. package/dist/modules/fund_registry.js +10 -10
  251. package/dist/modules/general_settings.d.ts +30 -4
  252. package/dist/modules/graceful_shutdown.d.ts +3 -3
  253. package/dist/modules/graceful_shutdown.js +19 -13
  254. package/dist/modules/grid_price_source.d.ts +1 -1
  255. package/dist/modules/key_store.d.ts +14 -8
  256. package/dist/modules/key_store.js +7 -7
  257. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  258. package/dist/modules/launcher/adapter_requirement.js +5 -5
  259. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  260. package/dist/modules/launcher/bot_supervisor.js +12 -11
  261. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  262. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  263. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  264. package/dist/modules/launcher/credential_daemon.js +2 -2
  265. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  266. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  267. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  268. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  269. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  270. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  271. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  272. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  273. package/dist/modules/launcher/supervisor_control.js +4 -2
  274. package/dist/modules/lazy_shim.d.ts +11 -0
  275. package/dist/modules/lazy_shim.js +16 -0
  276. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  277. package/dist/modules/market_adapter_whitelist.js +15 -3
  278. package/dist/modules/node_connect_policy.d.ts +3 -2
  279. package/dist/modules/node_failure_ledger.d.ts +6 -5
  280. package/dist/modules/node_manager.d.ts +41 -11
  281. package/dist/modules/node_manager.js +5 -4
  282. package/dist/modules/order/accounting.d.ts +53 -24
  283. package/dist/modules/order/accounting.js +16 -15
  284. package/dist/modules/order/async_lock.d.ts +5 -2
  285. package/dist/modules/order/async_lock.js +1 -1
  286. package/dist/modules/order/export.d.ts +7 -6
  287. package/dist/modules/order/export.js +1 -7
  288. package/dist/modules/order/format.d.ts +16 -7
  289. package/dist/modules/order/format.js +15 -3
  290. package/dist/modules/order/genesis_policy.d.ts +24 -21
  291. package/dist/modules/order/genesis_policy.js +17 -10
  292. package/dist/modules/order/grid.d.ts +144 -36
  293. package/dist/modules/order/grid.js +226 -145
  294. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  295. package/dist/modules/order/grid_reconcile.js +13 -12
  296. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  297. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  298. package/dist/modules/order/index.d.ts +264 -1
  299. package/dist/modules/order/logger.d.ts +46 -19
  300. package/dist/modules/order/logger.js +38 -49
  301. package/dist/modules/order/logger_state.d.ts +4 -4
  302. package/dist/modules/order/manager.d.ts +232 -191
  303. package/dist/modules/order/manager.js +110 -130
  304. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  305. package/dist/modules/order/processed_fill_store.js +16 -27
  306. package/dist/modules/order/strategy.d.ts +21 -13
  307. package/dist/modules/order/strategy.js +5 -6
  308. package/dist/modules/order/sync_engine.d.ts +91 -33
  309. package/dist/modules/order/sync_engine.js +84 -53
  310. package/dist/modules/order/utils/math.d.ts +157 -102
  311. package/dist/modules/order/utils/math.js +77 -38
  312. package/dist/modules/order/utils/order.d.ts +310 -110
  313. package/dist/modules/order/utils/order.js +153 -126
  314. package/dist/modules/order/utils/slot.d.ts +1 -1
  315. package/dist/modules/order/utils/system.d.ts +156 -26
  316. package/dist/modules/order/utils/system.js +103 -71
  317. package/dist/modules/order/utils/validate.d.ts +89 -41
  318. package/dist/modules/order/utils/validate.js +26 -24
  319. package/dist/modules/order/utils/withPoolRef.d.ts +6 -4
  320. package/dist/modules/order/utils/withPoolRef.js +18 -12
  321. package/dist/modules/order/working_grid.d.ts +14 -13
  322. package/dist/modules/paths.d.ts +1 -4
  323. package/dist/modules/paths.js +33 -61
  324. package/dist/modules/process_discovery.d.ts +1 -1
  325. package/dist/modules/process_discovery.js +2 -1
  326. package/dist/modules/runtime.d.ts +7 -3
  327. package/dist/modules/runtime.js +4 -3
  328. package/dist/modules/runtime_settings.d.ts +14 -11
  329. package/dist/modules/runtime_settings.js +30 -24
  330. package/dist/modules/settings_merge.d.ts +29 -3
  331. package/dist/modules/settings_merge.js +56 -78
  332. package/dist/modules/socket_json_client.d.ts +9 -5
  333. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  334. package/dist/modules/storage/browser_adapter.js +7 -30
  335. package/dist/modules/storage/index.d.ts +1 -1
  336. package/dist/modules/storage/node_adapter.d.ts +45 -27
  337. package/dist/modules/storage/node_adapter.js +9 -9
  338. package/dist/modules/storage/types.d.ts +5 -4
  339. package/dist/modules/types.d.ts +1090 -6
  340. package/dist/modules/types.js +4 -1
  341. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  342. package/dist/modules/utils/asset_symbols.js +2 -1
  343. package/dist/modules/utils/errors.d.ts +9 -0
  344. package/dist/modules/utils/errors.js +24 -4
  345. package/dist/modules/utils/time_range.d.ts +1 -12
  346. package/dist/modules/utils/time_range.js +1 -1
  347. package/dist/modules/validate_profiles.js +53 -43
  348. package/dist/modules/version_notice.d.ts +23 -11
  349. package/dist/modules/version_notice.js +6 -4
  350. package/dist/pm2.d.ts +28 -27
  351. package/dist/pm2.js +61 -40
  352. package/dist/scripts/analyze-credit.d.ts +2 -1
  353. package/dist/scripts/analyze-credit.js +23 -24
  354. package/dist/scripts/analyze-git.js +2 -15
  355. package/dist/scripts/analyze-orders.d.ts +77 -9
  356. package/dist/scripts/analyze-orders.js +65 -40
  357. package/dist/scripts/chart_command.d.ts +27 -18
  358. package/dist/scripts/chart_command.js +15 -13
  359. package/dist/scripts/check_any.d.ts +22 -0
  360. package/dist/scripts/check_any.js +158 -0
  361. package/dist/scripts/diagnose-pool-history.js +13 -13
  362. package/dist/scripts/print_grid.js +0 -1
  363. package/dist/scripts/run-tests.js +39 -8
  364. package/dist/scripts/runner.js +1 -1
  365. package/dist/scripts/sync-version.js +0 -10
  366. package/dist/scripts/test-credit-renewal.js +30 -21
  367. package/dist/scripts/update.d.ts +10 -5
  368. package/dist/scripts/update.js +168 -103
  369. package/dist/scripts/update_dist_freshness.js +1 -0
  370. package/dist/scripts/update_layout.d.ts +61 -0
  371. package/dist/scripts/update_layout.js +180 -0
  372. package/dist/scripts/validate_bots.js +2 -1
  373. package/dist/scripts/verify-browser-bundle.js +8 -0
  374. package/dist/unlock.d.ts +28 -3
  375. package/dist/unlock.js +63 -35
  376. package/docs/BITSHARES_ONBOARDING.md +10 -12
  377. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -2
  378. package/docs/COW_INVARIANTS.md +13 -6
  379. package/docs/DEXBOT_COMPARISON.md +8 -8
  380. package/docs/EVOLUTION.md +10 -8
  381. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  382. package/docs/GRID_RECALCULATION.md +4 -2
  383. package/docs/GRID_RECONCILE.md +14 -3
  384. package/docs/LIFECYCLE.md +11 -11
  385. package/docs/MPA_CREDIT_USAGE.md +22 -3
  386. package/docs/README.md +14 -3
  387. package/docs/WORKFLOW.md +1 -0
  388. package/docs/architecture.md +31 -19
  389. package/docs/developer_guide.md +6 -6
  390. package/market_adapter/README.md +12 -5
  391. package/modules/README.md +4 -1
  392. package/package.json +9 -9
  393. package/scripts/README.md +43 -38
  394. package/tests/README.md +25 -10
  395. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  396. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  397. package/scripts/git-viewer.sh +0 -489
  398. package/scripts/postinstall.js +0 -16
@@ -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, recordOrderPlacement } 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
@@ -320,10 +322,10 @@ class OrderManager {
320
322
  _accountingFailureSignal;
321
323
  _recoveryStateValue;
322
324
  _gridRegenStateValue;
323
- _ordersByTypeCache = null;
324
- _ordersByStateCache = null;
325
- _ordersByTypeCacheVersion = -1;
326
- _ordersByStateCacheVersion = -1;
325
+ _orderIdIndexes = {
326
+ type: { cache: null, version: -1 },
327
+ state: { cache: null, version: -1 },
328
+ };
327
329
  /**
328
330
  * Lazy-compute order-IDs grouped by type.
329
331
  *
@@ -338,48 +340,40 @@ class OrderManager {
338
340
  * next grid-version bump triggers a full rebuild from the real orders.
339
341
  */
340
342
  get _ordersByType() {
341
- if (this._ordersByTypeCache !== null && this._ordersByTypeCacheVersion === this._gridVersion) {
342
- return this._ordersByTypeCache;
343
- }
344
- const byType = {};
345
- for (const key of [ORDER_TYPES.BUY, ORDER_TYPES.SELL, ORDER_TYPES.SPREAD]) {
346
- byType[key] = new Set();
347
- }
348
- for (const [id, o] of this.orders) {
349
- if (byType[o.type])
350
- byType[o.type].add(id);
351
- }
352
- this._ordersByTypeCache = byType;
353
- this._ordersByTypeCacheVersion = this._gridVersion;
354
- return byType;
343
+ return this._getOrderIdIndex('type', [ORDER_TYPES.BUY, ORDER_TYPES.SELL, ORDER_TYPES.SPREAD]);
355
344
  }
356
345
  set _ordersByType(val) {
357
- this._ordersByTypeCache = val;
358
- this._ordersByTypeCacheVersion = this._gridVersion;
346
+ this._orderIdIndexes.type.cache = val;
347
+ this._orderIdIndexes.type.version = this._gridVersion;
359
348
  }
360
349
  /**
361
350
  * Lazy-compute order-IDs grouped by state. Same semantics as
362
351
  * _ordersByType — see getter doc for details.
363
352
  */
364
353
  get _ordersByState() {
365
- if (this._ordersByStateCache !== null && this._ordersByStateCacheVersion === this._gridVersion) {
366
- return this._ordersByStateCache;
367
- }
368
- const byState = {};
369
- for (const key of [ORDER_STATES.VIRTUAL, ORDER_STATES.ACTIVE, ORDER_STATES.PARTIAL]) {
370
- byState[key] = new Set();
371
- }
372
- for (const [id, o] of this.orders) {
373
- if (byState[o.state])
374
- byState[o.state].add(id);
375
- }
376
- this._ordersByStateCache = byState;
377
- this._ordersByStateCacheVersion = this._gridVersion;
378
- return byState;
354
+ return this._getOrderIdIndex('state', [ORDER_STATES.VIRTUAL, ORDER_STATES.ACTIVE, ORDER_STATES.PARTIAL]);
379
355
  }
380
356
  set _ordersByState(val) {
381
- this._ordersByStateCache = val;
382
- this._ordersByStateCacheVersion = this._gridVersion;
357
+ this._orderIdIndexes.state.cache = val;
358
+ this._orderIdIndexes.state.version = this._gridVersion;
359
+ }
360
+ /** Rebuild an order-id index for `field` over `keys`, memoized per `_gridVersion`. */
361
+ _getOrderIdIndex(field, keys) {
362
+ const slot = this._orderIdIndexes[field];
363
+ if (slot.cache !== null && slot.version === this._gridVersion) {
364
+ return slot.cache;
365
+ }
366
+ const index = {};
367
+ for (const key of keys)
368
+ index[key] = new Set();
369
+ for (const [id, o] of this.orders) {
370
+ const key = o[field];
371
+ if (index[key])
372
+ index[key].add(id);
373
+ }
374
+ slot.cache = index;
375
+ slot.version = this._gridVersion;
376
+ return index;
383
377
  }
384
378
  initialSpreadCount;
385
379
  currentSpreadCount;
@@ -577,6 +571,11 @@ class OrderManager {
577
571
  this._gapEvacStreaks = new Map();
578
572
  this._gapEvacCancelQueued = new Set();
579
573
  this._metrics = {
574
+ fillsProcessed: 0,
575
+ batchesExecuted: 0,
576
+ fillProcessingTimeMs: 0,
577
+ lockContentionEvents: 0,
578
+ maxQueueDepth: 0,
580
579
  fundRecalcCount: 0,
581
580
  lockAcquisitions: 0,
582
581
  lockContentionSkips: 0,
@@ -735,7 +734,7 @@ class OrderManager {
735
734
  this._bootstrapping++;
736
735
  }
737
736
  /**
738
- * @returns {any}
737
+ * @returns {unknown}
739
738
  */
740
739
  finishBootstrap() {
741
740
  const result = { hadDrift: false, driftInfo: null };
@@ -796,19 +795,12 @@ class OrderManager {
796
795
  * without rescheduling, so this is the only wake-up for fills enqueued
797
796
  * during a region; the watchdog path must fire it too or a hung broadcast's
798
797
  * queued fills wait for the next fill event.
799
- * Fans out to the legacy single listener plus every registered listener
800
- * (see addBroadcastRegionEndListener): a second wirer must never silently
801
- * displace the fill-queue drain. Guarded so a listener error never escapes
802
- * into a finally/watchdog frame.
798
+ * Fans out to every listener registered via addBroadcastRegionEndListener:
799
+ * a second wirer must never silently displace the fill-queue drain.
800
+ * Guarded so a listener error never escapes into a finally/watchdog frame.
803
801
  * @returns {void}
804
802
  */
805
803
  _fireBroadcastRegionEnd() {
806
- try {
807
- this._onBroadcastRegionEnd?.();
808
- }
809
- catch (err) {
810
- this.logger?.log?.(`[BROADCAST] Region-end hook failed: ${err?.message || err}`, 'warn');
811
- }
812
804
  const listeners = this._onBroadcastRegionEndListeners;
813
805
  if (Array.isArray(listeners)) {
814
806
  for (const listener of listeners) {
@@ -816,15 +808,14 @@ class OrderManager {
816
808
  listener?.();
817
809
  }
818
810
  catch (err) {
819
- this.logger?.log?.(`[BROADCAST] Region-end listener failed: ${err?.message || err}`, 'warn');
811
+ this.logger?.log?.(`[BROADCAST] Region-end listener failed: ${getErrorMessage(err)}`, 'warn');
820
812
  }
821
813
  }
822
814
  }
823
815
  }
824
816
  /**
825
- * Register an additional broadcast-region-end listener without displacing
826
- * the legacy single listener or previously registered ones. Duplicate
827
- * registrations of the same function reference are ignored.
817
+ * Register a broadcast-region-end listener. Duplicate registrations of the
818
+ * same function reference are ignored.
828
819
  * @param {() => void} listener
829
820
  * @returns {void}
830
821
  */
@@ -857,7 +848,7 @@ class OrderManager {
857
848
  * value can lag behind the actual orders state (virtualized orders
858
849
  * release committed capital via updateOptimisticFreeBalance without
859
850
  * triggering a recalc). Reading from the orders map avoids that race.
860
- * @returns {any}
851
+ * @returns {unknown}
861
852
  */
862
853
  getChainFundsSnapshot() {
863
854
  let committedBuy = 0, committedSell = 0;
@@ -1000,7 +991,7 @@ class OrderManager {
1000
991
  return await this.sync.fetchAccountBalancesAndSetTotals();
1001
992
  }
1002
993
  /**
1003
- * @param {any} totals - Account balance totals
994
+ * @param {unknown} totals - Account balance totals
1004
995
  * @returns {Promise<void>}
1005
996
  */
1006
997
  async setAccountTotals(totals = { buy: null, sell: null, buyFree: null, sellFree: null }) {
@@ -1170,7 +1161,7 @@ class OrderManager {
1170
1161
  * @param {Object} info
1171
1162
  * @returns {Promise<any>}
1172
1163
  */
1173
- syncFromOpenOrders(orders, info) {
1164
+ syncFromOpenOrders(orders, info = {}) {
1174
1165
  return this.sync.syncFromOpenOrders(orders, info);
1175
1166
  }
1176
1167
  /**
@@ -1178,7 +1169,7 @@ class OrderManager {
1178
1169
  * @param {Object} [options]
1179
1170
  * @returns {Promise<any>}
1180
1171
  */
1181
- syncFromFillHistory(fill, options) {
1172
+ syncFromFillHistory(fill, options = {}) {
1182
1173
  return this.sync.syncFromFillHistory(fill, options);
1183
1174
  }
1184
1175
  /**
@@ -1186,7 +1177,7 @@ class OrderManager {
1186
1177
  * @param {Object} [options]
1187
1178
  * @returns {Promise<any>}
1188
1179
  */
1189
- syncFromFillHistoryBatch(fills, options) {
1180
+ syncFromFillHistoryBatch(fills, options = {}) {
1190
1181
  return this.sync.syncFromFillHistoryBatch(fills, options);
1191
1182
  }
1192
1183
  /**
@@ -1305,7 +1296,7 @@ class OrderManager {
1305
1296
  this.logger.log(warning.message, 'warn');
1306
1297
  }
1307
1298
  if (!validation.isValid && validation.errors.length > 0) {
1308
- const fatalError = validation.errors.find((e) => e.isFatal || e.code === 'ILLEGAL_SPREAD_STATE');
1299
+ const fatalError = validation.errors.find((e) => e.isFatal === true || getErrorCode(e) === 'ILLEGAL_SPREAD_STATE');
1309
1300
  if (fatalError) {
1310
1301
  this.logger.log(fatalError.message, 'error');
1311
1302
  this._lastIllegalState = {
@@ -1324,9 +1315,9 @@ class OrderManager {
1324
1315
  // Ensure a mutable copy before passing to updateOptimisticFreeBalance.
1325
1316
  // validation.normalizedOrder may reference a frozen master-grid order,
1326
1317
  // and _resolveBtsFeeLifecycle mutates btsFeeState on the order object.
1327
- let nextOrder = { ...validation.normalizedOrder };
1318
+ let nextOrder = { ...(validation.normalizedOrder ?? {}) };
1328
1319
  // Apply phantom order auto-correction to the normalized order
1329
- const phantomError = validation.errors.find((e) => e.code === 'PHANTOM_ORDER');
1320
+ const phantomError = validation.errors.find((e) => getErrorCode(e) === 'PHANTOM_ORDER');
1330
1321
  let accountingSkip = skipAccounting;
1331
1322
  if (phantomError && phantomError.autoCorrect) {
1332
1323
  nextOrder = { ...nextOrder, ...phantomError.autoCorrect };
@@ -1387,18 +1378,6 @@ class OrderManager {
1387
1378
  this._markGridDirty();
1388
1379
  return true;
1389
1380
  }
1390
- /**
1391
- * Backward-compatible accessor for _currentWorkingGrid.
1392
- * Returns the top of the working grid stack (null if empty).
1393
- */
1394
- get _currentWorkingGrid() {
1395
- return this._peekWorkingGrid();
1396
- }
1397
- set _currentWorkingGrid(val) {
1398
- if (val !== null) {
1399
- this._currentWorkingGridStack.push(val);
1400
- }
1401
- }
1402
1381
  _peekWorkingGrid() {
1403
1382
  const stack = this._currentWorkingGridStack;
1404
1383
  return stack.length > 0 ? stack[stack.length - 1] : null;
@@ -1420,7 +1399,7 @@ class OrderManager {
1420
1399
  /**
1421
1400
  * @param {Array<import('./types').Order>} updates - Order updates to apply
1422
1401
  * @param {string} [context] - Update context label
1423
- * @param {any} [options]
1402
+ * @param {unknown} [options]
1424
1403
  * @returns {Promise<boolean>}
1425
1404
  */
1426
1405
  async applyGridUpdateBatch(updates, context = 'batch-update', options = {}) {
@@ -1493,7 +1472,7 @@ class OrderManager {
1493
1472
  return { skipped: true, suspended: true, reason: this._gridPersistenceSuspendedReason };
1494
1473
  }
1495
1474
  const result = await this.persistGrid(undefined);
1496
- if (result && result.skipped === true) {
1475
+ if (result && 'skipped' in result && result.skipped === true) {
1497
1476
  // Persistence was deferred (suspension, validation, etc.) — keep
1498
1477
  // the dirty flag so a later tick can retry.
1499
1478
  return result;
@@ -1724,22 +1703,21 @@ class OrderManager {
1724
1703
  */
1725
1704
  _logBoundaryDebug(source, newIdx) {
1726
1705
  try {
1727
- const self = this;
1728
- const boundary = newIdx == null ? self.boundaryIdx : newIdx;
1706
+ const boundary = newIdx == null ? this.boundaryIdx : newIdx;
1729
1707
  if (boundary == null)
1730
1708
  return;
1731
- const gapSlots = typeof self._gapSlots === 'number' ? self._gapSlots : 0;
1709
+ const gapSlots = typeof this._gapSlots === 'number' ? this._gapSlots : 0;
1732
1710
  const sellStart = boundary + 1 + gapSlots;
1733
1711
  const countActive = (type) => {
1734
1712
  let n = 0;
1735
- for (const o of (self.orders?.values?.() || [])) {
1713
+ for (const o of this.orders.values()) {
1736
1714
  if (o && o.type === type && o.orderId)
1737
1715
  n++;
1738
1716
  }
1739
1717
  return n;
1740
1718
  };
1741
1719
  this.logger?.log?.(`[BOUNDARY] ${source} boundary=${boundary} sellStart=${sellStart} gapSlots=${gapSlots} ` +
1742
- `spreadCount=${self.currentSpreadCount ?? self.initialSpreadCount ?? '?'} ` +
1720
+ `spreadCount=${this.currentSpreadCount ?? this.initialSpreadCount ?? '?'} ` +
1743
1721
  `activeBuy=${countActive(ORDER_TYPES.BUY)} activeSell=${countActive(ORDER_TYPES.SELL)}`, 'debug');
1744
1722
  }
1745
1723
  catch {
@@ -1821,7 +1799,7 @@ class OrderManager {
1821
1799
  let priceSrc = 'direct';
1822
1800
  if (!Number.isFinite(price) || price <= 0) {
1823
1801
  try {
1824
- const slot = f.id ? this.orders?.get?.(f.id) : null;
1802
+ const slot = f.id ? this.orders.get(f.id) : null;
1825
1803
  price = slot ? Number(slot.price) : null;
1826
1804
  if (Number.isFinite(price) && price > 0)
1827
1805
  priceSrc = 'slot-fallback';
@@ -1834,7 +1812,7 @@ class OrderManager {
1834
1812
  continue;
1835
1813
  this._setLastFillPivot(f.type, price, 'fill');
1836
1814
  recorded++;
1837
- lastKind = f?.isPartial === true ? 'partial' : (f?.isPartial === false ? 'full' : 'unknown');
1815
+ lastKind = f.isPartial === true ? 'partial' : (f.isPartial === false ? 'full' : 'unknown');
1838
1816
  lastPriceSrc = priceSrc;
1839
1817
  }
1840
1818
  // One line per fill batch (chunk): the pivot mutations above are otherwise
@@ -1954,14 +1932,14 @@ class OrderManager {
1954
1932
  * @param {Function} batchCb - Batch callback
1955
1933
  * @returns {Promise<Object>}
1956
1934
  */
1957
- async checkSpreadCondition(BitShares, batchCb) {
1935
+ async checkSpreadCondition(BitShares, batchCb = null) {
1958
1936
  return await checkSpreadCondition(this, BitShares, batchCb);
1959
1937
  }
1960
1938
  /**
1961
1939
  * @param {Function} batchCb - Batch callback
1962
1940
  * @returns {Promise<Object>}
1963
1941
  */
1964
- async checkGridHealth(batchCb) {
1942
+ async checkGridHealth(batchCb = null) {
1965
1943
  return await checkGridHealth(this, batchCb);
1966
1944
  }
1967
1945
  /**
@@ -1971,7 +1949,7 @@ class OrderManager {
1971
1949
  return calculateCurrentSpread(this);
1972
1950
  }
1973
1951
  /**
1974
- * @returns {any}
1952
+ * @returns {unknown}
1975
1953
  */
1976
1954
  checkFundDriftAfterFills() {
1977
1955
  if (!this.assets || !hasValidAccountTotals(this.accountTotals)) {
@@ -1981,7 +1959,7 @@ class OrderManager {
1981
1959
  }
1982
1960
  /**
1983
1961
  * @param {Object|number} [pipelineSignals] - Pipeline state signals or queue length
1984
- * @returns {any}
1962
+ * @returns {unknown}
1985
1963
  */
1986
1964
  isPipelineEmpty(pipelineSignals = 0) {
1987
1965
  const normalizedSignals = (typeof pipelineSignals === 'number')
@@ -2100,7 +2078,8 @@ class OrderManager {
2100
2078
  const boundary = this.boundaryIdx;
2101
2079
  const gapSlots = this._gapSlots;
2102
2080
  let queued = 0;
2103
- for (const candidate of candidates) {
2081
+ for (const raw of candidates) {
2082
+ const candidate = raw;
2104
2083
  const slotId = candidate?.id;
2105
2084
  const chainOrderId = candidate?.orderId;
2106
2085
  if (!slotId || !chainOrderId)
@@ -2276,6 +2255,7 @@ class OrderManager {
2276
2255
  gridVersion: this._gridVersion,
2277
2256
  boundaryIdx: this.boundaryIdx,
2278
2257
  funds: this.getChainFundsSnapshot(),
2258
+ manager: this,
2279
2259
  fills,
2280
2260
  excludeIds,
2281
2261
  gapSlots: this._gapSlots,
@@ -2487,7 +2467,7 @@ class OrderManager {
2487
2467
  /**
2488
2468
  * @param {Object} [options]
2489
2469
  * @param {boolean} [options.allowBootstrapTransient]
2490
- * @returns {any}
2470
+ * @returns {unknown}
2491
2471
  */
2492
2472
  validateGridStateForPersistence(options = {}) {
2493
2473
  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;