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
@@ -13,7 +13,7 @@ const { readOpenOrdersWithMetaSafe } = chainOrdersModule;
13
13
  import { BroadcastUncertainError as BroadcastUncertainErrorBinding } from './dexbot_credential_client.js';
14
14
  const BroadcastUncertainError = BroadcastUncertainErrorBinding;
15
15
  import * as orderUtils from './order/utils/order.js';
16
- import { sleep, setLastFillPivot } from './order/utils/system.js';
16
+ import { sleep, setLastFillPivot, fireStructuralResync } from './order/utils/system.js';
17
17
  const { buildCreateOrderArgs, buildCreateOpFingerprint, extractBatchOperationResults, formatUnmatchedChainOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, buildOutsideInPairGroups, isOrderPlaced, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, } = orderUtils;
18
18
  import * as validate from './order/utils/validate.js';
19
19
  const { validateCreateTargetSlots, evaluateCommit, hasExecutableActions, stampGapEvacuationRotation } = validate;
@@ -59,7 +59,7 @@ function hasSlotPriceCollision(items, targetPrice, precision, excludeId, predica
59
59
  if (p == null)
60
60
  continue;
61
61
  try {
62
- if (priceSlotEqual(p, targetPrice, precision))
62
+ if (priceSlotEqual(Number(p), targetPrice, precision))
63
63
  return it;
64
64
  }
65
65
  catch {
@@ -70,13 +70,13 @@ function hasSlotPriceCollision(items, targetPrice, precision, excludeId, predica
70
70
  return null;
71
71
  }
72
72
  import * as constantsModule from './constants.js';
73
- const { COW_ACTIONS, COW_PERFORMANCE, ORDER_STATES, ORDER_TYPES, REBALANCE_STATES, } = constantsModule;
73
+ const { COW_ACTIONS, COW_ORIGINS, COW_PERFORMANCE, ORDER_STATES, ORDER_TYPES, REBALANCE_STATES, } = constantsModule;
74
74
  import { acquireIfNotHeld } from './order/async_lock.js';
75
75
  import * as FormatModule from './order/format.js';
76
76
  const Format = FormatModule;
77
77
  import * as workingGridModule from './order/working_grid.js';
78
78
  const { WorkingGrid } = workingGridModule;
79
- import { getErrorMessage, resolveSeamMs, resolveSeamMsOrNull } from './utils/errors.js';
79
+ import { getErrorMessage, resolveSeamMs, resolveSeamMsOrNull, getErrorField } from './utils/errors.js';
80
80
  // Maximum number of times the pre-broadcast staleness guard may re-plan the
81
81
  // batch from a fresh master before proceeding anyway. Bounded so a master
82
82
  // grid that keeps mutating (fill bursts, sync loops) can never livelock the
@@ -116,7 +116,7 @@ function buildOutsideInPairGroupsForCreateEntries(createEntries) {
116
116
  function buildOutsideInPairGroupsWithAdapter(items, toOrder) {
117
117
  return buildOutsideInPairGroups(items, {
118
118
  isValid: (item) => Boolean(toOrder(item)),
119
- getType: (item) => toOrder(item)?.type,
119
+ getType: (item) => String(toOrder(item)?.type ?? ''),
120
120
  getPrice: (item) => toOrder(item)?.price,
121
121
  });
122
122
  }
@@ -169,7 +169,7 @@ function getPendingBroadcasts(bot) {
169
169
  function findChainOrderForPendingEntry(bot, chainSnapshot, entry) {
170
170
  if (!entry?.slotId)
171
171
  return null;
172
- return findChainOrderForSlot(bot, chainSnapshot, entry.slotId, {
172
+ return findChainOrderForSlot(bot, chainSnapshot, String(entry.slotId), {
173
173
  sell: entry.finalInts?.sell,
174
174
  receive: entry.finalInts?.receive,
175
175
  orderType: entry.orderType,
@@ -225,9 +225,10 @@ function extractOperationResults(result, warnContext = '', logFn = null) {
225
225
  if (Array.isArray(extracted))
226
226
  return extracted;
227
227
  if (result && logFn) {
228
+ const resultObj = result;
228
229
  const resultType = Array.isArray(result) ? 'array' : typeof result;
229
230
  const keySummary = (resultType === 'object' && !Array.isArray(result))
230
- ? Object.keys(result).slice(0, 8).join(',')
231
+ ? Object.keys(resultObj).slice(0, 8).join(',')
231
232
  : '';
232
233
  const contextSuffix = warnContext ? ` (${warnContext})` : '';
233
234
  const keysSuffix = keySummary ? `; keys=[${keySummary}]` : '';
@@ -264,11 +265,11 @@ function findMissingCreateResultContexts(operationResults, opContexts) {
264
265
  function markMissingCreateResultsAsStructuralBlocker(bot, missingCreateResults) {
265
266
  const blockers = Array.isArray(missingCreateResults)
266
267
  ? missingCreateResults.map((item) => {
267
- const order = item.ctx?.order || {};
268
+ const order = (item.ctx?.order ?? {});
268
269
  const fingerprint = [
269
270
  `type=${order.type || 'unknown'}`,
270
- `price=${Format.formatPrice6(order.price)}`,
271
- `size=${Format.formatAmount(order.size)}`
271
+ `price=${Format.formatPrice6(Number(order.price))}`,
272
+ `size=${Format.formatAmount(Number(order.size))}`
272
273
  ].join(',');
273
274
  return {
274
275
  chainOrderId: 'unknown',
@@ -319,7 +320,7 @@ function formatUnmatchedChainOrderForLog(order) {
319
320
  * in production (always null), so batchId scoping cannot discriminate.
320
321
  */
321
322
  function recordPendingBroadcast(bot, entry) {
322
- if (!bot.manager || !entry || !entry.order)
323
+ if (!bot.manager || !entry || !entry.order || !entry.finalInts)
323
324
  return null;
324
325
  if (!bot.manager._pendingBroadcasts || !(bot.manager._pendingBroadcasts instanceof Map)) {
325
326
  bot.manager._pendingBroadcasts = new Map();
@@ -338,7 +339,7 @@ function recordPendingBroadcast(bot, entry) {
338
339
  orderType: entry.order.type,
339
340
  order: entry.order,
340
341
  finalInts: entry.finalInts,
341
- batchId: bot._currentBatchId || null,
342
+ batchId: bot._currentBatchId != null ? String(bot._currentBatchId) : null,
342
343
  recordedAt: Date.now()
343
344
  });
344
345
  return fingerprint;
@@ -366,7 +367,7 @@ function crossedOrderLabel(crossed) {
366
367
  const orderId = crossed.orderId || crossed.chainOrderId || 'n/a';
367
368
  const type = crossed.type || crossed.order?.type || 'unknown';
368
369
  const price = crossed.price ?? crossed.order?.price;
369
- return `${type} ${id} (${orderId}) @${price != null ? Format.formatPrice6(price) : 'n/a'}`;
370
+ return `${type} ${id} (${orderId}) @${price != null ? Format.formatPrice6(Number(price)) : 'n/a'}`;
370
371
  }
371
372
  /**
372
373
  * Build the candidate set for crossing-placement checks: master orders
@@ -384,7 +385,7 @@ function crossedOrderLabel(crossed) {
384
385
  * predicates would blind the guard to them — the shared
385
386
  * isCrossingCheckCandidate predicate accepts slot-id-only wrappers.
386
387
  * @param {Object} bot
387
- * @returns {any[]}
388
+ * @returns {unknown[]}
388
389
  */
389
390
  function buildCrossingCandidates(bot) {
390
391
  return orderUtils.buildCrossingCheckCandidates(bot?.manager);
@@ -563,7 +564,7 @@ function findChainOrderForSlot(bot, chainOrders, slotId, planned) {
563
564
  const targetReceive = Number(planned.receive);
564
565
  const plannedSide = planned.orderType ||
565
566
  planned.side ||
566
- bot.manager._pendingBroadcasts?.get?.(planned.fingerprint)?.orderType ||
567
+ bot.manager._pendingBroadcasts?.get?.(String(planned.fingerprint))?.orderType ||
567
568
  bot.manager.orders.get(slotId)?.type;
568
569
  if (plannedSide !== 'buy' && plannedSide !== 'sell') {
569
570
  return null;
@@ -641,7 +642,7 @@ async function matchPendingToChain(bot, pending, chainSnapshot, opContexts, acco
641
642
  for (const entry of pending) {
642
643
  if (adoptedSlotIds.has(entry.slotId))
643
644
  continue;
644
- const fp = buildChainOrderFingerprint(bot, o, entry.slotId);
645
+ const fp = buildChainOrderFingerprint(bot, o, String(entry.slotId));
645
646
  if (fp && bot.manager._pendingBroadcasts?.has(fp)) {
646
647
  adopted.push({ entry, match: o });
647
648
  adoptedSlotIds.add(entry.slotId);
@@ -657,7 +658,7 @@ async function matchPendingToChain(bot, pending, chainSnapshot, opContexts, acco
657
658
  // landed between the initial read and this point (TOCTOU window).
658
659
  if (discarded.length > 0 && typeof chainOrders.readOpenOrders === 'function') {
659
660
  const createDiscarded = discarded.filter((e) => {
660
- const ctx = opContexts[e.ctxIndex];
661
+ const ctx = opContexts[e.ctxIndex ?? -1];
661
662
  return ctx && ctx.kind === 'create';
662
663
  });
663
664
  if (createDiscarded.length > 0) {
@@ -681,7 +682,7 @@ async function matchPendingToChain(bot, pending, chainSnapshot, opContexts, acco
681
682
  const freshChain = freshRead.orders;
682
683
  const remainingDiscarded = [];
683
684
  for (const entry of discarded) {
684
- const ctx = opContexts[entry.ctxIndex];
685
+ const ctx = opContexts[entry.ctxIndex ?? -1];
685
686
  if (ctx && ctx.kind === 'create') {
686
687
  const match = findChainOrderForPendingEntry(bot, freshChain, entry);
687
688
  if (match) {
@@ -719,14 +720,14 @@ async function adoptMatchedEntries(bot, adopted, opContexts) {
719
720
  let adoptedCount = 0;
720
721
  for (const { entry, match } of adopted) {
721
722
  adoptedCount++;
722
- const plannedOpCtx = opContexts[entry.ctxIndex];
723
+ const plannedOpCtx = opContexts[entry.ctxIndex ?? -1];
723
724
  if (plannedOpCtx && plannedOpCtx.kind === 'create') {
724
725
  const chainOrderId = match.id;
725
726
  const expectedType = plannedOpCtx.order?.type || entry.orderType;
726
727
  try {
727
728
  const btsFeeData = getAssetFeesSafe('BTS');
728
729
  await bot.manager.synchronizeWithChain({
729
- gridOrderId: plannedOpCtx.order?.id || entry.slotId,
730
+ gridOrderId: plannedOpCtx.order?.id || String(entry.slotId),
730
731
  chainOrderId,
731
732
  expectedType,
732
733
  fee: btsFeeData?.createFee || 0,
@@ -734,12 +735,12 @@ async function adoptMatchedEntries(bot, adopted, opContexts) {
734
735
  }, 'createOrder');
735
736
  }
736
737
  catch (syncErr) {
737
- bot.manager.logger.log(`[COW][UNCERTAIN] Failed to adopt matched order ${chainOrderId} for slot ${entry.slotId}: ${syncErr?.message || syncErr}`, 'error');
738
+ bot.manager.logger.log(`[COW][UNCERTAIN] Failed to adopt matched order ${chainOrderId} for slot ${entry.slotId}: ${getErrorMessage(syncErr)}`, 'error');
738
739
  }
739
740
  }
740
741
  // Remove from pending broadcasts — matched entries are resolved.
741
- if (entry.fingerprint && bot.manager._pendingBroadcasts?.has(entry.fingerprint)) {
742
- bot.manager._pendingBroadcasts.delete(entry.fingerprint);
742
+ if (entry.fingerprint != null && bot.manager._pendingBroadcasts?.has(String(entry.fingerprint))) {
743
+ bot.manager._pendingBroadcasts.delete(String(entry.fingerprint));
743
744
  }
744
745
  }
745
746
  return adoptedCount;
@@ -757,7 +758,7 @@ async function restoreDiscardedCreates(bot, discarded, opContexts) {
757
758
  let discardedCount = 0;
758
759
  for (const entry of discarded) {
759
760
  discardedCount++;
760
- const plannedOpCtx = opContexts[entry.ctxIndex];
761
+ const plannedOpCtx = opContexts[entry.ctxIndex ?? -1];
761
762
  // A pending-broadcast entry is always a CREATE (recordPendingBroadcast
762
763
  // only records creates), so the slot restore below must not depend on
763
764
  // opContexts being present: the PENDING_BROADCASTS reject path invokes
@@ -791,7 +792,7 @@ async function restoreDiscardedCreates(bot, discarded, opContexts) {
791
792
  // funds. The next sync's orphan adoption reconciles a
792
793
  // landed order into this slot cleanly.
793
794
  bot.manager.logger.log(`[COW][UNCERTAIN] Restored creation-uncertain state for slot ${entry.slotId} ` +
794
- `(type=${plannedType}, size: ${entry.order.size}); next sync adoption will reconcile any landed order`, 'warn');
795
+ `(type=${plannedType}, size: ${entry.order.size}); next sync adoption will reconcile landed orders`, 'warn');
795
796
  const updates = [{
796
797
  ...slot,
797
798
  type: plannedType,
@@ -842,7 +843,7 @@ async function restoreDiscardedCreates(bot, discarded, opContexts) {
842
843
  const missingType = entry.order.type;
843
844
  if (missingType === ORDER_TYPES.BUY || missingType === ORDER_TYPES.SELL) {
844
845
  bot.manager.logger.log(`[COW][UNCERTAIN] Slot ${entry.order.id} missing from master after discard — materializing creation-uncertain state ` +
845
- `(type=${missingType}, size: ${entry.order.size}); next sync adoption will reconcile any landed order`, 'warn');
846
+ `(type=${missingType}, size: ${entry.order.size}); next sync adoption will reconcile landed orders`, 'warn');
846
847
  const updates = [{
847
848
  id: entry.order.id,
848
849
  type: missingType,
@@ -858,24 +859,24 @@ async function restoreDiscardedCreates(bot, discarded, opContexts) {
858
859
  }
859
860
  }
860
861
  else {
861
- bot.manager.logger.log(`[COW][UNCERTAIN] Slot ${entry.order.id} missing from master after discard with unrecognized type ${missingType} — cannot reconstruct creation-uncertain state; next sync must adopt any landed order as an orphan`, 'error');
862
+ bot.manager.logger.log(`[COW][UNCERTAIN] Slot ${entry.order.id} missing from master after discard with unrecognized type ${missingType} — cannot reconstruct creation-uncertain state; next sync must adopt a landed order as an orphan`, 'error');
862
863
  }
863
864
  }
864
865
  }
865
866
  else {
866
- bot.manager.logger.log(`[COW][UNCERTAIN] Discarded CREATE for slot ${entry.slotId} has no usable placement descriptor (id=${entry.order?.id ?? 'none'}, size=${entry.order?.size ?? 'none'}, type=${entry.order?.type ?? 'none'}) — nothing restored; next sync must adopt any landed order as an orphan`, 'error');
867
+ bot.manager.logger.log(`[COW][UNCERTAIN] Discarded CREATE for slot ${entry.slotId} has no usable placement descriptor (id=${entry.order?.id ?? 'none'}, size=${entry.order?.size ?? 'none'}, type=${entry.order?.type ?? 'none'}) — nothing restored; next sync must adopt a landed order as an orphan`, 'error');
867
868
  }
868
869
  }
869
870
  catch (restoreErr) {
870
- bot.manager.logger.log(`[COW][UNCERTAIN] Failed to restore slot ${entry.slotId} after discard: ${restoreErr?.message || restoreErr}`, 'error');
871
+ bot.manager.logger.log(`[COW][UNCERTAIN] Failed to restore slot ${entry.slotId} after discard: ${getErrorMessage(restoreErr)}`, 'error');
871
872
  }
872
873
  }
873
874
  else {
874
- bot.manager.logger.log(`[COW][UNCERTAIN] Discarded pending broadcast for slot ${entry.slotId} is not a recognizable CREATE (no create opContext, no order id/type) — skipping restore; next sync must adopt any landed order as an orphan`, 'error');
875
+ bot.manager.logger.log(`[COW][UNCERTAIN] Discarded pending broadcast for slot ${entry.slotId} is not a recognizable CREATE (no create opContext, no order id/type) — skipping restore; next sync must adopt a landed order as an orphan`, 'error');
875
876
  }
876
877
  // Remove from pending broadcasts.
877
- if (entry.fingerprint && bot.manager._pendingBroadcasts?.has(entry.fingerprint)) {
878
- bot.manager._pendingBroadcasts.delete(entry.fingerprint);
878
+ if (entry.fingerprint != null && bot.manager._pendingBroadcasts?.has(String(entry.fingerprint))) {
879
+ bot.manager._pendingBroadcasts.delete(String(entry.fingerprint));
879
880
  }
880
881
  }
881
882
  // 4. If some entries remain unresolved (broadcasts that point to opContext
@@ -911,11 +912,22 @@ async function resyncIfUnreconciled(bot, err, pending, chainSnapshot, adopted, a
911
912
  // chain snapshot.
912
913
  const alreadyScheduled = bot._structuralGridResyncRunning || bot._structuralGridResyncTimer;
913
914
  if (!alreadyScheduled && chainSnapshot.length > 0) {
915
+ // "Unreconciled" must mean chain orders absent from MASTER, not merely
916
+ // absent from this batch's adopted set. Every resting order master
917
+ // already tracks is reconciled by definition; counting those as
918
+ // unreconciled forced a structural resync (grid rebuild + LAST-FILL
919
+ // pivot clear) after every uncertain broadcast on a populated grid.
914
920
  const reconciledOrderIds = new Set(adopted.map((a) => a.match?.id).filter(Boolean));
921
+ try {
922
+ const known = collectKnownOnChainOrderIds(bot.manager, null, null).masterIds;
923
+ for (const id of known)
924
+ reconciledOrderIds.add(id);
925
+ }
926
+ catch { /* best-effort: fall back to the adopted-only set */ }
915
927
  const unreconciledCount = chainSnapshot.filter((o) => !reconciledOrderIds.has(o.id)).length;
916
928
  if (unreconciledCount > 0) {
917
- bot.manager.logger.log(`[COW][UNCERTAIN] ${unreconciledCount} chain order(s) remain unreconciled after uncertain broadcast recovery. ` +
918
- `These may be legitimate pre-existing orders or leftovers from a prior cycle. Requesting structural resync.`, 'warn');
929
+ bot.manager.logger.log(`[COW][UNCERTAIN] ${unreconciledCount} chain order(s) unknown to master remain after uncertain ` +
930
+ `broadcast recovery (neither adopted nor tracked). Requesting structural resync.`, 'warn');
919
931
  await requestStructuralResync(bot, 'unreconciled orders after uncertain broadcast', {
920
932
  batchId: err?.batchId || null,
921
933
  pendingCount: pending.length,
@@ -958,9 +970,9 @@ async function reconcileAfterUncertainBroadcastImpl(bot, err, opContexts, _optio
958
970
  chainReadTruncated = chainRead.truncated;
959
971
  }
960
972
  catch (readErr) {
961
- bot.manager.logger.log(`[COW][UNCERTAIN] readOpenOrders failed: ${readErr?.message || readErr}. ` +
973
+ bot.manager.logger.log(`[COW][UNCERTAIN] readOpenOrders failed: ${getErrorMessage(readErr)}. ` +
962
974
  `Falling back to structural resync.`, 'error');
963
- await requestStructuralResync(bot, 'broadcast uncertain — readOpenOrders failed', { batchId: err?.batchId || null, error: readErr?.message || String(readErr) });
975
+ await requestStructuralResync(bot, 'broadcast uncertain — readOpenOrders failed', { batchId: err?.batchId || null, error: getErrorMessage(readErr) || String(readErr) });
964
976
  clearPendingBroadcasts(bot.manager?._pendingBroadcasts);
965
977
  return { executed: false, hadRotation: false, uncertain: true };
966
978
  }
@@ -981,7 +993,7 @@ async function reconcileAfterUncertainBroadcastImpl(bot, err, opContexts, _optio
981
993
  // second pass, and a TOCTOU re-read for discarded CREATEs (see
982
994
  // matchPendingToChain). A deferred re-read returns its result directly.
983
995
  const matched = await matchPendingToChain(bot, pending, chainSnapshot, opContexts, accountRef, err);
984
- if (matched.deferred)
996
+ if ('deferred' in matched)
985
997
  return matched.deferred;
986
998
  const { adopted, discarded } = matched;
987
999
  // 3b. Apply decisions
@@ -999,7 +1011,7 @@ async function reconcileAfterUncertainBroadcastImpl(bot, err, opContexts, _optio
999
1011
  await bot.manager.persistGrid();
1000
1012
  }
1001
1013
  catch (persistErr) {
1002
- bot.manager.logger.log(`[COW][UNCERTAIN] Persist after reconcile failed: ${persistErr?.message || persistErr}`, 'error');
1014
+ bot.manager.logger.log(`[COW][UNCERTAIN] Persist after reconcile failed: ${getErrorMessage(persistErr)}`, 'error');
1003
1015
  }
1004
1016
  }
1005
1017
  }
@@ -1023,9 +1035,9 @@ function shouldExecuteCreatePairMode(_bot, opContexts) {
1023
1035
  let hasBuy = false;
1024
1036
  let hasSell = false;
1025
1037
  for (const ctx of opContexts) {
1026
- if (ctx.order.type === ORDER_TYPES.BUY)
1038
+ if (ctx.order?.type === ORDER_TYPES.BUY)
1027
1039
  hasBuy = true;
1028
- if (ctx.order.type === ORDER_TYPES.SELL)
1040
+ if (ctx.order?.type === ORDER_TYPES.SELL)
1029
1041
  hasSell = true;
1030
1042
  if (hasBuy && hasSell)
1031
1043
  return true;
@@ -1062,11 +1074,13 @@ function verifyOpAgainstChain(bot, freshChain, ctx) {
1062
1074
  function verifyCreateAbsent(bot, freshChain, ctx) {
1063
1075
  if (!ctx.finalInts || !ctx.order)
1064
1076
  return 'absent';
1065
- const match = findChainOrderForSlot(bot, freshChain, ctx.order.id, {
1066
- sell: ctx.finalInts.sell,
1067
- receive: ctx.finalInts.receive,
1068
- orderType: ctx.order.type,
1069
- fingerprint: createOpFingerprintForSlot(bot, ctx.order, ctx.finalInts, ctx.order.id)
1077
+ const finalInts = ctx.finalInts;
1078
+ const order = ctx.order;
1079
+ const match = findChainOrderForSlot(bot, freshChain, order.id, {
1080
+ sell: finalInts.sell,
1081
+ receive: finalInts.receive,
1082
+ orderType: order.type,
1083
+ fingerprint: createOpFingerprintForSlot(bot, order, finalInts, order.id)
1070
1084
  });
1071
1085
  return match ? 'landed' : 'absent';
1072
1086
  }
@@ -1093,12 +1107,14 @@ function verifyCancelLanded(freshChain, ctx) {
1093
1107
  * concurrently) → 'unknown' (defer).
1094
1108
  */
1095
1109
  function verifyUpdateUnapplied(freshChain, ctx) {
1110
+ const updateInfo = ctx.updateInfo;
1111
+ const rotation = ctx.rotation;
1096
1112
  const chainOrderId = ctx.kind === 'size-update'
1097
- ? ctx.updateInfo?.partialOrder?.orderId
1098
- : ctx.rotation?.oldOrder?.orderId;
1113
+ ? (updateInfo?.partialOrder?.orderId)
1114
+ : (rotation?.oldOrder?.orderId);
1099
1115
  const cachedRaw = ctx.kind === 'size-update'
1100
- ? ctx.updateInfo?.partialOrder?.rawOnChain
1101
- : ctx.rotation?.oldOrder?.rawOnChain;
1116
+ ? (updateInfo?.partialOrder?.rawOnChain)
1117
+ : (rotation?.oldOrder?.rawOnChain);
1102
1118
  if (!chainOrderId)
1103
1119
  return 'unknown';
1104
1120
  const chainOrder = freshChain.find((o) => String(o?.id ?? '') === String(chainOrderId));
@@ -1134,7 +1150,7 @@ async function executeWithRetryOnUncertain(bot, operations, opContexts) {
1134
1150
  }
1135
1151
  catch (err) {
1136
1152
  const isRetriable = err instanceof BroadcastUncertainError
1137
- && !err.partialOnChainState
1153
+ && !getErrorField(err, 'partialOnChainState')
1138
1154
  && attempt <= MAX_RETRIES;
1139
1155
  if (isRetriable) {
1140
1156
  // Verify per operation kind against a live snapshot before
@@ -1165,7 +1181,7 @@ async function executeWithRetryOnUncertain(bot, operations, opContexts) {
1165
1181
  }
1166
1182
  }
1167
1183
  catch (verifyErr) {
1168
- bot.manager.logger.log(`[COW] Pre-retry chain verification failed (non-fatal): ${verifyErr?.message || verifyErr}`, 'warn');
1184
+ bot.manager.logger.log(`[COW] Pre-retry chain verification failed (non-fatal): ${getErrorMessage(verifyErr)}`, 'warn');
1169
1185
  }
1170
1186
  if (absence === 'absent') {
1171
1187
  bot.manager.logger.log(`[COW] Broadcast uncertain (attempt ${attempt}/${MAX_RETRIES + 1}); verified unapplied on chain, retrying...`, 'warn');
@@ -1209,17 +1225,18 @@ async function executeWithRetryOnUncertain(bot, operations, opContexts) {
1209
1225
  function formatPartialBroadcastSummary(err) {
1210
1226
  if (!err || typeof err !== 'object')
1211
1227
  return '?/?';
1212
- if (err.chunkedBroadcast === true) {
1213
- const total = Number.isFinite(Number(err.chunksTotal)) ? Number(err.chunksTotal) : null;
1214
- const failed = Number.isFinite(Number(err.chunksFailed)) ? Number(err.chunksFailed) : 0;
1215
- const aborted = Number.isFinite(Number(err.chunksAborted)) ? Number(err.chunksAborted) : 0;
1228
+ const info = err;
1229
+ if (info.chunkedBroadcast === true) {
1230
+ const total = Number.isFinite(Number(info.chunksTotal)) ? Number(info.chunksTotal) : null;
1231
+ const failed = Number.isFinite(Number(info.chunksFailed)) ? Number(info.chunksFailed) : 0;
1232
+ const aborted = Number.isFinite(Number(info.chunksAborted)) ? Number(info.chunksAborted) : 0;
1216
1233
  if (total === null)
1217
1234
  return '?/? chunks broadcast';
1218
1235
  const broadcast = Math.max(0, total - failed - aborted);
1219
1236
  return `${broadcast}/${total} chunks broadcast`;
1220
1237
  }
1221
- const broadcast = err.groupsBroadcast;
1222
- const total = err.groupsTotal;
1238
+ const broadcast = info.groupsBroadcast;
1239
+ const total = info.groupsTotal;
1223
1240
  return `${broadcast ?? '?'}/${total ?? '?'} groups broadcast`;
1224
1241
  }
1225
1242
  /**
@@ -1298,13 +1315,14 @@ async function executeChunkedWithRetryOnUncertain(bot, operations, opContexts) {
1298
1315
  }
1299
1316
  catch (err) {
1300
1317
  if (firstFailure === null)
1301
- firstFailure = { index: idx, err };
1318
+ firstFailure = { index: idx, err: err };
1302
1319
  failedChunkCount++;
1303
- const failedChunkLandedOps = Number.isFinite(Number(err.broadcastedOperationCount))
1304
- ? Number(err.broadcastedOperationCount)
1320
+ const rawFailedChunkLandedOps = getErrorField(err, 'broadcastedOperationCount');
1321
+ const failedChunkLandedOps = Number.isFinite(Number(rawFailedChunkLandedOps))
1322
+ ? Number(rawFailedChunkLandedOps)
1305
1323
  : 0;
1306
1324
  landedOpsFromFailures += failedChunkLandedOps;
1307
- if (err.partialOnChainState === true || failedChunkLandedOps > 0)
1325
+ if (getErrorField(err, 'partialOnChainState') === true || failedChunkLandedOps > 0)
1308
1326
  anyFailurePartial = true;
1309
1327
  if (err instanceof BroadcastUncertainError) {
1310
1328
  // Uncertainty: the tx result is unknown — the chunk may or may
@@ -1395,10 +1413,11 @@ async function executeOperationsWithStrategy(bot, operations, opContexts) {
1395
1413
  const groupsTotal = groups.length;
1396
1414
  const broadcastedOperationCount = mergedContexts.length;
1397
1415
  bot.manager.logger.log(`[COW] Grouped create execution failed at group ${idx + 1}/${groupsTotal}; ${groupsBroadcast} group(s) already broadcast (${broadcastedOperationCount} op context(s)). Partial on-chain state is possible.`, 'error');
1398
- err.partialOnChainState = groupsBroadcast > 0;
1399
- err.groupsBroadcast = groupsBroadcast;
1400
- err.groupsTotal = groupsTotal;
1401
- err.broadcastedOperationCount = broadcastedOperationCount;
1416
+ const broadcastErrAugment = err;
1417
+ broadcastErrAugment.partialOnChainState = groupsBroadcast > 0;
1418
+ broadcastErrAugment.groupsBroadcast = groupsBroadcast;
1419
+ broadcastErrAugment.groupsTotal = groupsTotal;
1420
+ broadcastErrAugment.broadcastedOperationCount = broadcastedOperationCount;
1402
1421
  throw err;
1403
1422
  }
1404
1423
  const groupOpResults = extractOperationResults(groupResult, '', bot.manager?.logger?.log?.bind(bot.manager?.logger));
@@ -1438,25 +1457,30 @@ function validateOperationFunds(bot, operations, assetA, assetB) {
1438
1457
  snap = { chainFreeSell: 0, chainFreeBuy: 0 };
1439
1458
  bot.manager?.logger?.log?.('[COW][VALIDATION] getChainFundsSnapshot unavailable — fund validation skipped (assuming no balance)', 'warn');
1440
1459
  }
1441
- const netRequiredFunds = { [assetA.id]: 0, [assetB.id]: 0 };
1442
- const runningRequiredFunds = { [assetA.id]: 0, [assetB.id]: 0 };
1443
- const peakRequiredFunds = { [assetA.id]: 0, [assetB.id]: 0 };
1460
+ const assetKeyA = assetA.id ?? '';
1461
+ const assetKeyB = assetB.id ?? '';
1462
+ const netRequiredFunds = { [assetKeyA]: 0, [assetKeyB]: 0 };
1463
+ const runningRequiredFunds = { [assetKeyA]: 0, [assetKeyB]: 0 };
1464
+ const peakRequiredFunds = { [assetKeyA]: 0, [assetKeyB]: 0 };
1444
1465
  for (const op of operations) {
1445
- if (!op?.op_data)
1466
+ const opData = op?.op_data;
1467
+ if (!opData)
1446
1468
  continue;
1447
1469
  let sellAssetId = null;
1448
- let sellAmountInt = 0;
1470
+ let sellAmountInt = null;
1449
1471
  if (op.op_name === 'limit_order_create') {
1450
- sellAssetId = op.op_data.amount_to_sell?.asset_id;
1451
- sellAmountInt = op.op_data.amount_to_sell?.amount;
1472
+ const ats = opData.amount_to_sell;
1473
+ sellAssetId = ats?.asset_id ?? null;
1474
+ sellAmountInt = ats?.amount != null ? Number(ats.amount) : null;
1452
1475
  }
1453
1476
  else if (op.op_name === 'limit_order_update') {
1454
- sellAssetId = op.op_data.new_price?.base?.asset_id;
1455
- sellAmountInt = op.op_data.new_price?.base?.amount;
1477
+ const base = opData.new_price?.base;
1478
+ sellAssetId = base?.asset_id ?? null;
1479
+ sellAmountInt = base?.amount != null ? Number(base.amount) : null;
1456
1480
  }
1457
- if (sellAssetId && (sellAmountInt !== undefined && sellAmountInt !== null)) {
1458
- const precision = (sellAssetId === assetA.id) ? assetA.precision : assetB.precision;
1459
- const assetSymbol = (sellAssetId === assetA.id) ? assetA.symbol : assetB.symbol;
1481
+ if (sellAssetId && sellAmountInt != null) {
1482
+ const precision = (sellAssetId === assetKeyA) ? assetA.precision : assetB.precision;
1483
+ const assetSymbol = (sellAssetId === assetKeyA) ? assetA.symbol : assetB.symbol;
1460
1484
  if (Number(sellAmountInt) <= 0) {
1461
1485
  return {
1462
1486
  isValid: false,
@@ -1466,8 +1490,9 @@ function validateOperationFunds(bot, operations, assetA, assetB) {
1466
1490
  }
1467
1491
  let signedDelta = 0;
1468
1492
  if (op.op_name === 'limit_order_update') {
1469
- const deltaAssetId = op.op_data.delta_amount_to_sell?.asset_id;
1470
- const deltaSellInt = op.op_data.delta_amount_to_sell?.amount;
1493
+ const deltaAmount = opData.delta_amount_to_sell;
1494
+ const deltaAssetId = deltaAmount?.asset_id;
1495
+ const deltaSellInt = deltaAmount?.amount;
1471
1496
  if (deltaAssetId === sellAssetId && Number.isFinite(Number(deltaSellInt))) {
1472
1497
  signedDelta = blockchainToFloat(deltaSellInt, precision);
1473
1498
  }
@@ -1482,18 +1507,18 @@ function validateOperationFunds(bot, operations, assetA, assetB) {
1482
1507
  }
1483
1508
  }
1484
1509
  const availableFunds = {
1485
- [assetA.id]: quantizeFloat(snap.chainFreeSell || 0, assetA.precision),
1486
- [assetB.id]: quantizeFloat(snap.chainFreeBuy || 0, assetB.precision)
1510
+ [assetKeyA]: quantizeFloat(snap.chainFreeSell || 0, assetA.precision),
1511
+ [assetKeyB]: quantizeFloat(snap.chainFreeBuy || 0, assetB.precision)
1487
1512
  };
1488
1513
  const fundViolations = [];
1489
1514
  for (const assetId in peakRequiredFunds) {
1490
1515
  const required = peakRequiredFunds[assetId];
1491
1516
  const netRequired = netRequiredFunds[assetId] || 0;
1492
1517
  const available = availableFunds[assetId] || 0;
1493
- const prec = (assetId === assetA.id) ? assetA.precision : assetB.precision;
1518
+ const prec = (assetId === assetKeyA) ? assetA.precision : assetB.precision;
1494
1519
  if (floatToBlockchainInt(required, prec) > floatToBlockchainInt(available, prec)) {
1495
1520
  fundViolations.push({
1496
- asset: assetId === assetA.id ? assetA.symbol : assetB.symbol,
1521
+ asset: assetId === assetKeyA ? assetA.symbol : assetB.symbol,
1497
1522
  required,
1498
1523
  netRequired,
1499
1524
  available,
@@ -1504,7 +1529,7 @@ function validateOperationFunds(bot, operations, assetA, assetB) {
1504
1529
  if (fundViolations.length > 0) {
1505
1530
  let summary = `[VALIDATION] Fund validation FAILED:\n`;
1506
1531
  for (const v of fundViolations) {
1507
- summary += ` ${v.asset}: peakRequired=${Format.formatAmount8(v.required)}, netRequired=${Format.formatAmount8(v.netRequired)}, available=${Format.formatAmount8(v.available)}, deficit=${Format.formatAmount8(v.deficit)}\n`;
1532
+ summary += ` ${v.asset}: peakRequired=${Format.formatAmount8(Number(v.required))}, netRequired=${Format.formatAmount8(Number(v.netRequired))}, available=${Format.formatAmount8(Number(v.available))}, deficit=${Format.formatAmount8(Number(v.deficit))}\n`;
1508
1533
  }
1509
1534
  return { isValid: false, summary: summary.trim(), violations: fundViolations };
1510
1535
  }
@@ -1519,11 +1544,12 @@ function validateOperationFunds(bot, operations, assetA, assetB) {
1519
1544
  * @returns {number|null}
1520
1545
  */
1521
1546
  function resolveIdealSizeForValidation(_bot, orderLike, fallbackSize = null) {
1547
+ const nested = orderLike?.order;
1522
1548
  const candidates = [
1523
1549
  orderLike?.idealSize,
1524
- orderLike?.order?.idealSize,
1550
+ nested?.idealSize,
1525
1551
  orderLike?.size,
1526
- orderLike?.order?.size,
1552
+ nested?.size,
1527
1553
  fallbackSize
1528
1554
  ];
1529
1555
  for (const candidate of candidates) {
@@ -1541,7 +1567,7 @@ function resolveIdealSizeForValidation(_bot, orderLike, fallbackSize = null) {
1541
1567
  * @param {string} type
1542
1568
  * @param {Object|null} [orderLike=null]
1543
1569
  * @param {number|null} [fallbackSize=null]
1544
- * @returns {any}
1570
+ * @returns {unknown}
1545
1571
  */
1546
1572
  function validateOrderSizeForExecution(bot, size, type, orderLike = null, fallbackSize = null) {
1547
1573
  return validateOrderSize(size, type, bot.manager.assets, bot.config.gridLimits?.MIN_ORDER_SIZE_FACTOR, resolveIdealSizeForValidation(bot, orderLike, fallbackSize), bot.config.gridLimits?.PARTIAL_DUST_THRESHOLD_PERCENTAGE);
@@ -1620,7 +1646,7 @@ function recordGridPriceInvariantCheck(bot, slotId, price, stats, site) {
1620
1646
  return true;
1621
1647
  }
1622
1648
  stats.violated++;
1623
- orderUtils.reportGridPriceInvariant(bot?.manager, slotId, price, site);
1649
+ orderUtils.reportGridPriceInvariant(bot?.manager, String(slotId), price, site);
1624
1650
  considerGridPriceInvariantEscalation(bot, slotId, price, inv, site);
1625
1651
  return false;
1626
1652
  }
@@ -1641,7 +1667,7 @@ function recordGridPriceInvariantCheck(bot, slotId, price, stats, site) {
1641
1667
  * Keeping it on the bot also keeps the count from outliving the resync that
1642
1668
  * repairs the slot, and lets tests start from a clean slate.
1643
1669
  *
1644
- * @param {any} bot
1670
+ * @param {unknown} bot
1645
1671
  * @returns {Map<string, number>}
1646
1672
  */
1647
1673
  function getInvariantRejectStreak(bot) {
@@ -1699,21 +1725,13 @@ function considerGridPriceInvariantEscalation(bot, slotId, price, inv, site) {
1699
1725
  `${Number.isFinite(actual) ? Format.formatPrice6(actual) : 'n/a'} ` +
1700
1726
  `(genesis ${Number.isFinite(expected) ? Format.formatPrice6(expected) : 'n/a'}); ` +
1701
1727
  `requesting structural resync to repair the slot`, 'error');
1702
- try {
1703
- const res = bot.manager.requestStructuralGridResync('grid-price-invariant-violation', {
1704
- slotId: String(slotId),
1705
- expected: Number.isFinite(expected) ? expected : null,
1706
- actual: Number.isFinite(actual) ? actual : null,
1707
- site,
1708
- streak,
1709
- });
1710
- res?.catch?.((err) => {
1711
- bot.manager?.logger?.log?.(`[GRID-PRICE-INVARIANT] Structural resync request failed: ${getErrorMessage(err)}`, 'error');
1712
- });
1713
- }
1714
- catch (err) {
1715
- bot.manager?.logger?.log?.(`[GRID-PRICE-INVARIANT] Structural resync request failed: ${getErrorMessage(err)}`, 'error');
1716
- }
1728
+ fireStructuralResync(bot, 'grid-price-invariant-violation', {
1729
+ slotId: String(slotId),
1730
+ expected: Number.isFinite(expected) ? expected : null,
1731
+ actual: Number.isFinite(actual) ? actual : null,
1732
+ site,
1733
+ streak,
1734
+ }, '[GRID-PRICE-INVARIANT] Structural resync request failed');
1717
1735
  return streak;
1718
1736
  }
1719
1737
  /**
@@ -1832,9 +1850,11 @@ function refreshLastFillPivotFromQueue(bot) {
1832
1850
  // SPREAD slots carrying on-chain orders).
1833
1851
  if ((type == null || price == null) && fillOp?.pays && fillOp?.receives && assets?.assetA && assets?.assetB) {
1834
1852
  try {
1835
- const paysId = fillOp.pays.asset_id;
1836
- const paysAmt = Number(fillOp.pays.amount);
1837
- const recvAmt = Number(fillOp.receives.amount);
1853
+ const pays = fillOp.pays;
1854
+ const receives = fillOp.receives;
1855
+ const paysId = pays.asset_id;
1856
+ const paysAmt = Number(pays.amount);
1857
+ const recvAmt = Number(receives.amount);
1838
1858
  if (Number.isFinite(paysAmt) && paysAmt > 0 && Number.isFinite(recvAmt) && recvAmt > 0) {
1839
1859
  const paysFloat = (base, precision) => base / Math.pow(10, precision);
1840
1860
  if (paysId === assets.assetA.id) {
@@ -1908,19 +1928,23 @@ function buildActionsFromPlan(_bot, plan) {
1908
1928
  const normalizedPlan = Array.isArray(plan)
1909
1929
  ? { ordersToPlace: plan }
1910
1930
  : (plan || {});
1911
- const { ordersToPlace = [], ordersToRotate = [], ordersToUpdate = [], ordersToCancel = [] } = normalizedPlan;
1931
+ const ordersToPlace = (normalizedPlan.ordersToPlace ?? []);
1932
+ const ordersToRotate = (normalizedPlan.ordersToRotate ?? []);
1933
+ const ordersToUpdate = (normalizedPlan.ordersToUpdate ?? []);
1934
+ const ordersToCancel = (normalizedPlan.ordersToCancel ?? []);
1912
1935
  // Per-action origin: guard bypasses are scoped per action (not per batch),
1913
1936
  // so a future rotation entry merged into a correction plan cannot silently
1914
1937
  // inherit the spread-correction bypass. Actions built outside this helper
1915
1938
  // carry no origin and default to guarded (safe default).
1916
- const planOrigin = normalizedPlan?.origin;
1939
+ const planOrigin = normalizedPlan.origin;
1917
1940
  // B-stamp inputs: the plan-level boundary + gap width frozen AT
1918
1941
  // PLAN-BUILD TIME. The stamp carries this geometry so the execution
1919
1942
  // guard can bypass on it — and re-verifies it against the LIVE
1920
1943
  // committed geometry at execution time (isEvacuationStampStillValid),
1921
1944
  // downgrading stale stamps to the live probe.
1922
- const frozenBoundaryRaw = Number(normalizedPlan?.boundaryIdx ?? _bot?.manager?.boundaryIdx);
1923
- const frozenGapRaw = Number(normalizedPlan?.gapSlots ?? _bot?.manager?._gapSlots);
1945
+ const mgrView = _bot?.manager;
1946
+ const frozenBoundaryRaw = Number(normalizedPlan.boundaryIdx ?? mgrView?.boundaryIdx);
1947
+ const frozenGapRaw = Number(normalizedPlan.gapSlots ?? mgrView?._gapSlots);
1924
1948
  const hasFrozenGeometry = Number.isFinite(frozenBoundaryRaw) && Number.isFinite(frozenGapRaw) && frozenGapRaw >= 0;
1925
1949
  const withOrigin = (action, sourceMaster = null) => {
1926
1950
  if (!planOrigin)
@@ -1931,9 +1955,9 @@ function buildActionsFromPlan(_bot, plan) {
1931
1955
  // per-action origin there is safe. Other plan origins keep riding
1932
1956
  // non-UPDATE actions unchanged.
1933
1957
  if (action?.type !== COW_ACTIONS.UPDATE) {
1934
- return planOrigin === 'gap-evacuation' ? { ...action } : { ...action, origin: planOrigin };
1958
+ return planOrigin === COW_ORIGINS.GAP_EVACUATION ? { ...action } : { ...action, origin: planOrigin };
1935
1959
  }
1936
- if (planOrigin !== 'gap-evacuation')
1960
+ if (planOrigin !== COW_ORIGINS.GAP_EVACUATION)
1937
1961
  return { ...action, origin: planOrigin };
1938
1962
  if (!hasFrozenGeometry)
1939
1963
  return { ...action, origin: planOrigin };
@@ -1949,7 +1973,7 @@ function buildActionsFromPlan(_bot, plan) {
1949
1973
  // The stampler wants the ORDER type (SELL/BUY), which rides on
1950
1974
  // action.order.type — action.type is the COW action kind ('update').
1951
1975
  const rotOrderType = action?.order?.type ?? action?.type;
1952
- const proved = stampGapEvacuationRotation(base, sourceMaster, action.newPrice, action.newSize, rotOrderType, frozenBoundaryRaw, frozenGapRaw, _bot?.manager?.assets);
1976
+ const proved = stampGapEvacuationRotation(base, sourceMaster, action.newPrice, action.newSize, rotOrderType, frozenBoundaryRaw, frozenGapRaw, mgrView?.assets);
1953
1977
  // Proof refused: strip the origin so the action is exactly an
1954
1978
  // unstamped rotation (never an origin claim without a stamp).
1955
1979
  if (!proved?.evacBoundary && !proved?.evacGapSlots) {
@@ -1960,21 +1984,22 @@ function buildActionsFromPlan(_bot, plan) {
1960
1984
  const actions = [];
1961
1985
  for (const o of ordersToCancel) {
1962
1986
  if (o?.orderId) {
1963
- actions.push({ type: COW_ACTIONS.CANCEL, id: o.id, orderId: o.orderId });
1987
+ actions.push({ type: COW_ACTIONS.CANCEL, id: String(o.id), orderId: o.orderId });
1964
1988
  }
1965
1989
  }
1966
1990
  for (const r of ordersToRotate) {
1967
- const oldOrder = r?.oldOrder || r;
1968
- const id = oldOrder?.id || r?.id;
1969
- const orderId = oldOrder?.orderId || r?.orderId;
1970
- const newGridId = r?.newGridId || id;
1971
- const newSize = Number.isFinite(Number(r?.newSize))
1972
- ? Number(r.newSize)
1973
- : Number(r?.size || oldOrder?.size || 0);
1974
- const newPrice = Number.isFinite(Number(r?.newPrice))
1975
- ? Number(r.newPrice)
1976
- : Number(r?.price || oldOrder?.price);
1977
- const orderType = r?.type || oldOrder?.type;
1991
+ const rv = r;
1992
+ const oldOrder = (rv.oldOrder ?? rv);
1993
+ const id = String(oldOrder.id ?? rv.id ?? '');
1994
+ const orderId = (oldOrder.orderId ?? rv.orderId);
1995
+ const newGridId = String(rv.newGridId ?? id);
1996
+ const newSize = Number.isFinite(Number(rv.newSize))
1997
+ ? Number(rv.newSize)
1998
+ : Number(rv.size || oldOrder.size || 0);
1999
+ const newPrice = Number.isFinite(Number(rv.newPrice))
2000
+ ? Number(rv.newPrice)
2001
+ : Number(rv.price || oldOrder.price);
2002
+ const orderType = (rv.type || oldOrder.type);
1978
2003
  if (!id || !orderId || !newGridId || !orderType || !Number.isFinite(newPrice) || !(newSize > 0))
1979
2004
  continue;
1980
2005
  actions.push(withOrigin({
@@ -1993,13 +2018,14 @@ function buildActionsFromPlan(_bot, plan) {
1993
2018
  }, oldOrder));
1994
2019
  }
1995
2020
  for (const o of ordersToUpdate) {
1996
- const partialOrder = o?.partialOrder || o;
1997
- const id = o?.id || partialOrder?.id;
1998
- const orderId = o?.orderId || partialOrder?.orderId;
1999
- const orderType = o?.type || partialOrder?.type;
2000
- const newSize = Number.isFinite(Number(o?.newSize))
2001
- ? Number(o.newSize)
2002
- : Number(partialOrder?.size || 0);
2021
+ const ov = o;
2022
+ const partialOrder = (ov.partialOrder ?? ov);
2023
+ const id = String(ov.id ?? partialOrder.id ?? '');
2024
+ const orderId = (ov.orderId ?? partialOrder.orderId);
2025
+ const orderType = (ov.type || partialOrder.type);
2026
+ const newSize = Number.isFinite(Number(ov.newSize))
2027
+ ? Number(ov.newSize)
2028
+ : Number(partialOrder.size || 0);
2003
2029
  if (!id || !orderId)
2004
2030
  continue;
2005
2031
  actions.push(withOrigin({
@@ -2019,7 +2045,7 @@ function buildActionsFromPlan(_bot, plan) {
2019
2045
  for (const o of ordersToPlace) {
2020
2046
  if (!o?.id)
2021
2047
  continue;
2022
- actions.push(withOrigin({ type: COW_ACTIONS.CREATE, id: o.id, order: o }));
2048
+ actions.push(withOrigin({ type: COW_ACTIONS.CREATE, id: String(o.id), order: o }));
2023
2049
  }
2024
2050
  return actions;
2025
2051
  }
@@ -2129,9 +2155,9 @@ function buildCowResultFromPlan(bot, plan) {
2129
2155
  return {
2130
2156
  workingGrid,
2131
2157
  workingIndexes: workingGrid.getIndexes(),
2132
- workingBoundary,
2158
+ workingBoundary: workingBoundary,
2133
2159
  actions,
2134
- origin: plan?.origin,
2160
+ origin: plan.origin,
2135
2161
  ...(refillSlotIds !== undefined ? { refillSlotIds } : {})
2136
2162
  };
2137
2163
  }
@@ -2151,23 +2177,30 @@ function applyRotationTransitionsToWorkingGrid(bot, workingGrid, executedContext
2151
2177
  for (const ctx of executedContexts) {
2152
2178
  if (ctx.kind !== 'rotation' || !ctx.rotation?.newGridId)
2153
2179
  continue;
2154
- const { rotation } = ctx;
2155
- const { oldOrder, newGridId, newPrice, newSize, type } = rotation;
2180
+ const rotation = ctx.rotation;
2181
+ const oldOrder = rotation?.oldOrder;
2182
+ const oldOrderId = oldOrder?.id != null ? String(oldOrder.id) : null;
2183
+ const newGridId = String(rotation?.newGridId ?? '');
2184
+ const newPrice = rotation?.newPrice;
2185
+ const newSize = rotation?.newSize;
2186
+ const type = rotation?.type;
2187
+ if (!newGridId)
2188
+ continue;
2156
2189
  // Source slot → VIRTUAL (if it's a different slot). Phase 2: the
2157
2190
  // source stays a RAIL-TYPED hole with its booked size preserved —
2158
2191
  // only state/orderId/rawOnChain are cleared, never type or size
2159
2192
  // (no SPREAD retype, no zeroing). In-rail sources must remain
2160
2193
  // visible to candidate-selection and evacuation geometry.
2161
- if (oldOrder?.id && oldOrder.id !== newGridId) {
2162
- const sourceSlot = workingGrid.get(oldOrder.id);
2194
+ if (oldOrderId && oldOrderId !== newGridId) {
2195
+ const sourceSlot = workingGrid.get(oldOrderId);
2163
2196
  if (sourceSlot && sourceSlot.orderId) {
2164
- workingGrid.set(oldOrder.id, {
2197
+ workingGrid.set(oldOrderId, {
2165
2198
  ...sourceSlot,
2166
2199
  state: ORDER_STATES.VIRTUAL,
2167
2200
  orderId: null,
2168
2201
  rawOnChain: null,
2169
2202
  });
2170
- bot.manager.logger.log(`[COW] Pre-applied rotation: source ${oldOrder.id} → VIRTUAL (order ${sourceSlot.orderId} moved to ${newGridId})`, 'debug');
2203
+ bot.manager.logger.log(`[COW] Pre-applied rotation: source ${oldOrderId} → VIRTUAL (order ${sourceSlot.orderId} moved to ${newGridId})`, 'debug');
2171
2204
  }
2172
2205
  }
2173
2206
  // Destination slot → ACTIVE with inherited orderId from source
@@ -2176,7 +2209,7 @@ function applyRotationTransitionsToWorkingGrid(bot, workingGrid, executedContext
2176
2209
  workingGrid.set(newGridId, {
2177
2210
  ...destSlot,
2178
2211
  id: newGridId,
2179
- type,
2212
+ type: type,
2180
2213
  size: newSize,
2181
2214
  price: newPrice,
2182
2215
  state: ORDER_STATES.ACTIVE,
@@ -2209,7 +2242,7 @@ function applyRotationTransitionsToWorkingGrid(bot, workingGrid, executedContext
2209
2242
  * @returns {{ allConfirmed: boolean, confirmed: Array, unconfirmed: Array }}
2210
2243
  */
2211
2244
  async function pollChainForConfirmation(bot, opContexts, options = {}) {
2212
- const maxPollRetries = options.maxPollRetries || 4;
2245
+ const maxPollRetries = Number(options.maxPollRetries) || 4;
2213
2246
  // Test seam (see updateOrdersOnChainBatchCOW): bot._testPollIntervalMs
2214
2247
  // overrides the production pacing when set by the tests. An explicit 0 is
2215
2248
  // honored; null/undefined falls through to the production 1.5s default.
@@ -2217,7 +2250,7 @@ async function pollChainForConfirmation(bot, opContexts, options = {}) {
2217
2250
  const seamMs = bot?._testPollIntervalMs;
2218
2251
  const pollIntervalMs = resolveSeamMs(explicitPollMs, resolveSeamMs(seamMs, 1500));
2219
2252
  // Only CREATE operations can be confirmed by polling (they appear as new orders on chain)
2220
- const createContexts = opContexts.filter((ctx) => ctx && ctx.kind === 'create' && ctx.finalInts && ctx.order);
2253
+ const createContexts = opContexts.filter((ctx) => !!ctx && ctx.kind === 'create' && !!ctx.finalInts && !!ctx.order);
2221
2254
  if (createContexts.length === 0) {
2222
2255
  return { allConfirmed: false, confirmed: [], unconfirmed: [...opContexts], confirmedChainIds: [] };
2223
2256
  }
@@ -2353,10 +2386,10 @@ function resolveRefillBoundaryHold(workingBoundary, committedBoundary, skippedUp
2353
2386
  * re-plan from unchanged master re-derives the identical plan and re-hits
2354
2387
  * the identical guard blocks, so it is suppressed rather than re-broadcast;
2355
2388
  * the heal path is a fresh fill-driven plan or the re-center.
2356
- * @param {any} manager - Order manager (mutable tracking fields)
2389
+ * @param {unknown} manager - Order manager (mutable tracking fields)
2357
2390
  * @param {boolean} held - Whether this batch held the boundary
2358
- * @param {any} keptBoundary - Committed boundary that was kept
2359
- * @param {any} plannedBoundary - Boundary the plan wanted
2391
+ * @param {unknown} keptBoundary - Committed boundary that was kept
2392
+ * @param {unknown} plannedBoundary - Boundary the plan wanted
2360
2393
  * @param {string[]} heldSlotIds - Refill slots skipped this batch
2361
2394
  * @returns {number} Consecutive-hold count after this batch (0 when clear)
2362
2395
  */
@@ -2391,7 +2424,7 @@ function trackBoundaryHold(manager, held, keptBoundary, plannedBoundary, heldSlo
2391
2424
  /**
2392
2425
  * Restore skipped update slots in the working grid to master state.
2393
2426
  * @param {import('./dexbot_class.js').DEXBot} bot
2394
- * @param {any} workingGrid
2427
+ * @param {unknown} workingGrid
2395
2428
  * @param {Set<string>} skippedSlotIds
2396
2429
  * @param {number} [skippedCount=0]
2397
2430
  */
@@ -2687,7 +2720,7 @@ async function runPreBroadcastGuards(bot, cowResult) {
2687
2720
  if (action.type !== COW_ACTIONS.CREATE)
2688
2721
  return true;
2689
2722
  const targetId = action.id || action.order?.id;
2690
- return !violatingIds.has(targetId);
2723
+ return !violatingIds.has(String(targetId));
2691
2724
  });
2692
2725
  actions.length = 0;
2693
2726
  actions.push(...filteredActions);
@@ -2740,13 +2773,13 @@ async function runPreBroadcastGuards(bot, cowResult) {
2740
2773
  await reconcileAfterUncertainBroadcast(bot, new BroadcastUncertainError('rejected CREATE batch had pending broadcasts', {
2741
2774
  operations: pendingBroadcasts.map((p) => p.order),
2742
2775
  accountName: bot.account,
2743
- batchId: bot._currentBatchId || null,
2776
+ batchId: bot._currentBatchId != null ? String(bot._currentBatchId) : null,
2744
2777
  payload: null,
2745
2778
  timeoutMs: null
2746
2779
  }), []);
2747
2780
  }
2748
2781
  catch (recoverErr) {
2749
- bot.manager.logger.log(`[COW] Recovery from pending broadcasts failed: ${recoverErr?.message || recoverErr}`, 'error');
2782
+ bot.manager.logger.log(`[COW] Recovery from pending broadcasts failed: ${getErrorMessage(recoverErr)}`, 'error');
2750
2783
  }
2751
2784
  popPushedWorkingGrid(bot, cowResult);
2752
2785
  return {
@@ -2812,7 +2845,7 @@ async function runPreBroadcastGuards(bot, cowResult) {
2812
2845
  }
2813
2846
  }
2814
2847
  catch (syncErr) {
2815
- bot.manager.logger.log(`[COW] Failed to sync/unmatched orders: ${syncErr?.message || syncErr}`, 'warn');
2848
+ bot.manager.logger.log(`[COW] Failed to sync/unmatched orders: ${getErrorMessage(syncErr)}`, 'warn');
2816
2849
  }
2817
2850
  await requestStructuralResync(bot, 'unmatched chain orders before COW create', { unmatchedChainOrders: unmatchedChainOrders });
2818
2851
  bot.manager.logger.log(`[COW] Rejecting CREATE batch after sync: working grid invalidated by master mutation`, 'info');
@@ -2964,10 +2997,10 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
2964
2997
  const drainResult = await orderUtils.correctAllPriceMismatches(bot.manager, bot.account, bot.privateKey, chainOrders);
2965
2998
  if (drainResult?.failed > 0) {
2966
2999
  bot.manager.logger.log(`[COW] ${drainResult.failed} correction(s) failed pre-batch` +
2967
- (drainResult.staleDropped > 0 ? `, ${drainResult.staleDropped} stale dropped` : '') +
3000
+ ((drainResult.staleDropped ?? 0) > 0 ? `, ${drainResult.staleDropped} stale dropped` : '') +
2968
3001
  `; remaining entries retry on next sync/maintenance tick`, 'warn');
2969
3002
  }
2970
- else if (drainResult?.staleDropped > 0) {
3003
+ else if ((drainResult?.staleDropped ?? 0) > 0) {
2971
3004
  bot.manager.logger.log(`[COW] Pre-batch drain resolved, ${drainResult.staleDropped} stale correction(s) dropped`, 'info');
2972
3005
  }
2973
3006
  }
@@ -2980,8 +3013,8 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
2980
3013
  // runPreBroadcastGuards. Refusals already popped the working grid.
2981
3014
  const guards = await runPreBroadcastGuards(bot, cowResult);
2982
3015
  if (!guards.proceed)
2983
- return guards.result;
2984
- const { crossingCandidates, intraBatchCandidates } = guards;
3016
+ return guards.result ?? { executed: false, hadRotation: false };
3017
+ const { crossingCandidates = [], intraBatchCandidates = [] } = guards;
2985
3018
  const { assetA, assetB } = bot.manager.assets;
2986
3019
  const operations = [];
2987
3020
  const opContexts = [];
@@ -3089,7 +3122,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3089
3122
  if (action.orderId)
3090
3123
  cancelOpIndexByOrderId.set(action.orderId, operations.length - 1);
3091
3124
  const order = bot.manager.orders.get(action.id) || { id: action.id, orderId: action.orderId };
3092
- opContexts.push({ kind: 'cancel', order });
3125
+ opContexts.push({ kind: 'cancel', order: order });
3093
3126
  }
3094
3127
  catch (err) {
3095
3128
  const orderNotFound = /\bnot found\b/i.test(getErrorMessage(err)) || /\bdoes not exist\b/i.test(getErrorMessage(err));
@@ -3139,7 +3172,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3139
3172
  if (batchCollision) {
3140
3173
  bot.manager.logger.log(`[COW] Skipping CREATE for ${order.id} at ${Format.formatPrice6(createPrice)}: ` +
3141
3174
  `same-batch CREATE ${batchCollision.id} already at ` +
3142
- `price ${Format.formatPrice6(batchCollision.order.price)}. ` +
3175
+ `price ${Format.formatPrice6(Number(batchCollision.order?.price ?? batchCollision.price))}. ` +
3143
3176
  `The next reconcile cycle will resolve the mismatch.`, 'warn');
3144
3177
  if (order.id)
3145
3178
  skippedCreateSlotIds.add(order.id);
@@ -3173,8 +3206,8 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3173
3206
  try {
3174
3207
  const actionOrigin = action?.origin;
3175
3208
  const batchOrigin = cowResult?.origin;
3176
- const isCorrectionCreate = actionOrigin === 'spread-correction'
3177
- || (actionOrigin == null && batchOrigin === 'spread-correction');
3209
+ const isCorrectionCreate = actionOrigin === COW_ORIGINS.SPREAD_CORRECTION
3210
+ || (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION);
3178
3211
  if (!isCorrectionCreate) {
3179
3212
  const { check, refreshed } = runLastFillGuardCheck(bot, createPrice, order.size, order.type, lastFillGuardStats, true);
3180
3213
  if (refreshed)
@@ -3182,7 +3215,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3182
3215
  if (check.blocked) {
3183
3216
  lastFillGuardStats.skipped++;
3184
3217
  const dir = order.type === ORDER_TYPES.BUY ? 'above' : 'below';
3185
- bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping ${order.type} CREATE for ${order.id} at ${Format.formatPrice6(createPrice)}: ${dir} last filled ${Format.formatPrice6(check.pivot)} (halfInc ${check.halfInc}% thr ${Format.formatPrice6(check.threshold)}); re-planned after market moves`, 'debug');
3218
+ bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping ${order.type} CREATE for ${order.id} at ${Format.formatPrice6(createPrice)}: ${dir} last filled ${Format.formatPrice6(Number(check.pivot))} (halfInc ${check.halfInc}% thr ${Format.formatPrice6(Number(check.threshold))}); re-planned after market moves`, 'debug');
3186
3219
  if (order.id)
3187
3220
  skippedCreateSlotIds.add(order.id);
3188
3221
  continue;
@@ -3345,7 +3378,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3345
3378
  try {
3346
3379
  let bypassedEvacuation = false;
3347
3380
  const rotationOrigin = action?.origin;
3348
- if (rotationOrigin === 'gap-evacuation') {
3381
+ if (rotationOrigin === COW_ORIGINS.GAP_EVACUATION) {
3349
3382
  const frozenB = Number(action?.evacBoundary);
3350
3383
  const frozenG = Number(action?.evacGapSlots);
3351
3384
  let stampUsable = Number.isFinite(frozenB) && Number.isFinite(frozenG);
@@ -3454,7 +3487,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3454
3487
  if (action.newGridId)
3455
3488
  skippedUpdateSlotIds.add(action.newGridId);
3456
3489
  const dir = orderType === ORDER_TYPES.BUY ? 'above' : 'below';
3457
- bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping ${orderType} UPDATE for ${action.id} -> ${action.newGridId} at ${Format.formatPrice6(newPrice)}: ${dir} last filled ${Format.formatPrice6(check.pivot)} (halfInc ${check.halfInc}% thr ${Format.formatPrice6(check.threshold)})`, 'debug');
3490
+ bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping ${orderType} UPDATE for ${action.id} -> ${action.newGridId} at ${Format.formatPrice6(newPrice)}: ${dir} last filled ${Format.formatPrice6(Number(check.pivot))} (halfInc ${check.halfInc}% thr ${Format.formatPrice6(Number(check.threshold))})`, 'debug');
3458
3491
  continue;
3459
3492
  }
3460
3493
  lastFillGuardStats.passed++;
@@ -3562,14 +3595,14 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3562
3595
  if (fbCollision) {
3563
3596
  bot.manager.logger.log(`[COW] Skipping CREATE fallback for ${targetSlotId} at ${Format.formatPrice6(fbPrice)}: ` +
3564
3597
  `existing placed order ${fbCollision.id} (${fbCollision.orderId}) ` +
3565
- `already at price ${Format.formatPrice6(fbCollision.price)}.`, 'warn');
3598
+ `already at price ${Format.formatPrice6(Number(fbCollision.price))}.`, 'warn');
3566
3599
  continue;
3567
3600
  }
3568
3601
  const fbBatchCollision = hasSlotPriceCollision(opContexts, fbPrice, fbPrecision, targetSlotId, (ctx) => ctx.kind === 'create');
3569
3602
  if (fbBatchCollision) {
3570
3603
  bot.manager.logger.log(`[COW] Skipping CREATE fallback for ${targetSlotId} at ${Format.formatPrice6(fbPrice)}: ` +
3571
3604
  `same-batch CREATE ${fbBatchCollision.id} already at ` +
3572
- `price ${Format.formatPrice6(fbBatchCollision.order.price)}.`, 'warn');
3605
+ `price ${Format.formatPrice6(Number(fbBatchCollision.order?.price ?? fbBatchCollision.price))}.`, 'warn');
3573
3606
  continue;
3574
3607
  }
3575
3608
  // CROSSING-PLACEMENT GUARD (fallback variant):
@@ -3599,8 +3632,8 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3599
3632
  const fbDir = fbType === ORDER_TYPES.BUY ? 'above' : 'below';
3600
3633
  bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping CREATE fallback for ${targetSlotId} at ` +
3601
3634
  `${Format.formatPrice6(fbPrice)}: ${fbDir} last filled ` +
3602
- `${Format.formatPrice6(fbCheck.pivot)} (halfInc ${fbCheck.halfInc}% thr ` +
3603
- `${Format.formatPrice6(fbCheck.threshold)}); re-planned after market moves`, 'debug');
3635
+ `${Format.formatPrice6(Number(fbCheck.pivot))} (halfInc ${fbCheck.halfInc}% thr ` +
3636
+ `${Format.formatPrice6(Number(fbCheck.threshold))}); re-planned after market moves`, 'debug');
3604
3637
  continue;
3605
3638
  }
3606
3639
  lastFillGuardStats.passed++;
@@ -3701,7 +3734,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3701
3734
  ? cctx?.order?.orderId || cctx?.orderId
3702
3735
  : cord?.orderId;
3703
3736
  if (cOrderId)
3704
- cancelOpIndexByOrderId.set(cOrderId, ci);
3737
+ cancelOpIndexByOrderId.set(String(cOrderId), ci);
3705
3738
  }
3706
3739
  // skippedUpdateCount is threaded via countRef so the restore
3707
3740
  // below covers gate-dropped rotations too.
@@ -3785,7 +3818,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3785
3818
  ? Number(bot.manager._gridVersion)
3786
3819
  : undefined;
3787
3820
  for (const slotId of clampedUpdateSlotIds) {
3788
- workingGrid.syncFromMaster(bot.manager.orders, slotId, masterVersion);
3821
+ workingGrid.syncFromMaster(bot.manager.orders, String(slotId), masterVersion);
3789
3822
  }
3790
3823
  bot.manager.logger.log(`[COW] Re-synced ${clampedUpdateSlotIds.size} post-fill-clamped slot(s) from master before commit`, 'debug');
3791
3824
  }
@@ -3862,7 +3895,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3862
3895
  // Bounded re-plan + proceed — policy documented on replanStaleBatch.
3863
3896
  const replan = await replanStaleBatch(bot, cowResult, replanDepth, preBroadcastGuard, seamPollIntervalMs);
3864
3897
  if (replan.handled) {
3865
- return replan.result;
3898
+ return replan.result ?? { executed: false, hadRotation: false };
3866
3899
  }
3867
3900
  // Fall through: proceed with the current plan (bounded policy).
3868
3901
  }
@@ -3908,7 +3941,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3908
3941
  heldBroadcastSlot = false;
3909
3942
  const replan = await replanStaleBatch(bot, cowResult, replanDepth, postWaitGuard, seamPollIntervalMs);
3910
3943
  if (replan.handled) {
3911
- return replan.result;
3944
+ return replan.result ?? { executed: false, hadRotation: false };
3912
3945
  }
3913
3946
  // No fill context for a re-plan (or the re-plan limit was
3914
3947
  // reached). The stale policy proceeds with the original plan, so
@@ -3958,17 +3991,17 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3958
3991
  let adoptedCount = 0;
3959
3992
  let normalizedCount = 0;
3960
3993
  for (const item of missingCreateResults) {
3961
- const slotId = item.ctx?.order?.id || item.ctx?.id;
3994
+ const slotId = String(item.ctx?.order?.id ?? item.ctx?.id ?? '');
3962
3995
  const slot = workingGrid.get(slotId);
3963
3996
  if (!slot)
3964
3997
  continue;
3965
3998
  const isConfirmed = confirmation.confirmed.some((c) => (c?.order?.id || c?.id) === slotId);
3966
3999
  if (isConfirmed && chainSnap) {
3967
- const match = findChainOrderForSlot(bot, chainSnap, slotId, {
4000
+ const match = findChainOrderForSlot(bot, chainSnap, String(slotId), {
3968
4001
  sell: item.ctx?.finalInts?.sell,
3969
4002
  receive: item.ctx?.finalInts?.receive,
3970
4003
  orderType: item.ctx?.order?.type,
3971
- fingerprint: createOpFingerprintForSlot(bot, item.ctx?.order, item.ctx?.finalInts, slotId)
4004
+ fingerprint: createOpFingerprintForSlot(bot, item.ctx?.order, item.ctx?.finalInts, String(slotId))
3972
4005
  });
3973
4006
  if (match?.id) {
3974
4007
  workingGrid.set(slotId, { ...slot, orderId: match.id });
@@ -4024,6 +4057,15 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4024
4057
  });
4025
4058
  }
4026
4059
  const batchResult = await processBatchResults(bot, result, executedContexts);
4060
+ // A `suspended` persist result is a deliberate, temporary gate
4061
+ // (credential-daemon outage), NOT a corrupt/ahead state: the
4062
+ // in-memory master stays authoritative and the dirty-flush
4063
+ // pipeline persists it once suspension lifts. Treat it as a
4064
+ // deferral — never as a structural-resync trigger.
4065
+ const isSuspendedPersist = (r) => {
4066
+ const v = r;
4067
+ return Boolean(v && v.skipped && v.suspended === true);
4068
+ };
4027
4069
  const persistResult = await bot.manager.persistGrid();
4028
4070
  if (persistResult && (persistResult.skipped || persistResult.isValid === false)) {
4029
4071
  bot.manager.logger.log(`[COW][PERSIST-GUARD] First persist attempt was ` +
@@ -4032,7 +4074,21 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4032
4074
  `clearing working grid reference.`, 'warn');
4033
4075
  bot.manager._persistenceWarning = persistResult;
4034
4076
  const retryResult = await bot.manager.persistGrid();
4035
- if (retryResult && (retryResult.skipped || retryResult.isValid === false)) {
4077
+ if (isSuspendedPersist(retryResult)) {
4078
+ bot.manager.logger.log(`[COW][PERSIST-GUARD] Grid persistence is suspended ` +
4079
+ `(${retryResult.reason || 'no reason'}); deferring disk flush until it resumes.`, 'warn');
4080
+ // The committed grid is not on disk yet. Mark it dirty so
4081
+ // the end-of-tick flushGridDirty safety net retries it at
4082
+ // the next end-of-tick flush after the suspension lifts,
4083
+ // instead of relying on the next COW/recovery persist to
4084
+ // converge disk.
4085
+ try {
4086
+ bot.manager._markGridDirty?.();
4087
+ }
4088
+ catch { /* best-effort */ }
4089
+ delete bot.manager._persistenceWarning;
4090
+ }
4091
+ else if (retryResult && (retryResult.skipped || retryResult.isValid === false)) {
4036
4092
  bot.manager.logger.log(`[COW][PERSIST-GUARD] Retry also skipped/invalid ` +
4037
4093
  `(${retryResult.reason || 'no reason'}). Master grid in memory ` +
4038
4094
  `is ahead of disk snapshot; structural resync requested.`, 'error');
@@ -4067,7 +4123,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4067
4123
  }
4068
4124
  catch (err) {
4069
4125
  bot.manager.logger.log(`[COW] Batch transaction failed: ${getErrorMessage(err)}`, 'error');
4070
- if (err?.partialOnChainState) {
4126
+ if (getErrorField(err, 'partialOnChainState')) {
4071
4127
  bot.manager.logger.log(`[COW] Non-atomic grouped execution detected (${formatPartialBroadcastSummary(err)}). Local rollback cannot undo confirmed on-chain operations; next sync/reconcile will converge state.`, 'warn');
4072
4128
  }
4073
4129
  bot.manager.stopBroadcasting();
@@ -4077,7 +4133,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4077
4133
  // and we can commit the working grid directly, bypassing the expensive
4078
4134
  // reconciliation state machine. This handles the ~90% case where the
4079
4135
  // chain accepted the transaction but the response was lost.
4080
- if (err instanceof BroadcastUncertainError && err.partialOnChainState !== true) {
4136
+ if (err instanceof BroadcastUncertainError && getErrorField(err, 'partialOnChainState') !== true) {
4081
4137
  try {
4082
4138
  const confirmation = await pollChainForConfirmation(bot, opContexts);
4083
4139
  if (confirmation.allConfirmed) {
@@ -4225,12 +4281,12 @@ async function requestStructuralResync(bot, reason, details = {}) {
4225
4281
  * freshest orders are dropped — so it MUST NOT drive adoption; we return false
4226
4282
  * and let the caller keep pending-broadcast protection + structural resync.
4227
4283
  *
4228
- * @param {any} bot
4229
- * @param {any} chainOrders - chain_orders module (has readOpenOrdersWithMetaSafe + batchReadOrders)
4284
+ * @param {unknown} bot
4285
+ * @param {unknown} chainOrders - chain_orders module (has readOpenOrdersWithMetaSafe + batchReadOrders)
4230
4286
  * @param {string} logPrefix
4231
4287
  * @param {Object} [opts]
4232
- * @param {any} [opts.placedResults] - broadcast result carrying operation_results
4233
- * @param {any[]} [opts.placedContexts] - opContexts aligned with operation_results
4288
+ * @param {unknown} [opts.placedResults] - broadcast result carrying operation_results
4289
+ * @param {unknown[]} [opts.placedContexts] - opContexts aligned with operation_results
4234
4290
  * @param {string[]} [opts.polledCreateIds] - fresh CREATE chain ids confirmed by
4235
4291
  * the uncertain-broadcast poll (no broadcast result exists on that path);
4236
4292
  * routes the poll call sites through the by-id path with its lagging-create
@@ -4247,7 +4303,7 @@ async function requestStructuralResync(bot, reason, details = {}) {
4247
4303
  * post-fill rotation immediately (no re-broadcast), so the next placement lands
4248
4304
  * at the shifted slot, never at x.
4249
4305
  *
4250
- * @param {any} bot
4306
+ * @param {unknown} bot
4251
4307
  * @param {number} workingBoundary - boundary index the refused batch targeted
4252
4308
  */
4253
4309
  async function restoreBoundaryAfterAdoption(bot, workingBoundary) {
@@ -4419,7 +4475,11 @@ async function persistGridAndClearPendingBroadcasts(bot, logPrefix) {
4419
4475
  * @returns {Promise<Object>} The commit-refused return object
4420
4476
  */
4421
4477
  async function recoverRefusedCommit(bot, chainOrders, logPrefix, adoptOpts, contexts, workingBoundary, opts = {}) {
4422
- const { extraReturn = {}, successReturn = null, failureResyncReason = 'commit refused after broadcast (chain adoption unavailable)', failureLogMessage = 'Commit refused and chain adoption unavailable; keeping pending-broadcast protection pending structural resync', preAdoptLogMessage = null, } = opts;
4478
+ const extraReturn = (opts.extraReturn ?? {});
4479
+ const successReturn = opts.successReturn;
4480
+ const failureResyncReason = (opts.failureResyncReason ?? 'commit refused after broadcast (chain adoption unavailable)');
4481
+ const failureLogMessage = (opts.failureLogMessage ?? 'Commit refused and chain adoption unavailable; keeping pending-broadcast protection pending structural resync');
4482
+ const preAdoptLogMessage = opts.preAdoptLogMessage;
4423
4483
  if (preAdoptLogMessage) {
4424
4484
  bot.manager.logger.log(`${logPrefix} ${preAdoptLogMessage}`, 'warn');
4425
4485
  }
@@ -4449,7 +4509,7 @@ async function recoverRefusedCommit(bot, chainOrders, logPrefix, adoptOpts, cont
4449
4509
  * startup), so the guard degrades to its previous behaviour rather than
4450
4510
  * silently disabling. Never throws.
4451
4511
  *
4452
- * @param {any} manager
4512
+ * @param {unknown} manager
4453
4513
  * @param {number|null|undefined} rawPrice
4454
4514
  * @returns {{price: number|null, snapped: boolean, idx: number|null, nearestDrift: number|null}}
4455
4515
  */
@@ -4460,7 +4520,7 @@ function resolveOnGridPivot(manager, rawPrice) {
4460
4520
  try {
4461
4521
  const genesis = manager?._genesis;
4462
4522
  const levels = genesis?.priceLevels;
4463
- if (!Array.isArray(levels) || levels.length === 0)
4523
+ if (!genesis || !Array.isArray(levels) || levels.length === 0)
4464
4524
  return { price, snapped: false, idx: null, nearestDrift: null };
4465
4525
  const idx = math.slotIndexForPrice(price, genesis);
4466
4526
  if (!Number.isFinite(idx))
@@ -4640,9 +4700,9 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4640
4700
  try {
4641
4701
  if (!Array.isArray(operations) || !Array.isArray(opContexts) || operations.length === 0)
4642
4702
  return empty;
4643
- const stats = opts?.lastFillGuardStats;
4703
+ const stats = opts.lastFillGuardStats;
4644
4704
  const frozenPivot = Number(opts?.frozenPivot);
4645
- const frozenType = opts?.frozenType;
4705
+ const frozenType = opts.frozenType;
4646
4706
  const frozenCold = !Number.isFinite(frozenPivot) || frozenType == null;
4647
4707
  const queueDepthBefore = Array.isArray(bot?._incomingFillQueue)
4648
4708
  ? bot._incomingFillQueue.length
@@ -4684,8 +4744,8 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4684
4744
  return { ...empty, refreshed };
4685
4745
  // Pivot moved (or armed mid-batch): re-check every built op's FINAL
4686
4746
  // price. Same bypass rules as the build loop; unjudgeable => KEEP.
4687
- const actions = Array.isArray(opts?.actions) ? opts.actions : [];
4688
- const batchOrigin = opts?.cowResult?.origin;
4747
+ const actions = (Array.isArray(opts.actions) ? opts.actions : []);
4748
+ const batchOrigin = opts.cowResult?.origin;
4689
4749
  const actionBySlot = new Map();
4690
4750
  for (const a of actions) {
4691
4751
  if (!a)
@@ -4719,15 +4779,15 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4719
4779
  // Spread-correction CREATE bypass (mirrors the build loop:
4720
4780
  // per-action origin, batch origin as back-compat fallback).
4721
4781
  const actionOrigin = action?.origin;
4722
- if (actionOrigin === 'spread-correction'
4723
- || (actionOrigin == null && batchOrigin === 'spread-correction')) {
4782
+ if (actionOrigin === COW_ORIGINS.SPREAD_CORRECTION
4783
+ || (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION)) {
4724
4784
  if (stats)
4725
4785
  stats.bypassed = (Number(stats.bypassed) || 0) + 1;
4726
4786
  continue;
4727
4787
  }
4728
4788
  }
4729
4789
  else if (ctx.kind === 'rotation') {
4730
- const rot = ctx.rotation || {};
4790
+ const rot = (ctx.rotation || {});
4731
4791
  slotId = rot.newGridId || rot.oldOrder?.id || null;
4732
4792
  price = Number(rot.newPrice);
4733
4793
  type = rot.type || null;
@@ -4772,7 +4832,7 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4772
4832
  // The gate must not invent a block it cannot prove —
4773
4833
  // especially not on an op the build loop already allowed.
4774
4834
  const rotOrigin = action?.origin;
4775
- if (rotOrigin === 'gap-evacuation'
4835
+ if (rotOrigin === COW_ORIGINS.GAP_EVACUATION
4776
4836
  && Number.isFinite(Number(action?.evacBoundary))
4777
4837
  && Number.isFinite(Number(action?.evacGapSlots))) {
4778
4838
  if (stats)
@@ -4805,8 +4865,8 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4805
4865
  dropped.push({ index: i, kind: ctx.kind, slotId, price, type });
4806
4866
  try {
4807
4867
  bot.manager?.logger?.log?.(`[LAST-FILL-GUARD] Final gate dropping ${type} ${ctx.kind} for ${slotId ?? 'unknown'} at ` +
4808
- `${Format.formatPrice6(price)}: ${dir} last filled ${Format.formatPrice6(check.pivot)} ` +
4809
- `(halfInc ${check.halfInc}% thr ${Format.formatPrice6(check.threshold)}); re-planned after market moves`, 'warn');
4868
+ `${Format.formatPrice6(price)}: ${dir} last filled ${check.pivot != null ? Format.formatPrice6(Number(check.pivot)) : 'n/a'} ` +
4869
+ `(halfInc ${check.halfInc}% thr ${check.threshold != null ? Format.formatPrice6(Number(check.threshold)) : 'n/a'}); re-planned after market moves`, 'warn');
4810
4870
  }
4811
4871
  catch { /* logging is best-effort */ }
4812
4872
  }
@@ -4845,25 +4905,25 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4845
4905
  // drop: undefined at best, a DIFFERENT create's context at worst,
4846
4906
  // which would let the uncertain-broadcast reconcile adopt a matched
4847
4907
  // chain order into the wrong slot).
4848
- const skippedUpdateSlotIds = opts?.skippedUpdateSlotIds;
4849
- const skippedCreateSlotIds = opts?.skippedCreateSlotIds;
4850
- const countRef = opts?.skippedUpdateCountRef;
4908
+ const skippedUpdateSlotIds = opts.skippedUpdateSlotIds;
4909
+ const skippedCreateSlotIds = opts.skippedCreateSlotIds;
4910
+ const countRef = opts.skippedUpdateCountRef;
4851
4911
  try {
4852
4912
  const pending = bot.manager?._pendingBroadcasts;
4853
4913
  for (const d of dropped) {
4854
4914
  if (d.kind === 'rotation') {
4855
- const act = (d.slotId && actionBySlot.get(d.slotId)) || null;
4915
+ const act = d.slotId ? (actionBySlot.get(String(d.slotId)) ?? null) : null;
4856
4916
  const srcId = act?.id || null;
4857
4917
  if (srcId && skippedUpdateSlotIds instanceof Set)
4858
4918
  skippedUpdateSlotIds.add(srcId);
4859
4919
  if (d.slotId && skippedUpdateSlotIds instanceof Set)
4860
- skippedUpdateSlotIds.add(d.slotId);
4920
+ skippedUpdateSlotIds.add(String(d.slotId));
4861
4921
  if (countRef && typeof countRef === 'object')
4862
4922
  countRef.count = (Number(countRef.count) || 0) + 1;
4863
4923
  }
4864
4924
  else if (d.kind === 'create') {
4865
4925
  if (d.slotId && skippedCreateSlotIds instanceof Set)
4866
- skippedCreateSlotIds.add(d.slotId);
4926
+ skippedCreateSlotIds.add(String(d.slotId));
4867
4927
  if (pending instanceof Map) {
4868
4928
  for (const [fp, entry] of pending) {
4869
4929
  // Match by slot only: the fingerprint embeds
@@ -4937,21 +4997,24 @@ async function applyAdoptionFeeAccounting(bot, contexts) {
4937
4997
  : null;
4938
4998
  for (const ctx of contexts) {
4939
4999
  if (ctx?.kind === 'create') {
4940
- const slot = ctx.order?.id ? bot.manager.orders.get(ctx.order.id) : null;
5000
+ const order = ctx.order;
5001
+ if (!order)
5002
+ continue;
5003
+ const slot = order.id ? bot.manager.orders.get(order.id) : null;
4941
5004
  if (!slot?.orderId)
4942
5005
  continue;
4943
5006
  try {
4944
5007
  await bot.manager.synchronizeWithChain({
4945
- gridOrderId: ctx.order.id,
5008
+ gridOrderId: order.id,
4946
5009
  chainOrderId: slot.orderId,
4947
5010
  isPartialPlacement: false,
4948
- expectedType: ctx.order.type,
5011
+ expectedType: order.type,
4949
5012
  fee: btsFeeData?.createFee || 0,
4950
- order: ctx.order ?? null,
5013
+ order: order,
4951
5014
  }, 'createOrder');
4952
5015
  }
4953
5016
  catch (feeErr) {
4954
- bot.manager.logger.log(`[COW] Adoption fee accounting failed for create slot ${ctx.order.id}: ${getErrorMessage(feeErr)}`, 'warn');
5017
+ bot.manager.logger.log(`[COW] Adoption fee accounting failed for create slot ${order.id}: ${getErrorMessage(feeErr)}`, 'warn');
4955
5018
  }
4956
5019
  }
4957
5020
  else if (ctx?.kind === 'cancel') {
@@ -4962,9 +5025,9 @@ async function applyAdoptionFeeAccounting(bot, contexts) {
4962
5025
  // the on-chain cost exactly once (mirrors the sync's
4963
5026
  // 'cancel-order-unmatched-fee' pattern; the deferred-fee refund is
4964
5027
  // reconciled by the next sync's fill/cancel processing).
4965
- if (btsSide && btsFeeData?.cancelFee > 0) {
5028
+ if (btsSide && btsFeeData && (btsFeeData.cancelFee ?? 0) > 0) {
4966
5029
  try {
4967
- await bot.manager.accountant.adjustTotalBalance(btsSide, -btsFeeData.cancelFee, 'cancel-adopt-fee');
5030
+ await bot.manager.accountant.adjustTotalBalance(btsSide, -(btsFeeData.cancelFee ?? 0), 'cancel-adopt-fee');
4968
5031
  }
4969
5032
  catch (feeErr) {
4970
5033
  bot.manager.logger.log(`[COW] Adoption fee accounting failed for cancel ${ctx.order?.orderId}: ${getErrorMessage(feeErr)}`, 'warn');
@@ -4976,9 +5039,9 @@ async function applyAdoptionFeeAccounting(bot, contexts) {
4976
5039
  // charged on this path; the next sync's size reconciliation applies
4977
5040
  // the chain state without an update fee (fee 0), so charge it once
4978
5041
  // here to prevent optimistic BTS drift.
4979
- if (btsSide && btsFeeData?.updateFee > 0) {
5042
+ if (btsSide && btsFeeData && (btsFeeData.updateFee ?? 0) > 0) {
4980
5043
  try {
4981
- await bot.manager.accountant.adjustTotalBalance(btsSide, -btsFeeData.updateFee, 'update-adopt-fee');
5044
+ await bot.manager.accountant.adjustTotalBalance(btsSide, -(btsFeeData.updateFee ?? 0), 'update-adopt-fee');
4982
5045
  }
4983
5046
  catch (feeErr) {
4984
5047
  bot.manager.logger.log(`[COW] Adoption fee accounting failed for update ${ctx.kind === 'size-update' ? ctx.updateInfo?.partialOrder?.orderId : ctx.rotation?.oldOrder?.orderId}: ${getErrorMessage(feeErr)}`, 'warn');
@@ -5026,35 +5089,37 @@ async function processBatchResults(bot, result, opContexts) {
5026
5089
  for (let i = 0; i < opContexts.length; i++) {
5027
5090
  const ctx = opContexts[i];
5028
5091
  const res = results[i];
5092
+ const ctxOrder = ctx.order;
5093
+ const ctxUpdateInfo = ctx.updateInfo;
5029
5094
  if (ctx.kind === 'cancel') {
5030
- bot.manager.logger.log(`Cancelled surplus order ${ctx.order.id} (${ctx.order.orderId})`, 'info');
5031
- const oldOrder = ctx.order;
5095
+ bot.manager.logger.log(`Cancelled surplus order ${ctxOrder.id} (${ctxOrder.orderId})`, 'info');
5096
+ const oldOrder = ctxOrder;
5032
5097
  const committedOrder = oldOrder?.id ? bot.manager.orders.get(oldOrder.id) : null;
5033
5098
  await applyOptimisticFeeBalance(bot, oldOrder, committedOrder, 'fill-cancel', btsFeeData?.cancelFee || 0);
5034
5099
  }
5035
5100
  else if (ctx.kind === 'size-update') {
5036
- const oldOrder = ctx.updateInfo.partialOrder;
5037
- const ord = bot.manager.orders.get(oldOrder.id);
5101
+ const oldOrder = ctxUpdateInfo.partialOrder;
5102
+ const ord = bot.manager.orders.get(String(oldOrder.id));
5038
5103
  await applyOptimisticFeeBalance(bot, oldOrder, ord, 'order-update', btsFeeData?.updateFee || 0);
5039
5104
  if (ord) {
5040
- const updatedSlot = { ...ord, size: ctx.updateInfo.newSize };
5105
+ const updatedSlot = { ...ord, size: Number(ctxUpdateInfo.newSize) };
5041
5106
  if (ctx.finalInts) {
5042
5107
  updatedSlot.rawOnChain = rawOnChainFromInts(ord.orderId, ctx.finalInts);
5043
5108
  }
5044
5109
  updatesToApply.push({ order: updatedSlot, context: 'post-update-metadata' });
5045
5110
  }
5046
- bot.manager.logger.log(`Size update complete: ${ctx.updateInfo.partialOrder.orderId}`, 'info');
5111
+ bot.manager.logger.log(`Size update complete: ${ctxUpdateInfo.partialOrder.orderId}`, 'info');
5047
5112
  updateOperationCount++;
5048
5113
  }
5049
5114
  else if (ctx.kind === 'create') {
5050
5115
  const chainOrderId = res && res[1];
5051
5116
  if (chainOrderId) {
5052
5117
  await bot.manager.synchronizeWithChain({
5053
- gridOrderId: ctx.order.id, chainOrderId, expectedType: ctx.order.type, fee: btsFeeData?.createFee || 0,
5054
- order: ctx.order ?? null,
5118
+ gridOrderId: ctxOrder.id, chainOrderId, expectedType: ctxOrder.type, fee: btsFeeData?.createFee || 0,
5119
+ order: ctxOrder ?? null,
5055
5120
  }, 'createOrder');
5056
5121
  if (ctx.finalInts) {
5057
- const syncedOrder = bot.manager.orders.get(ctx.order.id);
5122
+ const syncedOrder = bot.manager.orders.get(ctxOrder.id);
5058
5123
  if (syncedOrder) {
5059
5124
  updatesToApply.push({
5060
5125
  order: {
@@ -5068,27 +5133,31 @@ async function processBatchResults(bot, result, opContexts) {
5068
5133
  // Success line mirrors the failure-path fingerprint below
5069
5134
  // (type/price/size) so both are greppable by the same keys —
5070
5135
  // this is what ties a fill back to the slot that placed it.
5071
- bot.manager.logger.log(`Placed ${ctx.order.type} order ${ctx.order.id} ` +
5072
- `@${Format.formatPrice6(ctx.order.price)} x${Format.formatAmount(ctx.order.size)} ` +
5136
+ bot.manager.logger.log(`Placed ${ctxOrder.type} order ${ctxOrder.id} ` +
5137
+ `@${Format.formatPrice6(ctxOrder.price)} x${Format.formatAmount(ctxOrder.size)} ` +
5073
5138
  `-> ${chainOrderId}`, 'info');
5074
5139
  }
5075
5140
  else {
5076
5141
  const fingerprint = [
5077
- `type=${ctx.order.type || 'unknown'}`,
5078
- `price=${Format.formatPrice6(ctx.order.price)}`,
5079
- `size=${Format.formatAmount(ctx.order.size)}`
5142
+ `type=${ctxOrder.type || 'unknown'}`,
5143
+ `price=${Format.formatPrice6(ctxOrder.price)}`,
5144
+ `size=${Format.formatAmount(ctxOrder.size)}`
5080
5145
  ].join(',');
5081
- bot.manager.logger.log(`[COW] CRITICAL: Create op for slot ${ctx.order.id} (type=${ctx.order.type}) ` +
5082
- `returned no chainOrderId. Identify any orphaned on-chain order by local fingerprint ` +
5146
+ bot.manager.logger.log(`[COW] CRITICAL: Create op for slot ${ctxOrder.id} (type=${ctxOrder.type}) ` +
5147
+ `returned no chainOrderId. Identify orphaned on-chain orders by local fingerprint ` +
5083
5148
  `${fingerprint} before cancelling.`, 'error');
5084
5149
  }
5085
5150
  }
5086
5151
  else if (ctx.kind === 'rotation') {
5087
5152
  hadRotation = true;
5088
- const { rotation } = ctx;
5089
- const { oldOrder, newPrice, newGridId, newSize, type } = rotation;
5153
+ const rotation = (ctx.rotation ?? {});
5154
+ const oldOrder = rotation.oldOrder;
5155
+ const newPrice = rotation.newPrice;
5156
+ const newGridId = rotation.newGridId;
5157
+ const newSize = rotation.newSize;
5158
+ const type = rotation.type;
5090
5159
  if (!newGridId) {
5091
- const ord = bot.manager.orders.get(oldOrder.id || rotation.id);
5160
+ const ord = bot.manager.orders.get(String(oldOrder?.id || rotation.id));
5092
5161
  await applyOptimisticFeeBalance(bot, oldOrder, ord, 'order-update', btsFeeData?.updateFee || 0);
5093
5162
  if (ord) {
5094
5163
  const updatedSlot = { ...ord, size: newSize };
@@ -5104,7 +5173,7 @@ async function processBatchResults(bot, result, opContexts) {
5104
5173
  if (!slot) {
5105
5174
  bot.manager.logger.log(`[ROTATION] Destination slot ${newGridId} missing from master grid after COW commit - skipping activation, sync will reconcile`, 'error');
5106
5175
  if (oldOrder?.id && oldOrder.id !== newGridId) {
5107
- const staleSource = bot.manager.orders.get(oldOrder.id);
5176
+ const staleSource = bot.manager.orders.get(String(oldOrder.id));
5108
5177
  if (staleSource?.orderId) {
5109
5178
  updatesToApply.push({
5110
5179
  order: { ...staleSource, state: ORDER_STATES.VIRTUAL, orderId: null, rawOnChain: null },
@@ -5128,7 +5197,7 @@ async function processBatchResults(bot, result, opContexts) {
5128
5197
  }
5129
5198
  await applyOptimisticFeeBalance(bot, oldOrder, updatedSlot, 'order-update', btsFeeData?.updateFee || 0);
5130
5199
  if (oldOrder?.id && oldOrder.id !== newGridId) {
5131
- const currentSource = bot.manager.orders.get(oldOrder.id);
5200
+ const currentSource = bot.manager.orders.get(String(oldOrder.id));
5132
5201
  if (currentSource && currentSource.orderId) {
5133
5202
  updatesToApply.push({
5134
5203
  order: {
@@ -5153,7 +5222,7 @@ async function processBatchResults(bot, result, opContexts) {
5153
5222
  updateOperationCount
5154
5223
  };
5155
5224
  }
5156
- export { isLastFillGuardBlocked, resolveOnGridPivot, checkGridPriceInvariant, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast, reconcileAfterUncertainBroadcastImpl, executeWithRetryOnUncertain, executeChunkedWithRetryOnUncertain, formatPartialBroadcastSummary, executeOperationsWithStrategy, buildActionsFromPlan, buildCowResultFromPlan, applyRotationTransitionsToWorkingGrid, pollChainForConfirmation, updateOrdersOnChainBatchCOW, processBatchResults, adoptPlacedBatchFromChain, resolveRefillBoundaryHold, toRefillSlotIdSet, trackBoundaryHold };
5225
+ export { isLastFillGuardBlocked, resolveOnGridPivot, checkGridPriceInvariant, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast, reconcileAfterUncertainBroadcastImpl, executeWithRetryOnUncertain, executeChunkedWithRetryOnUncertain, formatPartialBroadcastSummary, buildActionsFromPlan, buildCowResultFromPlan, applyRotationTransitionsToWorkingGrid, pollChainForConfirmation, updateOrdersOnChainBatchCOW, processBatchResults, adoptPlacedBatchFromChain, resolveRefillBoundaryHold, toRefillSlotIdSet, trackBoundaryHold };
5157
5226
  // Exported for regression tests (issue #23 sibling): the uncertain-broadcast
5158
5227
  // discard path must never drop a placement silently when master lost the slot.
5159
5228
  export { restoreDiscardedCreates };
@@ -5177,7 +5246,6 @@ export default {
5177
5246
  executeWithRetryOnUncertain,
5178
5247
  executeChunkedWithRetryOnUncertain,
5179
5248
  formatPartialBroadcastSummary,
5180
- executeOperationsWithStrategy,
5181
5249
  validateOperationFunds,
5182
5250
  resolveIdealSizeForValidation,
5183
5251
  validateOrderSizeForExecution,