dexbot 1.6.11 → 1.6.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (354) hide show
  1. package/CHANGELOG.md +35 -4
  2. package/README.md +2 -1
  3. package/analysis/README.md +2 -0
  4. package/analysis/tradingview/README.md +1 -1
  5. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
  6. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  7. package/claw/modules/chain_broadcast.ts +7 -1
  8. package/claw/modules/claw_launcher.ts +1 -1
  9. package/claw/modules/launcher_mode_detector.ts +9 -2
  10. package/claw/package.json +1 -1
  11. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  12. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  13. package/dist/analysis/account_resolver.d.ts +1 -1
  14. package/dist/analysis/account_resolver.js +2 -1
  15. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  16. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -7
  17. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  18. package/dist/analysis/ama_fitting/fetch_lp_candles.js +4 -4
  19. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +20 -4
  20. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +9 -6
  21. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +16 -12
  22. package/dist/analysis/analyze_args.d.ts +31 -0
  23. package/dist/analysis/analyze_args.js +41 -0
  24. package/dist/analysis/analyze_dynamic_weight.js +7 -17
  25. package/dist/analysis/analyze_kalman.js +7 -17
  26. package/dist/analysis/analyze_regime.js +7 -17
  27. package/dist/analysis/analyze_regime_windows.js +8 -18
  28. package/dist/analysis/analyze_risk_profile.js +8 -18
  29. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  30. package/dist/analysis/analyze_volatility.js +7 -17
  31. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +220 -12
  32. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +6 -5
  33. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  34. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +11 -63
  35. package/dist/analysis/bot_fitting/shared_utils.d.ts +7 -7
  36. package/dist/analysis/bot_fitting/shared_utils.js +2 -2
  37. package/dist/analysis/bot_key_utils.d.ts +18 -10
  38. package/dist/analysis/bot_key_utils.js +7 -4
  39. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  40. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  41. package/dist/analysis/chain_pool.d.ts +3 -1
  42. package/dist/analysis/chart_ui.d.ts +5 -2
  43. package/dist/analysis/chart_ui.js +6 -3
  44. package/dist/analysis/chart_utils.d.ts +5 -5
  45. package/dist/analysis/chart_utils.js +9 -0
  46. package/dist/analysis/fills_cache.d.ts +1 -1
  47. package/dist/analysis/fills_source.d.ts +2 -2
  48. package/dist/analysis/fills_source.js +14 -12
  49. package/dist/analysis/grid_correction_check.d.ts +1 -1
  50. package/dist/analysis/grid_correction_check.js +12 -11
  51. package/dist/analysis/math_utils.d.ts +7 -6
  52. package/dist/analysis/math_utils.js +5 -8
  53. package/dist/analysis/pnl_report.js +29 -29
  54. package/dist/analysis/price_sources.d.ts +8 -8
  55. package/dist/analysis/price_sources.js +5 -4
  56. package/dist/analysis/resolve_bot_accounts.js +2 -2
  57. package/dist/analysis/resolve_source.d.ts +1 -1
  58. package/dist/analysis/trade_profitability.d.ts +23 -2
  59. package/dist/analysis/trade_profitability.js +50 -50
  60. package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
  61. package/dist/analysis/tradingview/analyze_tradingview.js +6 -5
  62. package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
  63. package/dist/analysis/tradingview/grid_reset_config.js +23 -11
  64. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
  65. package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
  66. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  67. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +18 -19
  68. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -1
  69. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +5 -5
  70. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  71. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +5 -4
  72. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
  73. package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
  74. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  75. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  76. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  77. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  78. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  79. package/dist/credential-daemon.js +34 -20
  80. package/dist/dexbot.js +11 -11
  81. package/dist/market_adapter/candle_utils.d.ts +22 -18
  82. package/dist/market_adapter/candle_utils.js +24 -20
  83. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  84. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  85. package/dist/market_adapter/core/kibana_candles.d.ts +53 -18
  86. package/dist/market_adapter/core/kibana_candles.js +9 -7
  87. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  88. package/dist/market_adapter/core/kibana_client.js +8 -7
  89. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  90. package/dist/market_adapter/core/market_adapter_service.d.ts +284 -117
  91. package/dist/market_adapter/core/market_adapter_service.js +137 -113
  92. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  93. package/dist/market_adapter/core/strategies/ama.js +2 -4
  94. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  95. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  96. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  97. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  98. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  99. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  100. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
  101. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
  102. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  103. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  104. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  105. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  106. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  107. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  108. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  109. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  110. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  111. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  112. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +96 -224
  113. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +42 -7
  114. package/dist/market_adapter/inputs/fetch_lp_data.js +22 -15
  115. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  116. package/dist/market_adapter/inputs/kibana_feed_source.js +29 -22
  117. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  118. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  119. package/dist/market_adapter/inputs/window_cache.d.ts +99 -94
  120. package/dist/market_adapter/inputs/window_cache.js +8 -8
  121. package/dist/market_adapter/interval_utils.d.ts +4 -4
  122. package/dist/market_adapter/log_format.d.ts +6 -6
  123. package/dist/market_adapter/log_format.js +28 -21
  124. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  125. package/dist/market_adapter/lp_chart_core.js +26 -192
  126. package/dist/market_adapter/lp_chart_runner.d.ts +7 -7
  127. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  128. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  129. package/dist/market_adapter/market_adapter.d.ts +94 -32
  130. package/dist/market_adapter/market_adapter.js +67 -48
  131. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  132. package/dist/market_adapter/utils/adapter_client.js +2 -2
  133. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  134. package/dist/market_adapter/utils/chain.d.ts +50 -41
  135. package/dist/market_adapter/utils/chain.js +40 -46
  136. package/dist/market_adapter/utils/data_discovery.d.ts +4 -1
  137. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  138. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  139. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  140. package/dist/market_adapter/utils/file_lock.js +36 -32
  141. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  142. package/dist/market_adapter/utils/native_history.js +35 -28
  143. package/dist/modules/account_bots.d.ts +577 -21
  144. package/dist/modules/account_bots.js +182 -158
  145. package/dist/modules/account_orders.d.ts +66 -30
  146. package/dist/modules/account_orders.js +22 -20
  147. package/dist/modules/authority_resolver.d.ts +12 -2
  148. package/dist/modules/authority_resolver.js +15 -8
  149. package/dist/modules/bitshares-native/chain_client.d.ts +38 -3
  150. package/dist/modules/bitshares-native/chain_client.js +45 -46
  151. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  152. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  153. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  154. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  155. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  156. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  157. package/dist/modules/bitshares-native/index.d.ts +1 -1
  158. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  159. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  160. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  161. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  162. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  163. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  164. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  165. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  166. package/dist/modules/bitshares-native/serial/types.js +55 -62
  167. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  168. package/dist/modules/bitshares-native/signing_client.js +19 -14
  169. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  170. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  171. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  172. package/dist/modules/bitshares-native/transport.js +5 -4
  173. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  174. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  175. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  176. package/dist/modules/bitshares_client.d.ts +45 -13
  177. package/dist/modules/bitshares_client.js +28 -19
  178. package/dist/modules/bot_defaults.d.ts +6 -15
  179. package/dist/modules/bot_defaults.js +1 -5
  180. package/dist/modules/bot_settings.d.ts +44 -10
  181. package/dist/modules/bot_settings.js +11 -8
  182. package/dist/modules/bots_file_lock.d.ts +6 -6
  183. package/dist/modules/bots_file_lock.js +16 -12
  184. package/dist/modules/broadcast_failure.d.ts +2 -2
  185. package/dist/modules/broadcast_failure.js +5 -4
  186. package/dist/modules/chain_keys.d.ts +42 -40
  187. package/dist/modules/chain_keys.js +53 -45
  188. package/dist/modules/chain_orders.d.ts +93 -59
  189. package/dist/modules/chain_orders.js +31 -23
  190. package/dist/modules/constants.d.ts +527 -31
  191. package/dist/modules/constants.js +15 -47
  192. package/dist/modules/cr_planner.d.ts +40 -2
  193. package/dist/modules/credential_policy.d.ts +68 -8
  194. package/dist/modules/credential_policy.js +37 -31
  195. package/dist/modules/credential_session_cache.d.ts +2 -2
  196. package/dist/modules/credit_pricing.d.ts +42 -6
  197. package/dist/modules/credit_pricing.js +44 -30
  198. package/dist/modules/credit_runtime.d.ts +276 -118
  199. package/dist/modules/credit_runtime.js +462 -165
  200. package/dist/modules/crypto/browser_provider.js +6 -4
  201. package/dist/modules/crypto/node_provider.js +1 -1
  202. package/dist/modules/crypto/pure_scrypt.js +35 -4
  203. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  204. package/dist/modules/crypto/sync.d.ts +9 -9
  205. package/dist/modules/crypto/sync.js +16 -9
  206. package/dist/modules/dexbot_class.d.ts +195 -139
  207. package/dist/modules/dexbot_class.js +78 -28
  208. package/dist/modules/dexbot_cow_runtime.d.ts +167 -87
  209. package/dist/modules/dexbot_cow_runtime.js +248 -206
  210. package/dist/modules/dexbot_credential_client.d.ts +19 -11
  211. package/dist/modules/dexbot_fill_runtime.d.ts +63 -48
  212. package/dist/modules/dexbot_fill_runtime.js +48 -41
  213. package/dist/modules/dexbot_maintenance_runtime.d.ts +109 -70
  214. package/dist/modules/dexbot_maintenance_runtime.js +108 -83
  215. package/dist/modules/dexbot_startup_runtime.d.ts +11 -10
  216. package/dist/modules/dexbot_startup_runtime.js +43 -43
  217. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  218. package/dist/modules/dexbot_state_recovery.js +18 -13
  219. package/dist/modules/fund_registry.d.ts +4 -2
  220. package/dist/modules/fund_registry.js +10 -10
  221. package/dist/modules/general_settings.d.ts +30 -4
  222. package/dist/modules/graceful_shutdown.d.ts +3 -3
  223. package/dist/modules/graceful_shutdown.js +2 -2
  224. package/dist/modules/grid_price_source.d.ts +1 -1
  225. package/dist/modules/key_store.d.ts +14 -8
  226. package/dist/modules/key_store.js +7 -6
  227. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  228. package/dist/modules/launcher/adapter_requirement.js +5 -5
  229. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  230. package/dist/modules/launcher/bot_supervisor.js +12 -11
  231. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  232. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  233. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  234. package/dist/modules/launcher/credential_daemon.js +2 -2
  235. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  236. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  237. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  238. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  239. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  240. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  241. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  242. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  243. package/dist/modules/launcher/supervisor_control.js +4 -2
  244. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  245. package/dist/modules/market_adapter_whitelist.js +15 -3
  246. package/dist/modules/node_manager.d.ts +41 -11
  247. package/dist/modules/node_manager.js +5 -4
  248. package/dist/modules/order/accounting.d.ts +53 -24
  249. package/dist/modules/order/accounting.js +16 -15
  250. package/dist/modules/order/async_lock.d.ts +5 -2
  251. package/dist/modules/order/async_lock.js +1 -1
  252. package/dist/modules/order/export.d.ts +7 -6
  253. package/dist/modules/order/export.js +1 -7
  254. package/dist/modules/order/format.d.ts +4 -4
  255. package/dist/modules/order/genesis_policy.d.ts +21 -18
  256. package/dist/modules/order/genesis_policy.js +12 -8
  257. package/dist/modules/order/grid.d.ts +142 -36
  258. package/dist/modules/order/grid.js +148 -123
  259. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  260. package/dist/modules/order/grid_reconcile.js +13 -12
  261. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  262. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  263. package/dist/modules/order/index.d.ts +263 -1
  264. package/dist/modules/order/logger.d.ts +45 -11
  265. package/dist/modules/order/logger.js +38 -40
  266. package/dist/modules/order/logger_state.d.ts +4 -4
  267. package/dist/modules/order/manager.d.ts +225 -180
  268. package/dist/modules/order/manager.js +80 -83
  269. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  270. package/dist/modules/order/processed_fill_store.js +16 -27
  271. package/dist/modules/order/strategy.d.ts +21 -13
  272. package/dist/modules/order/strategy.js +5 -6
  273. package/dist/modules/order/sync_engine.d.ts +91 -33
  274. package/dist/modules/order/sync_engine.js +84 -53
  275. package/dist/modules/order/utils/math.d.ts +157 -102
  276. package/dist/modules/order/utils/math.js +77 -38
  277. package/dist/modules/order/utils/order.d.ts +310 -110
  278. package/dist/modules/order/utils/order.js +122 -99
  279. package/dist/modules/order/utils/slot.d.ts +1 -1
  280. package/dist/modules/order/utils/system.d.ts +176 -26
  281. package/dist/modules/order/utils/system.js +86 -69
  282. package/dist/modules/order/utils/validate.d.ts +89 -41
  283. package/dist/modules/order/utils/validate.js +24 -22
  284. package/dist/modules/order/utils/withPoolRef.d.ts +4 -3
  285. package/dist/modules/order/utils/withPoolRef.js +18 -12
  286. package/dist/modules/order/working_grid.d.ts +14 -13
  287. package/dist/modules/paths.d.ts +1 -4
  288. package/dist/modules/paths.js +1 -27
  289. package/dist/modules/process_discovery.d.ts +1 -1
  290. package/dist/modules/process_discovery.js +2 -1
  291. package/dist/modules/runtime.d.ts +7 -3
  292. package/dist/modules/runtime.js +4 -3
  293. package/dist/modules/runtime_settings.d.ts +15 -10
  294. package/dist/modules/runtime_settings.js +30 -24
  295. package/dist/modules/settings_merge.d.ts +29 -3
  296. package/dist/modules/settings_merge.js +56 -78
  297. package/dist/modules/socket_json_client.d.ts +7 -4
  298. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  299. package/dist/modules/storage/browser_adapter.js +7 -30
  300. package/dist/modules/storage/index.d.ts +1 -1
  301. package/dist/modules/storage/node_adapter.d.ts +45 -27
  302. package/dist/modules/storage/node_adapter.js +9 -9
  303. package/dist/modules/storage/types.d.ts +5 -4
  304. package/dist/modules/types.d.ts +1071 -2
  305. package/dist/modules/types.js +4 -1
  306. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  307. package/dist/modules/utils/asset_symbols.js +2 -1
  308. package/dist/modules/utils/errors.d.ts +9 -0
  309. package/dist/modules/utils/errors.js +23 -1
  310. package/dist/modules/utils/time_range.d.ts +1 -12
  311. package/dist/modules/utils/time_range.js +1 -1
  312. package/dist/modules/validate_profiles.js +53 -43
  313. package/dist/modules/version_notice.d.ts +14 -3
  314. package/dist/modules/version_notice.js +6 -4
  315. package/dist/pm2.d.ts +29 -27
  316. package/dist/pm2.js +5 -5
  317. package/dist/scripts/analyze-credit.d.ts +2 -1
  318. package/dist/scripts/analyze-credit.js +23 -24
  319. package/dist/scripts/analyze-orders.d.ts +77 -9
  320. package/dist/scripts/analyze-orders.js +65 -40
  321. package/dist/scripts/chart_command.d.ts +27 -18
  322. package/dist/scripts/chart_command.js +13 -11
  323. package/dist/scripts/check_any.d.ts +18 -0
  324. package/dist/scripts/check_any.js +126 -0
  325. package/dist/scripts/diagnose-pool-history.js +12 -7
  326. package/dist/scripts/print_grid.js +0 -1
  327. package/dist/scripts/run-tests.js +39 -7
  328. package/dist/scripts/runner.js +1 -1
  329. package/dist/scripts/test-credit-renewal.js +30 -21
  330. package/dist/scripts/update.d.ts +10 -5
  331. package/dist/scripts/update.js +168 -103
  332. package/dist/scripts/update_dist_freshness.js +1 -0
  333. package/dist/scripts/update_layout.d.ts +61 -0
  334. package/dist/scripts/update_layout.js +180 -0
  335. package/dist/scripts/validate_bots.js +2 -1
  336. package/dist/scripts/verify-browser-bundle.js +8 -0
  337. package/dist/unlock.d.ts +28 -3
  338. package/dist/unlock.js +63 -35
  339. package/docs/BITSHARES_ONBOARDING.md +2 -0
  340. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  341. package/docs/COW_INVARIANTS.md +13 -6
  342. package/docs/DEXBOT_COMPARISON.md +8 -8
  343. package/docs/EVOLUTION.md +10 -9
  344. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  345. package/docs/GRID_RECALCULATION.md +4 -2
  346. package/docs/GRID_RECONCILE.md +14 -3
  347. package/docs/LIFECYCLE.md +11 -11
  348. package/docs/MPA_CREDIT_USAGE.md +22 -3
  349. package/docs/README.md +14 -3
  350. package/docs/architecture.md +12 -9
  351. package/docs/developer_guide.md +6 -6
  352. package/market_adapter/README.md +6 -1
  353. package/modules/README.md +4 -1
  354. package/package.json +4 -1
@@ -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 {
@@ -76,7 +76,7 @@ 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
@@ -958,9 +959,9 @@ async function reconcileAfterUncertainBroadcastImpl(bot, err, opContexts, _optio
958
959
  chainReadTruncated = chainRead.truncated;
959
960
  }
960
961
  catch (readErr) {
961
- bot.manager.logger.log(`[COW][UNCERTAIN] readOpenOrders failed: ${readErr?.message || readErr}. ` +
962
+ bot.manager.logger.log(`[COW][UNCERTAIN] readOpenOrders failed: ${getErrorMessage(readErr)}. ` +
962
963
  `Falling back to structural resync.`, 'error');
963
- await requestStructuralResync(bot, 'broadcast uncertain — readOpenOrders failed', { batchId: err?.batchId || null, error: readErr?.message || String(readErr) });
964
+ await requestStructuralResync(bot, 'broadcast uncertain — readOpenOrders failed', { batchId: err?.batchId || null, error: getErrorMessage(readErr) || String(readErr) });
964
965
  clearPendingBroadcasts(bot.manager?._pendingBroadcasts);
965
966
  return { executed: false, hadRotation: false, uncertain: true };
966
967
  }
@@ -981,7 +982,7 @@ async function reconcileAfterUncertainBroadcastImpl(bot, err, opContexts, _optio
981
982
  // second pass, and a TOCTOU re-read for discarded CREATEs (see
982
983
  // matchPendingToChain). A deferred re-read returns its result directly.
983
984
  const matched = await matchPendingToChain(bot, pending, chainSnapshot, opContexts, accountRef, err);
984
- if (matched.deferred)
985
+ if ('deferred' in matched)
985
986
  return matched.deferred;
986
987
  const { adopted, discarded } = matched;
987
988
  // 3b. Apply decisions
@@ -999,7 +1000,7 @@ async function reconcileAfterUncertainBroadcastImpl(bot, err, opContexts, _optio
999
1000
  await bot.manager.persistGrid();
1000
1001
  }
1001
1002
  catch (persistErr) {
1002
- bot.manager.logger.log(`[COW][UNCERTAIN] Persist after reconcile failed: ${persistErr?.message || persistErr}`, 'error');
1003
+ bot.manager.logger.log(`[COW][UNCERTAIN] Persist after reconcile failed: ${getErrorMessage(persistErr)}`, 'error');
1003
1004
  }
1004
1005
  }
1005
1006
  }
@@ -1023,9 +1024,9 @@ function shouldExecuteCreatePairMode(_bot, opContexts) {
1023
1024
  let hasBuy = false;
1024
1025
  let hasSell = false;
1025
1026
  for (const ctx of opContexts) {
1026
- if (ctx.order.type === ORDER_TYPES.BUY)
1027
+ if (ctx.order?.type === ORDER_TYPES.BUY)
1027
1028
  hasBuy = true;
1028
- if (ctx.order.type === ORDER_TYPES.SELL)
1029
+ if (ctx.order?.type === ORDER_TYPES.SELL)
1029
1030
  hasSell = true;
1030
1031
  if (hasBuy && hasSell)
1031
1032
  return true;
@@ -1062,11 +1063,13 @@ function verifyOpAgainstChain(bot, freshChain, ctx) {
1062
1063
  function verifyCreateAbsent(bot, freshChain, ctx) {
1063
1064
  if (!ctx.finalInts || !ctx.order)
1064
1065
  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)
1066
+ const finalInts = ctx.finalInts;
1067
+ const order = ctx.order;
1068
+ const match = findChainOrderForSlot(bot, freshChain, order.id, {
1069
+ sell: finalInts.sell,
1070
+ receive: finalInts.receive,
1071
+ orderType: order.type,
1072
+ fingerprint: createOpFingerprintForSlot(bot, order, finalInts, order.id)
1070
1073
  });
1071
1074
  return match ? 'landed' : 'absent';
1072
1075
  }
@@ -1093,12 +1096,14 @@ function verifyCancelLanded(freshChain, ctx) {
1093
1096
  * concurrently) → 'unknown' (defer).
1094
1097
  */
1095
1098
  function verifyUpdateUnapplied(freshChain, ctx) {
1099
+ const updateInfo = ctx.updateInfo;
1100
+ const rotation = ctx.rotation;
1096
1101
  const chainOrderId = ctx.kind === 'size-update'
1097
- ? ctx.updateInfo?.partialOrder?.orderId
1098
- : ctx.rotation?.oldOrder?.orderId;
1102
+ ? (updateInfo?.partialOrder?.orderId)
1103
+ : (rotation?.oldOrder?.orderId);
1099
1104
  const cachedRaw = ctx.kind === 'size-update'
1100
- ? ctx.updateInfo?.partialOrder?.rawOnChain
1101
- : ctx.rotation?.oldOrder?.rawOnChain;
1105
+ ? (updateInfo?.partialOrder?.rawOnChain)
1106
+ : (rotation?.oldOrder?.rawOnChain);
1102
1107
  if (!chainOrderId)
1103
1108
  return 'unknown';
1104
1109
  const chainOrder = freshChain.find((o) => String(o?.id ?? '') === String(chainOrderId));
@@ -1134,7 +1139,7 @@ async function executeWithRetryOnUncertain(bot, operations, opContexts) {
1134
1139
  }
1135
1140
  catch (err) {
1136
1141
  const isRetriable = err instanceof BroadcastUncertainError
1137
- && !err.partialOnChainState
1142
+ && !getErrorField(err, 'partialOnChainState')
1138
1143
  && attempt <= MAX_RETRIES;
1139
1144
  if (isRetriable) {
1140
1145
  // Verify per operation kind against a live snapshot before
@@ -1165,7 +1170,7 @@ async function executeWithRetryOnUncertain(bot, operations, opContexts) {
1165
1170
  }
1166
1171
  }
1167
1172
  catch (verifyErr) {
1168
- bot.manager.logger.log(`[COW] Pre-retry chain verification failed (non-fatal): ${verifyErr?.message || verifyErr}`, 'warn');
1173
+ bot.manager.logger.log(`[COW] Pre-retry chain verification failed (non-fatal): ${getErrorMessage(verifyErr)}`, 'warn');
1169
1174
  }
1170
1175
  if (absence === 'absent') {
1171
1176
  bot.manager.logger.log(`[COW] Broadcast uncertain (attempt ${attempt}/${MAX_RETRIES + 1}); verified unapplied on chain, retrying...`, 'warn');
@@ -1209,17 +1214,18 @@ async function executeWithRetryOnUncertain(bot, operations, opContexts) {
1209
1214
  function formatPartialBroadcastSummary(err) {
1210
1215
  if (!err || typeof err !== 'object')
1211
1216
  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;
1217
+ const info = err;
1218
+ if (info.chunkedBroadcast === true) {
1219
+ const total = Number.isFinite(Number(info.chunksTotal)) ? Number(info.chunksTotal) : null;
1220
+ const failed = Number.isFinite(Number(info.chunksFailed)) ? Number(info.chunksFailed) : 0;
1221
+ const aborted = Number.isFinite(Number(info.chunksAborted)) ? Number(info.chunksAborted) : 0;
1216
1222
  if (total === null)
1217
1223
  return '?/? chunks broadcast';
1218
1224
  const broadcast = Math.max(0, total - failed - aborted);
1219
1225
  return `${broadcast}/${total} chunks broadcast`;
1220
1226
  }
1221
- const broadcast = err.groupsBroadcast;
1222
- const total = err.groupsTotal;
1227
+ const broadcast = info.groupsBroadcast;
1228
+ const total = info.groupsTotal;
1223
1229
  return `${broadcast ?? '?'}/${total ?? '?'} groups broadcast`;
1224
1230
  }
1225
1231
  /**
@@ -1298,13 +1304,14 @@ async function executeChunkedWithRetryOnUncertain(bot, operations, opContexts) {
1298
1304
  }
1299
1305
  catch (err) {
1300
1306
  if (firstFailure === null)
1301
- firstFailure = { index: idx, err };
1307
+ firstFailure = { index: idx, err: err };
1302
1308
  failedChunkCount++;
1303
- const failedChunkLandedOps = Number.isFinite(Number(err.broadcastedOperationCount))
1304
- ? Number(err.broadcastedOperationCount)
1309
+ const rawFailedChunkLandedOps = getErrorField(err, 'broadcastedOperationCount');
1310
+ const failedChunkLandedOps = Number.isFinite(Number(rawFailedChunkLandedOps))
1311
+ ? Number(rawFailedChunkLandedOps)
1305
1312
  : 0;
1306
1313
  landedOpsFromFailures += failedChunkLandedOps;
1307
- if (err.partialOnChainState === true || failedChunkLandedOps > 0)
1314
+ if (getErrorField(err, 'partialOnChainState') === true || failedChunkLandedOps > 0)
1308
1315
  anyFailurePartial = true;
1309
1316
  if (err instanceof BroadcastUncertainError) {
1310
1317
  // Uncertainty: the tx result is unknown — the chunk may or may
@@ -1395,10 +1402,11 @@ async function executeOperationsWithStrategy(bot, operations, opContexts) {
1395
1402
  const groupsTotal = groups.length;
1396
1403
  const broadcastedOperationCount = mergedContexts.length;
1397
1404
  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;
1405
+ const broadcastErrAugment = err;
1406
+ broadcastErrAugment.partialOnChainState = groupsBroadcast > 0;
1407
+ broadcastErrAugment.groupsBroadcast = groupsBroadcast;
1408
+ broadcastErrAugment.groupsTotal = groupsTotal;
1409
+ broadcastErrAugment.broadcastedOperationCount = broadcastedOperationCount;
1402
1410
  throw err;
1403
1411
  }
1404
1412
  const groupOpResults = extractOperationResults(groupResult, '', bot.manager?.logger?.log?.bind(bot.manager?.logger));
@@ -1438,25 +1446,30 @@ function validateOperationFunds(bot, operations, assetA, assetB) {
1438
1446
  snap = { chainFreeSell: 0, chainFreeBuy: 0 };
1439
1447
  bot.manager?.logger?.log?.('[COW][VALIDATION] getChainFundsSnapshot unavailable — fund validation skipped (assuming no balance)', 'warn');
1440
1448
  }
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 };
1449
+ const assetKeyA = assetA.id ?? '';
1450
+ const assetKeyB = assetB.id ?? '';
1451
+ const netRequiredFunds = { [assetKeyA]: 0, [assetKeyB]: 0 };
1452
+ const runningRequiredFunds = { [assetKeyA]: 0, [assetKeyB]: 0 };
1453
+ const peakRequiredFunds = { [assetKeyA]: 0, [assetKeyB]: 0 };
1444
1454
  for (const op of operations) {
1445
- if (!op?.op_data)
1455
+ const opData = op?.op_data;
1456
+ if (!opData)
1446
1457
  continue;
1447
1458
  let sellAssetId = null;
1448
- let sellAmountInt = 0;
1459
+ let sellAmountInt = null;
1449
1460
  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;
1461
+ const ats = opData.amount_to_sell;
1462
+ sellAssetId = ats?.asset_id ?? null;
1463
+ sellAmountInt = ats?.amount != null ? Number(ats.amount) : null;
1452
1464
  }
1453
1465
  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;
1466
+ const base = opData.new_price?.base;
1467
+ sellAssetId = base?.asset_id ?? null;
1468
+ sellAmountInt = base?.amount != null ? Number(base.amount) : null;
1456
1469
  }
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;
1470
+ if (sellAssetId && sellAmountInt != null) {
1471
+ const precision = (sellAssetId === assetKeyA) ? assetA.precision : assetB.precision;
1472
+ const assetSymbol = (sellAssetId === assetKeyA) ? assetA.symbol : assetB.symbol;
1460
1473
  if (Number(sellAmountInt) <= 0) {
1461
1474
  return {
1462
1475
  isValid: false,
@@ -1466,8 +1479,9 @@ function validateOperationFunds(bot, operations, assetA, assetB) {
1466
1479
  }
1467
1480
  let signedDelta = 0;
1468
1481
  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;
1482
+ const deltaAmount = opData.delta_amount_to_sell;
1483
+ const deltaAssetId = deltaAmount?.asset_id;
1484
+ const deltaSellInt = deltaAmount?.amount;
1471
1485
  if (deltaAssetId === sellAssetId && Number.isFinite(Number(deltaSellInt))) {
1472
1486
  signedDelta = blockchainToFloat(deltaSellInt, precision);
1473
1487
  }
@@ -1482,18 +1496,18 @@ function validateOperationFunds(bot, operations, assetA, assetB) {
1482
1496
  }
1483
1497
  }
1484
1498
  const availableFunds = {
1485
- [assetA.id]: quantizeFloat(snap.chainFreeSell || 0, assetA.precision),
1486
- [assetB.id]: quantizeFloat(snap.chainFreeBuy || 0, assetB.precision)
1499
+ [assetKeyA]: quantizeFloat(snap.chainFreeSell || 0, assetA.precision),
1500
+ [assetKeyB]: quantizeFloat(snap.chainFreeBuy || 0, assetB.precision)
1487
1501
  };
1488
1502
  const fundViolations = [];
1489
1503
  for (const assetId in peakRequiredFunds) {
1490
1504
  const required = peakRequiredFunds[assetId];
1491
1505
  const netRequired = netRequiredFunds[assetId] || 0;
1492
1506
  const available = availableFunds[assetId] || 0;
1493
- const prec = (assetId === assetA.id) ? assetA.precision : assetB.precision;
1507
+ const prec = (assetId === assetKeyA) ? assetA.precision : assetB.precision;
1494
1508
  if (floatToBlockchainInt(required, prec) > floatToBlockchainInt(available, prec)) {
1495
1509
  fundViolations.push({
1496
- asset: assetId === assetA.id ? assetA.symbol : assetB.symbol,
1510
+ asset: assetId === assetKeyA ? assetA.symbol : assetB.symbol,
1497
1511
  required,
1498
1512
  netRequired,
1499
1513
  available,
@@ -1504,7 +1518,7 @@ function validateOperationFunds(bot, operations, assetA, assetB) {
1504
1518
  if (fundViolations.length > 0) {
1505
1519
  let summary = `[VALIDATION] Fund validation FAILED:\n`;
1506
1520
  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`;
1521
+ 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
1522
  }
1509
1523
  return { isValid: false, summary: summary.trim(), violations: fundViolations };
1510
1524
  }
@@ -1519,11 +1533,12 @@ function validateOperationFunds(bot, operations, assetA, assetB) {
1519
1533
  * @returns {number|null}
1520
1534
  */
1521
1535
  function resolveIdealSizeForValidation(_bot, orderLike, fallbackSize = null) {
1536
+ const nested = orderLike?.order;
1522
1537
  const candidates = [
1523
1538
  orderLike?.idealSize,
1524
- orderLike?.order?.idealSize,
1539
+ nested?.idealSize,
1525
1540
  orderLike?.size,
1526
- orderLike?.order?.size,
1541
+ nested?.size,
1527
1542
  fallbackSize
1528
1543
  ];
1529
1544
  for (const candidate of candidates) {
@@ -1541,7 +1556,7 @@ function resolveIdealSizeForValidation(_bot, orderLike, fallbackSize = null) {
1541
1556
  * @param {string} type
1542
1557
  * @param {Object|null} [orderLike=null]
1543
1558
  * @param {number|null} [fallbackSize=null]
1544
- * @returns {any}
1559
+ * @returns {unknown}
1545
1560
  */
1546
1561
  function validateOrderSizeForExecution(bot, size, type, orderLike = null, fallbackSize = null) {
1547
1562
  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 +1635,7 @@ function recordGridPriceInvariantCheck(bot, slotId, price, stats, site) {
1620
1635
  return true;
1621
1636
  }
1622
1637
  stats.violated++;
1623
- orderUtils.reportGridPriceInvariant(bot?.manager, slotId, price, site);
1638
+ orderUtils.reportGridPriceInvariant(bot?.manager, String(slotId), price, site);
1624
1639
  considerGridPriceInvariantEscalation(bot, slotId, price, inv, site);
1625
1640
  return false;
1626
1641
  }
@@ -1641,7 +1656,7 @@ function recordGridPriceInvariantCheck(bot, slotId, price, stats, site) {
1641
1656
  * Keeping it on the bot also keeps the count from outliving the resync that
1642
1657
  * repairs the slot, and lets tests start from a clean slate.
1643
1658
  *
1644
- * @param {any} bot
1659
+ * @param {unknown} bot
1645
1660
  * @returns {Map<string, number>}
1646
1661
  */
1647
1662
  function getInvariantRejectStreak(bot) {
@@ -1832,9 +1847,11 @@ function refreshLastFillPivotFromQueue(bot) {
1832
1847
  // SPREAD slots carrying on-chain orders).
1833
1848
  if ((type == null || price == null) && fillOp?.pays && fillOp?.receives && assets?.assetA && assets?.assetB) {
1834
1849
  try {
1835
- const paysId = fillOp.pays.asset_id;
1836
- const paysAmt = Number(fillOp.pays.amount);
1837
- const recvAmt = Number(fillOp.receives.amount);
1850
+ const pays = fillOp.pays;
1851
+ const receives = fillOp.receives;
1852
+ const paysId = pays.asset_id;
1853
+ const paysAmt = Number(pays.amount);
1854
+ const recvAmt = Number(receives.amount);
1838
1855
  if (Number.isFinite(paysAmt) && paysAmt > 0 && Number.isFinite(recvAmt) && recvAmt > 0) {
1839
1856
  const paysFloat = (base, precision) => base / Math.pow(10, precision);
1840
1857
  if (paysId === assets.assetA.id) {
@@ -1908,19 +1925,23 @@ function buildActionsFromPlan(_bot, plan) {
1908
1925
  const normalizedPlan = Array.isArray(plan)
1909
1926
  ? { ordersToPlace: plan }
1910
1927
  : (plan || {});
1911
- const { ordersToPlace = [], ordersToRotate = [], ordersToUpdate = [], ordersToCancel = [] } = normalizedPlan;
1928
+ const ordersToPlace = (normalizedPlan.ordersToPlace ?? []);
1929
+ const ordersToRotate = (normalizedPlan.ordersToRotate ?? []);
1930
+ const ordersToUpdate = (normalizedPlan.ordersToUpdate ?? []);
1931
+ const ordersToCancel = (normalizedPlan.ordersToCancel ?? []);
1912
1932
  // Per-action origin: guard bypasses are scoped per action (not per batch),
1913
1933
  // so a future rotation entry merged into a correction plan cannot silently
1914
1934
  // inherit the spread-correction bypass. Actions built outside this helper
1915
1935
  // carry no origin and default to guarded (safe default).
1916
- const planOrigin = normalizedPlan?.origin;
1936
+ const planOrigin = normalizedPlan.origin;
1917
1937
  // B-stamp inputs: the plan-level boundary + gap width frozen AT
1918
1938
  // PLAN-BUILD TIME. The stamp carries this geometry so the execution
1919
1939
  // guard can bypass on it — and re-verifies it against the LIVE
1920
1940
  // committed geometry at execution time (isEvacuationStampStillValid),
1921
1941
  // 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);
1942
+ const mgrView = _bot?.manager;
1943
+ const frozenBoundaryRaw = Number(normalizedPlan.boundaryIdx ?? mgrView?.boundaryIdx);
1944
+ const frozenGapRaw = Number(normalizedPlan.gapSlots ?? mgrView?._gapSlots);
1924
1945
  const hasFrozenGeometry = Number.isFinite(frozenBoundaryRaw) && Number.isFinite(frozenGapRaw) && frozenGapRaw >= 0;
1925
1946
  const withOrigin = (action, sourceMaster = null) => {
1926
1947
  if (!planOrigin)
@@ -1949,7 +1970,7 @@ function buildActionsFromPlan(_bot, plan) {
1949
1970
  // The stampler wants the ORDER type (SELL/BUY), which rides on
1950
1971
  // action.order.type — action.type is the COW action kind ('update').
1951
1972
  const rotOrderType = action?.order?.type ?? action?.type;
1952
- const proved = stampGapEvacuationRotation(base, sourceMaster, action.newPrice, action.newSize, rotOrderType, frozenBoundaryRaw, frozenGapRaw, _bot?.manager?.assets);
1973
+ const proved = stampGapEvacuationRotation(base, sourceMaster, action.newPrice, action.newSize, rotOrderType, frozenBoundaryRaw, frozenGapRaw, mgrView?.assets);
1953
1974
  // Proof refused: strip the origin so the action is exactly an
1954
1975
  // unstamped rotation (never an origin claim without a stamp).
1955
1976
  if (!proved?.evacBoundary && !proved?.evacGapSlots) {
@@ -1960,21 +1981,22 @@ function buildActionsFromPlan(_bot, plan) {
1960
1981
  const actions = [];
1961
1982
  for (const o of ordersToCancel) {
1962
1983
  if (o?.orderId) {
1963
- actions.push({ type: COW_ACTIONS.CANCEL, id: o.id, orderId: o.orderId });
1984
+ actions.push({ type: COW_ACTIONS.CANCEL, id: String(o.id), orderId: o.orderId });
1964
1985
  }
1965
1986
  }
1966
1987
  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;
1988
+ const rv = r;
1989
+ const oldOrder = (rv.oldOrder ?? rv);
1990
+ const id = String(oldOrder.id ?? rv.id ?? '');
1991
+ const orderId = (oldOrder.orderId ?? rv.orderId);
1992
+ const newGridId = String(rv.newGridId ?? id);
1993
+ const newSize = Number.isFinite(Number(rv.newSize))
1994
+ ? Number(rv.newSize)
1995
+ : Number(rv.size || oldOrder.size || 0);
1996
+ const newPrice = Number.isFinite(Number(rv.newPrice))
1997
+ ? Number(rv.newPrice)
1998
+ : Number(rv.price || oldOrder.price);
1999
+ const orderType = (rv.type || oldOrder.type);
1978
2000
  if (!id || !orderId || !newGridId || !orderType || !Number.isFinite(newPrice) || !(newSize > 0))
1979
2001
  continue;
1980
2002
  actions.push(withOrigin({
@@ -1993,13 +2015,14 @@ function buildActionsFromPlan(_bot, plan) {
1993
2015
  }, oldOrder));
1994
2016
  }
1995
2017
  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);
2018
+ const ov = o;
2019
+ const partialOrder = (ov.partialOrder ?? ov);
2020
+ const id = String(ov.id ?? partialOrder.id ?? '');
2021
+ const orderId = (ov.orderId ?? partialOrder.orderId);
2022
+ const orderType = (ov.type || partialOrder.type);
2023
+ const newSize = Number.isFinite(Number(ov.newSize))
2024
+ ? Number(ov.newSize)
2025
+ : Number(partialOrder.size || 0);
2003
2026
  if (!id || !orderId)
2004
2027
  continue;
2005
2028
  actions.push(withOrigin({
@@ -2019,7 +2042,7 @@ function buildActionsFromPlan(_bot, plan) {
2019
2042
  for (const o of ordersToPlace) {
2020
2043
  if (!o?.id)
2021
2044
  continue;
2022
- actions.push(withOrigin({ type: COW_ACTIONS.CREATE, id: o.id, order: o }));
2045
+ actions.push(withOrigin({ type: COW_ACTIONS.CREATE, id: String(o.id), order: o }));
2023
2046
  }
2024
2047
  return actions;
2025
2048
  }
@@ -2129,9 +2152,9 @@ function buildCowResultFromPlan(bot, plan) {
2129
2152
  return {
2130
2153
  workingGrid,
2131
2154
  workingIndexes: workingGrid.getIndexes(),
2132
- workingBoundary,
2155
+ workingBoundary: workingBoundary,
2133
2156
  actions,
2134
- origin: plan?.origin,
2157
+ origin: plan.origin,
2135
2158
  ...(refillSlotIds !== undefined ? { refillSlotIds } : {})
2136
2159
  };
2137
2160
  }
@@ -2151,23 +2174,30 @@ function applyRotationTransitionsToWorkingGrid(bot, workingGrid, executedContext
2151
2174
  for (const ctx of executedContexts) {
2152
2175
  if (ctx.kind !== 'rotation' || !ctx.rotation?.newGridId)
2153
2176
  continue;
2154
- const { rotation } = ctx;
2155
- const { oldOrder, newGridId, newPrice, newSize, type } = rotation;
2177
+ const rotation = ctx.rotation;
2178
+ const oldOrder = rotation?.oldOrder;
2179
+ const oldOrderId = oldOrder?.id != null ? String(oldOrder.id) : null;
2180
+ const newGridId = String(rotation?.newGridId ?? '');
2181
+ const newPrice = rotation?.newPrice;
2182
+ const newSize = rotation?.newSize;
2183
+ const type = rotation?.type;
2184
+ if (!newGridId)
2185
+ continue;
2156
2186
  // Source slot → VIRTUAL (if it's a different slot). Phase 2: the
2157
2187
  // source stays a RAIL-TYPED hole with its booked size preserved —
2158
2188
  // only state/orderId/rawOnChain are cleared, never type or size
2159
2189
  // (no SPREAD retype, no zeroing). In-rail sources must remain
2160
2190
  // visible to candidate-selection and evacuation geometry.
2161
- if (oldOrder?.id && oldOrder.id !== newGridId) {
2162
- const sourceSlot = workingGrid.get(oldOrder.id);
2191
+ if (oldOrderId && oldOrderId !== newGridId) {
2192
+ const sourceSlot = workingGrid.get(oldOrderId);
2163
2193
  if (sourceSlot && sourceSlot.orderId) {
2164
- workingGrid.set(oldOrder.id, {
2194
+ workingGrid.set(oldOrderId, {
2165
2195
  ...sourceSlot,
2166
2196
  state: ORDER_STATES.VIRTUAL,
2167
2197
  orderId: null,
2168
2198
  rawOnChain: null,
2169
2199
  });
2170
- bot.manager.logger.log(`[COW] Pre-applied rotation: source ${oldOrder.id} → VIRTUAL (order ${sourceSlot.orderId} moved to ${newGridId})`, 'debug');
2200
+ bot.manager.logger.log(`[COW] Pre-applied rotation: source ${oldOrderId} → VIRTUAL (order ${sourceSlot.orderId} moved to ${newGridId})`, 'debug');
2171
2201
  }
2172
2202
  }
2173
2203
  // Destination slot → ACTIVE with inherited orderId from source
@@ -2176,7 +2206,7 @@ function applyRotationTransitionsToWorkingGrid(bot, workingGrid, executedContext
2176
2206
  workingGrid.set(newGridId, {
2177
2207
  ...destSlot,
2178
2208
  id: newGridId,
2179
- type,
2209
+ type: type,
2180
2210
  size: newSize,
2181
2211
  price: newPrice,
2182
2212
  state: ORDER_STATES.ACTIVE,
@@ -2209,7 +2239,7 @@ function applyRotationTransitionsToWorkingGrid(bot, workingGrid, executedContext
2209
2239
  * @returns {{ allConfirmed: boolean, confirmed: Array, unconfirmed: Array }}
2210
2240
  */
2211
2241
  async function pollChainForConfirmation(bot, opContexts, options = {}) {
2212
- const maxPollRetries = options.maxPollRetries || 4;
2242
+ const maxPollRetries = Number(options.maxPollRetries) || 4;
2213
2243
  // Test seam (see updateOrdersOnChainBatchCOW): bot._testPollIntervalMs
2214
2244
  // overrides the production pacing when set by the tests. An explicit 0 is
2215
2245
  // honored; null/undefined falls through to the production 1.5s default.
@@ -2217,7 +2247,7 @@ async function pollChainForConfirmation(bot, opContexts, options = {}) {
2217
2247
  const seamMs = bot?._testPollIntervalMs;
2218
2248
  const pollIntervalMs = resolveSeamMs(explicitPollMs, resolveSeamMs(seamMs, 1500));
2219
2249
  // 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);
2250
+ const createContexts = opContexts.filter((ctx) => !!ctx && ctx.kind === 'create' && !!ctx.finalInts && !!ctx.order);
2221
2251
  if (createContexts.length === 0) {
2222
2252
  return { allConfirmed: false, confirmed: [], unconfirmed: [...opContexts], confirmedChainIds: [] };
2223
2253
  }
@@ -2353,10 +2383,10 @@ function resolveRefillBoundaryHold(workingBoundary, committedBoundary, skippedUp
2353
2383
  * re-plan from unchanged master re-derives the identical plan and re-hits
2354
2384
  * the identical guard blocks, so it is suppressed rather than re-broadcast;
2355
2385
  * the heal path is a fresh fill-driven plan or the re-center.
2356
- * @param {any} manager - Order manager (mutable tracking fields)
2386
+ * @param {unknown} manager - Order manager (mutable tracking fields)
2357
2387
  * @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
2388
+ * @param {unknown} keptBoundary - Committed boundary that was kept
2389
+ * @param {unknown} plannedBoundary - Boundary the plan wanted
2360
2390
  * @param {string[]} heldSlotIds - Refill slots skipped this batch
2361
2391
  * @returns {number} Consecutive-hold count after this batch (0 when clear)
2362
2392
  */
@@ -2391,7 +2421,7 @@ function trackBoundaryHold(manager, held, keptBoundary, plannedBoundary, heldSlo
2391
2421
  /**
2392
2422
  * Restore skipped update slots in the working grid to master state.
2393
2423
  * @param {import('./dexbot_class.js').DEXBot} bot
2394
- * @param {any} workingGrid
2424
+ * @param {unknown} workingGrid
2395
2425
  * @param {Set<string>} skippedSlotIds
2396
2426
  * @param {number} [skippedCount=0]
2397
2427
  */
@@ -2687,7 +2717,7 @@ async function runPreBroadcastGuards(bot, cowResult) {
2687
2717
  if (action.type !== COW_ACTIONS.CREATE)
2688
2718
  return true;
2689
2719
  const targetId = action.id || action.order?.id;
2690
- return !violatingIds.has(targetId);
2720
+ return !violatingIds.has(String(targetId));
2691
2721
  });
2692
2722
  actions.length = 0;
2693
2723
  actions.push(...filteredActions);
@@ -2740,13 +2770,13 @@ async function runPreBroadcastGuards(bot, cowResult) {
2740
2770
  await reconcileAfterUncertainBroadcast(bot, new BroadcastUncertainError('rejected CREATE batch had pending broadcasts', {
2741
2771
  operations: pendingBroadcasts.map((p) => p.order),
2742
2772
  accountName: bot.account,
2743
- batchId: bot._currentBatchId || null,
2773
+ batchId: bot._currentBatchId != null ? String(bot._currentBatchId) : null,
2744
2774
  payload: null,
2745
2775
  timeoutMs: null
2746
2776
  }), []);
2747
2777
  }
2748
2778
  catch (recoverErr) {
2749
- bot.manager.logger.log(`[COW] Recovery from pending broadcasts failed: ${recoverErr?.message || recoverErr}`, 'error');
2779
+ bot.manager.logger.log(`[COW] Recovery from pending broadcasts failed: ${getErrorMessage(recoverErr)}`, 'error');
2750
2780
  }
2751
2781
  popPushedWorkingGrid(bot, cowResult);
2752
2782
  return {
@@ -2812,7 +2842,7 @@ async function runPreBroadcastGuards(bot, cowResult) {
2812
2842
  }
2813
2843
  }
2814
2844
  catch (syncErr) {
2815
- bot.manager.logger.log(`[COW] Failed to sync/unmatched orders: ${syncErr?.message || syncErr}`, 'warn');
2845
+ bot.manager.logger.log(`[COW] Failed to sync/unmatched orders: ${getErrorMessage(syncErr)}`, 'warn');
2816
2846
  }
2817
2847
  await requestStructuralResync(bot, 'unmatched chain orders before COW create', { unmatchedChainOrders: unmatchedChainOrders });
2818
2848
  bot.manager.logger.log(`[COW] Rejecting CREATE batch after sync: working grid invalidated by master mutation`, 'info');
@@ -2964,10 +2994,10 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
2964
2994
  const drainResult = await orderUtils.correctAllPriceMismatches(bot.manager, bot.account, bot.privateKey, chainOrders);
2965
2995
  if (drainResult?.failed > 0) {
2966
2996
  bot.manager.logger.log(`[COW] ${drainResult.failed} correction(s) failed pre-batch` +
2967
- (drainResult.staleDropped > 0 ? `, ${drainResult.staleDropped} stale dropped` : '') +
2997
+ ((drainResult.staleDropped ?? 0) > 0 ? `, ${drainResult.staleDropped} stale dropped` : '') +
2968
2998
  `; remaining entries retry on next sync/maintenance tick`, 'warn');
2969
2999
  }
2970
- else if (drainResult?.staleDropped > 0) {
3000
+ else if ((drainResult?.staleDropped ?? 0) > 0) {
2971
3001
  bot.manager.logger.log(`[COW] Pre-batch drain resolved, ${drainResult.staleDropped} stale correction(s) dropped`, 'info');
2972
3002
  }
2973
3003
  }
@@ -2980,8 +3010,8 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
2980
3010
  // runPreBroadcastGuards. Refusals already popped the working grid.
2981
3011
  const guards = await runPreBroadcastGuards(bot, cowResult);
2982
3012
  if (!guards.proceed)
2983
- return guards.result;
2984
- const { crossingCandidates, intraBatchCandidates } = guards;
3013
+ return guards.result ?? { executed: false, hadRotation: false };
3014
+ const { crossingCandidates = [], intraBatchCandidates = [] } = guards;
2985
3015
  const { assetA, assetB } = bot.manager.assets;
2986
3016
  const operations = [];
2987
3017
  const opContexts = [];
@@ -3089,7 +3119,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3089
3119
  if (action.orderId)
3090
3120
  cancelOpIndexByOrderId.set(action.orderId, operations.length - 1);
3091
3121
  const order = bot.manager.orders.get(action.id) || { id: action.id, orderId: action.orderId };
3092
- opContexts.push({ kind: 'cancel', order });
3122
+ opContexts.push({ kind: 'cancel', order: order });
3093
3123
  }
3094
3124
  catch (err) {
3095
3125
  const orderNotFound = /\bnot found\b/i.test(getErrorMessage(err)) || /\bdoes not exist\b/i.test(getErrorMessage(err));
@@ -3139,7 +3169,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3139
3169
  if (batchCollision) {
3140
3170
  bot.manager.logger.log(`[COW] Skipping CREATE for ${order.id} at ${Format.formatPrice6(createPrice)}: ` +
3141
3171
  `same-batch CREATE ${batchCollision.id} already at ` +
3142
- `price ${Format.formatPrice6(batchCollision.order.price)}. ` +
3172
+ `price ${Format.formatPrice6(Number(batchCollision.order?.price ?? batchCollision.price))}. ` +
3143
3173
  `The next reconcile cycle will resolve the mismatch.`, 'warn');
3144
3174
  if (order.id)
3145
3175
  skippedCreateSlotIds.add(order.id);
@@ -3182,7 +3212,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3182
3212
  if (check.blocked) {
3183
3213
  lastFillGuardStats.skipped++;
3184
3214
  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');
3215
+ 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
3216
  if (order.id)
3187
3217
  skippedCreateSlotIds.add(order.id);
3188
3218
  continue;
@@ -3454,7 +3484,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3454
3484
  if (action.newGridId)
3455
3485
  skippedUpdateSlotIds.add(action.newGridId);
3456
3486
  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');
3487
+ 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
3488
  continue;
3459
3489
  }
3460
3490
  lastFillGuardStats.passed++;
@@ -3562,14 +3592,14 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3562
3592
  if (fbCollision) {
3563
3593
  bot.manager.logger.log(`[COW] Skipping CREATE fallback for ${targetSlotId} at ${Format.formatPrice6(fbPrice)}: ` +
3564
3594
  `existing placed order ${fbCollision.id} (${fbCollision.orderId}) ` +
3565
- `already at price ${Format.formatPrice6(fbCollision.price)}.`, 'warn');
3595
+ `already at price ${Format.formatPrice6(Number(fbCollision.price))}.`, 'warn');
3566
3596
  continue;
3567
3597
  }
3568
3598
  const fbBatchCollision = hasSlotPriceCollision(opContexts, fbPrice, fbPrecision, targetSlotId, (ctx) => ctx.kind === 'create');
3569
3599
  if (fbBatchCollision) {
3570
3600
  bot.manager.logger.log(`[COW] Skipping CREATE fallback for ${targetSlotId} at ${Format.formatPrice6(fbPrice)}: ` +
3571
3601
  `same-batch CREATE ${fbBatchCollision.id} already at ` +
3572
- `price ${Format.formatPrice6(fbBatchCollision.order.price)}.`, 'warn');
3602
+ `price ${Format.formatPrice6(Number(fbBatchCollision.order?.price ?? fbBatchCollision.price))}.`, 'warn');
3573
3603
  continue;
3574
3604
  }
3575
3605
  // CROSSING-PLACEMENT GUARD (fallback variant):
@@ -3599,8 +3629,8 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3599
3629
  const fbDir = fbType === ORDER_TYPES.BUY ? 'above' : 'below';
3600
3630
  bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping CREATE fallback for ${targetSlotId} at ` +
3601
3631
  `${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');
3632
+ `${Format.formatPrice6(Number(fbCheck.pivot))} (halfInc ${fbCheck.halfInc}% thr ` +
3633
+ `${Format.formatPrice6(Number(fbCheck.threshold))}); re-planned after market moves`, 'debug');
3604
3634
  continue;
3605
3635
  }
3606
3636
  lastFillGuardStats.passed++;
@@ -3701,7 +3731,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3701
3731
  ? cctx?.order?.orderId || cctx?.orderId
3702
3732
  : cord?.orderId;
3703
3733
  if (cOrderId)
3704
- cancelOpIndexByOrderId.set(cOrderId, ci);
3734
+ cancelOpIndexByOrderId.set(String(cOrderId), ci);
3705
3735
  }
3706
3736
  // skippedUpdateCount is threaded via countRef so the restore
3707
3737
  // below covers gate-dropped rotations too.
@@ -3785,7 +3815,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3785
3815
  ? Number(bot.manager._gridVersion)
3786
3816
  : undefined;
3787
3817
  for (const slotId of clampedUpdateSlotIds) {
3788
- workingGrid.syncFromMaster(bot.manager.orders, slotId, masterVersion);
3818
+ workingGrid.syncFromMaster(bot.manager.orders, String(slotId), masterVersion);
3789
3819
  }
3790
3820
  bot.manager.logger.log(`[COW] Re-synced ${clampedUpdateSlotIds.size} post-fill-clamped slot(s) from master before commit`, 'debug');
3791
3821
  }
@@ -3862,7 +3892,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3862
3892
  // Bounded re-plan + proceed — policy documented on replanStaleBatch.
3863
3893
  const replan = await replanStaleBatch(bot, cowResult, replanDepth, preBroadcastGuard, seamPollIntervalMs);
3864
3894
  if (replan.handled) {
3865
- return replan.result;
3895
+ return replan.result ?? { executed: false, hadRotation: false };
3866
3896
  }
3867
3897
  // Fall through: proceed with the current plan (bounded policy).
3868
3898
  }
@@ -3908,7 +3938,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3908
3938
  heldBroadcastSlot = false;
3909
3939
  const replan = await replanStaleBatch(bot, cowResult, replanDepth, postWaitGuard, seamPollIntervalMs);
3910
3940
  if (replan.handled) {
3911
- return replan.result;
3941
+ return replan.result ?? { executed: false, hadRotation: false };
3912
3942
  }
3913
3943
  // No fill context for a re-plan (or the re-plan limit was
3914
3944
  // reached). The stale policy proceeds with the original plan, so
@@ -3958,17 +3988,17 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3958
3988
  let adoptedCount = 0;
3959
3989
  let normalizedCount = 0;
3960
3990
  for (const item of missingCreateResults) {
3961
- const slotId = item.ctx?.order?.id || item.ctx?.id;
3991
+ const slotId = String(item.ctx?.order?.id ?? item.ctx?.id ?? '');
3962
3992
  const slot = workingGrid.get(slotId);
3963
3993
  if (!slot)
3964
3994
  continue;
3965
3995
  const isConfirmed = confirmation.confirmed.some((c) => (c?.order?.id || c?.id) === slotId);
3966
3996
  if (isConfirmed && chainSnap) {
3967
- const match = findChainOrderForSlot(bot, chainSnap, slotId, {
3997
+ const match = findChainOrderForSlot(bot, chainSnap, String(slotId), {
3968
3998
  sell: item.ctx?.finalInts?.sell,
3969
3999
  receive: item.ctx?.finalInts?.receive,
3970
4000
  orderType: item.ctx?.order?.type,
3971
- fingerprint: createOpFingerprintForSlot(bot, item.ctx?.order, item.ctx?.finalInts, slotId)
4001
+ fingerprint: createOpFingerprintForSlot(bot, item.ctx?.order, item.ctx?.finalInts, String(slotId))
3972
4002
  });
3973
4003
  if (match?.id) {
3974
4004
  workingGrid.set(slotId, { ...slot, orderId: match.id });
@@ -4067,7 +4097,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4067
4097
  }
4068
4098
  catch (err) {
4069
4099
  bot.manager.logger.log(`[COW] Batch transaction failed: ${getErrorMessage(err)}`, 'error');
4070
- if (err?.partialOnChainState) {
4100
+ if (getErrorField(err, 'partialOnChainState')) {
4071
4101
  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
4102
  }
4073
4103
  bot.manager.stopBroadcasting();
@@ -4077,7 +4107,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4077
4107
  // and we can commit the working grid directly, bypassing the expensive
4078
4108
  // reconciliation state machine. This handles the ~90% case where the
4079
4109
  // chain accepted the transaction but the response was lost.
4080
- if (err instanceof BroadcastUncertainError && err.partialOnChainState !== true) {
4110
+ if (err instanceof BroadcastUncertainError && getErrorField(err, 'partialOnChainState') !== true) {
4081
4111
  try {
4082
4112
  const confirmation = await pollChainForConfirmation(bot, opContexts);
4083
4113
  if (confirmation.allConfirmed) {
@@ -4225,12 +4255,12 @@ async function requestStructuralResync(bot, reason, details = {}) {
4225
4255
  * freshest orders are dropped — so it MUST NOT drive adoption; we return false
4226
4256
  * and let the caller keep pending-broadcast protection + structural resync.
4227
4257
  *
4228
- * @param {any} bot
4229
- * @param {any} chainOrders - chain_orders module (has readOpenOrdersWithMetaSafe + batchReadOrders)
4258
+ * @param {unknown} bot
4259
+ * @param {unknown} chainOrders - chain_orders module (has readOpenOrdersWithMetaSafe + batchReadOrders)
4230
4260
  * @param {string} logPrefix
4231
4261
  * @param {Object} [opts]
4232
- * @param {any} [opts.placedResults] - broadcast result carrying operation_results
4233
- * @param {any[]} [opts.placedContexts] - opContexts aligned with operation_results
4262
+ * @param {unknown} [opts.placedResults] - broadcast result carrying operation_results
4263
+ * @param {unknown[]} [opts.placedContexts] - opContexts aligned with operation_results
4234
4264
  * @param {string[]} [opts.polledCreateIds] - fresh CREATE chain ids confirmed by
4235
4265
  * the uncertain-broadcast poll (no broadcast result exists on that path);
4236
4266
  * routes the poll call sites through the by-id path with its lagging-create
@@ -4247,7 +4277,7 @@ async function requestStructuralResync(bot, reason, details = {}) {
4247
4277
  * post-fill rotation immediately (no re-broadcast), so the next placement lands
4248
4278
  * at the shifted slot, never at x.
4249
4279
  *
4250
- * @param {any} bot
4280
+ * @param {unknown} bot
4251
4281
  * @param {number} workingBoundary - boundary index the refused batch targeted
4252
4282
  */
4253
4283
  async function restoreBoundaryAfterAdoption(bot, workingBoundary) {
@@ -4419,7 +4449,11 @@ async function persistGridAndClearPendingBroadcasts(bot, logPrefix) {
4419
4449
  * @returns {Promise<Object>} The commit-refused return object
4420
4450
  */
4421
4451
  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;
4452
+ const extraReturn = (opts.extraReturn ?? {});
4453
+ const successReturn = opts.successReturn;
4454
+ const failureResyncReason = (opts.failureResyncReason ?? 'commit refused after broadcast (chain adoption unavailable)');
4455
+ const failureLogMessage = (opts.failureLogMessage ?? 'Commit refused and chain adoption unavailable; keeping pending-broadcast protection pending structural resync');
4456
+ const preAdoptLogMessage = opts.preAdoptLogMessage;
4423
4457
  if (preAdoptLogMessage) {
4424
4458
  bot.manager.logger.log(`${logPrefix} ${preAdoptLogMessage}`, 'warn');
4425
4459
  }
@@ -4449,7 +4483,7 @@ async function recoverRefusedCommit(bot, chainOrders, logPrefix, adoptOpts, cont
4449
4483
  * startup), so the guard degrades to its previous behaviour rather than
4450
4484
  * silently disabling. Never throws.
4451
4485
  *
4452
- * @param {any} manager
4486
+ * @param {unknown} manager
4453
4487
  * @param {number|null|undefined} rawPrice
4454
4488
  * @returns {{price: number|null, snapped: boolean, idx: number|null, nearestDrift: number|null}}
4455
4489
  */
@@ -4460,7 +4494,7 @@ function resolveOnGridPivot(manager, rawPrice) {
4460
4494
  try {
4461
4495
  const genesis = manager?._genesis;
4462
4496
  const levels = genesis?.priceLevels;
4463
- if (!Array.isArray(levels) || levels.length === 0)
4497
+ if (!genesis || !Array.isArray(levels) || levels.length === 0)
4464
4498
  return { price, snapped: false, idx: null, nearestDrift: null };
4465
4499
  const idx = math.slotIndexForPrice(price, genesis);
4466
4500
  if (!Number.isFinite(idx))
@@ -4640,9 +4674,9 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4640
4674
  try {
4641
4675
  if (!Array.isArray(operations) || !Array.isArray(opContexts) || operations.length === 0)
4642
4676
  return empty;
4643
- const stats = opts?.lastFillGuardStats;
4677
+ const stats = opts.lastFillGuardStats;
4644
4678
  const frozenPivot = Number(opts?.frozenPivot);
4645
- const frozenType = opts?.frozenType;
4679
+ const frozenType = opts.frozenType;
4646
4680
  const frozenCold = !Number.isFinite(frozenPivot) || frozenType == null;
4647
4681
  const queueDepthBefore = Array.isArray(bot?._incomingFillQueue)
4648
4682
  ? bot._incomingFillQueue.length
@@ -4684,8 +4718,8 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4684
4718
  return { ...empty, refreshed };
4685
4719
  // Pivot moved (or armed mid-batch): re-check every built op's FINAL
4686
4720
  // 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;
4721
+ const actions = (Array.isArray(opts.actions) ? opts.actions : []);
4722
+ const batchOrigin = opts.cowResult?.origin;
4689
4723
  const actionBySlot = new Map();
4690
4724
  for (const a of actions) {
4691
4725
  if (!a)
@@ -4727,7 +4761,7 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4727
4761
  }
4728
4762
  }
4729
4763
  else if (ctx.kind === 'rotation') {
4730
- const rot = ctx.rotation || {};
4764
+ const rot = (ctx.rotation || {});
4731
4765
  slotId = rot.newGridId || rot.oldOrder?.id || null;
4732
4766
  price = Number(rot.newPrice);
4733
4767
  type = rot.type || null;
@@ -4805,8 +4839,8 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4805
4839
  dropped.push({ index: i, kind: ctx.kind, slotId, price, type });
4806
4840
  try {
4807
4841
  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');
4842
+ `${Format.formatPrice6(price)}: ${dir} last filled ${check.pivot != null ? Format.formatPrice6(Number(check.pivot)) : 'n/a'} ` +
4843
+ `(halfInc ${check.halfInc}% thr ${check.threshold != null ? Format.formatPrice6(Number(check.threshold)) : 'n/a'}); re-planned after market moves`, 'warn');
4810
4844
  }
4811
4845
  catch { /* logging is best-effort */ }
4812
4846
  }
@@ -4845,25 +4879,25 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4845
4879
  // drop: undefined at best, a DIFFERENT create's context at worst,
4846
4880
  // which would let the uncertain-broadcast reconcile adopt a matched
4847
4881
  // chain order into the wrong slot).
4848
- const skippedUpdateSlotIds = opts?.skippedUpdateSlotIds;
4849
- const skippedCreateSlotIds = opts?.skippedCreateSlotIds;
4850
- const countRef = opts?.skippedUpdateCountRef;
4882
+ const skippedUpdateSlotIds = opts.skippedUpdateSlotIds;
4883
+ const skippedCreateSlotIds = opts.skippedCreateSlotIds;
4884
+ const countRef = opts.skippedUpdateCountRef;
4851
4885
  try {
4852
4886
  const pending = bot.manager?._pendingBroadcasts;
4853
4887
  for (const d of dropped) {
4854
4888
  if (d.kind === 'rotation') {
4855
- const act = (d.slotId && actionBySlot.get(d.slotId)) || null;
4889
+ const act = d.slotId ? (actionBySlot.get(String(d.slotId)) ?? null) : null;
4856
4890
  const srcId = act?.id || null;
4857
4891
  if (srcId && skippedUpdateSlotIds instanceof Set)
4858
4892
  skippedUpdateSlotIds.add(srcId);
4859
4893
  if (d.slotId && skippedUpdateSlotIds instanceof Set)
4860
- skippedUpdateSlotIds.add(d.slotId);
4894
+ skippedUpdateSlotIds.add(String(d.slotId));
4861
4895
  if (countRef && typeof countRef === 'object')
4862
4896
  countRef.count = (Number(countRef.count) || 0) + 1;
4863
4897
  }
4864
4898
  else if (d.kind === 'create') {
4865
4899
  if (d.slotId && skippedCreateSlotIds instanceof Set)
4866
- skippedCreateSlotIds.add(d.slotId);
4900
+ skippedCreateSlotIds.add(String(d.slotId));
4867
4901
  if (pending instanceof Map) {
4868
4902
  for (const [fp, entry] of pending) {
4869
4903
  // Match by slot only: the fingerprint embeds
@@ -4937,21 +4971,24 @@ async function applyAdoptionFeeAccounting(bot, contexts) {
4937
4971
  : null;
4938
4972
  for (const ctx of contexts) {
4939
4973
  if (ctx?.kind === 'create') {
4940
- const slot = ctx.order?.id ? bot.manager.orders.get(ctx.order.id) : null;
4974
+ const order = ctx.order;
4975
+ if (!order)
4976
+ continue;
4977
+ const slot = order.id ? bot.manager.orders.get(order.id) : null;
4941
4978
  if (!slot?.orderId)
4942
4979
  continue;
4943
4980
  try {
4944
4981
  await bot.manager.synchronizeWithChain({
4945
- gridOrderId: ctx.order.id,
4982
+ gridOrderId: order.id,
4946
4983
  chainOrderId: slot.orderId,
4947
4984
  isPartialPlacement: false,
4948
- expectedType: ctx.order.type,
4985
+ expectedType: order.type,
4949
4986
  fee: btsFeeData?.createFee || 0,
4950
- order: ctx.order ?? null,
4987
+ order: order,
4951
4988
  }, 'createOrder');
4952
4989
  }
4953
4990
  catch (feeErr) {
4954
- bot.manager.logger.log(`[COW] Adoption fee accounting failed for create slot ${ctx.order.id}: ${getErrorMessage(feeErr)}`, 'warn');
4991
+ bot.manager.logger.log(`[COW] Adoption fee accounting failed for create slot ${order.id}: ${getErrorMessage(feeErr)}`, 'warn');
4955
4992
  }
4956
4993
  }
4957
4994
  else if (ctx?.kind === 'cancel') {
@@ -4962,9 +4999,9 @@ async function applyAdoptionFeeAccounting(bot, contexts) {
4962
4999
  // the on-chain cost exactly once (mirrors the sync's
4963
5000
  // 'cancel-order-unmatched-fee' pattern; the deferred-fee refund is
4964
5001
  // reconciled by the next sync's fill/cancel processing).
4965
- if (btsSide && btsFeeData?.cancelFee > 0) {
5002
+ if (btsSide && btsFeeData && (btsFeeData.cancelFee ?? 0) > 0) {
4966
5003
  try {
4967
- await bot.manager.accountant.adjustTotalBalance(btsSide, -btsFeeData.cancelFee, 'cancel-adopt-fee');
5004
+ await bot.manager.accountant.adjustTotalBalance(btsSide, -(btsFeeData.cancelFee ?? 0), 'cancel-adopt-fee');
4968
5005
  }
4969
5006
  catch (feeErr) {
4970
5007
  bot.manager.logger.log(`[COW] Adoption fee accounting failed for cancel ${ctx.order?.orderId}: ${getErrorMessage(feeErr)}`, 'warn');
@@ -4976,9 +5013,9 @@ async function applyAdoptionFeeAccounting(bot, contexts) {
4976
5013
  // charged on this path; the next sync's size reconciliation applies
4977
5014
  // the chain state without an update fee (fee 0), so charge it once
4978
5015
  // here to prevent optimistic BTS drift.
4979
- if (btsSide && btsFeeData?.updateFee > 0) {
5016
+ if (btsSide && btsFeeData && (btsFeeData.updateFee ?? 0) > 0) {
4980
5017
  try {
4981
- await bot.manager.accountant.adjustTotalBalance(btsSide, -btsFeeData.updateFee, 'update-adopt-fee');
5018
+ await bot.manager.accountant.adjustTotalBalance(btsSide, -(btsFeeData.updateFee ?? 0), 'update-adopt-fee');
4982
5019
  }
4983
5020
  catch (feeErr) {
4984
5021
  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 +5063,37 @@ async function processBatchResults(bot, result, opContexts) {
5026
5063
  for (let i = 0; i < opContexts.length; i++) {
5027
5064
  const ctx = opContexts[i];
5028
5065
  const res = results[i];
5066
+ const ctxOrder = ctx.order;
5067
+ const ctxUpdateInfo = ctx.updateInfo;
5029
5068
  if (ctx.kind === 'cancel') {
5030
- bot.manager.logger.log(`Cancelled surplus order ${ctx.order.id} (${ctx.order.orderId})`, 'info');
5031
- const oldOrder = ctx.order;
5069
+ bot.manager.logger.log(`Cancelled surplus order ${ctxOrder.id} (${ctxOrder.orderId})`, 'info');
5070
+ const oldOrder = ctxOrder;
5032
5071
  const committedOrder = oldOrder?.id ? bot.manager.orders.get(oldOrder.id) : null;
5033
5072
  await applyOptimisticFeeBalance(bot, oldOrder, committedOrder, 'fill-cancel', btsFeeData?.cancelFee || 0);
5034
5073
  }
5035
5074
  else if (ctx.kind === 'size-update') {
5036
- const oldOrder = ctx.updateInfo.partialOrder;
5037
- const ord = bot.manager.orders.get(oldOrder.id);
5075
+ const oldOrder = ctxUpdateInfo.partialOrder;
5076
+ const ord = bot.manager.orders.get(String(oldOrder.id));
5038
5077
  await applyOptimisticFeeBalance(bot, oldOrder, ord, 'order-update', btsFeeData?.updateFee || 0);
5039
5078
  if (ord) {
5040
- const updatedSlot = { ...ord, size: ctx.updateInfo.newSize };
5079
+ const updatedSlot = { ...ord, size: Number(ctxUpdateInfo.newSize) };
5041
5080
  if (ctx.finalInts) {
5042
5081
  updatedSlot.rawOnChain = rawOnChainFromInts(ord.orderId, ctx.finalInts);
5043
5082
  }
5044
5083
  updatesToApply.push({ order: updatedSlot, context: 'post-update-metadata' });
5045
5084
  }
5046
- bot.manager.logger.log(`Size update complete: ${ctx.updateInfo.partialOrder.orderId}`, 'info');
5085
+ bot.manager.logger.log(`Size update complete: ${ctxUpdateInfo.partialOrder.orderId}`, 'info');
5047
5086
  updateOperationCount++;
5048
5087
  }
5049
5088
  else if (ctx.kind === 'create') {
5050
5089
  const chainOrderId = res && res[1];
5051
5090
  if (chainOrderId) {
5052
5091
  await bot.manager.synchronizeWithChain({
5053
- gridOrderId: ctx.order.id, chainOrderId, expectedType: ctx.order.type, fee: btsFeeData?.createFee || 0,
5054
- order: ctx.order ?? null,
5092
+ gridOrderId: ctxOrder.id, chainOrderId, expectedType: ctxOrder.type, fee: btsFeeData?.createFee || 0,
5093
+ order: ctxOrder ?? null,
5055
5094
  }, 'createOrder');
5056
5095
  if (ctx.finalInts) {
5057
- const syncedOrder = bot.manager.orders.get(ctx.order.id);
5096
+ const syncedOrder = bot.manager.orders.get(ctxOrder.id);
5058
5097
  if (syncedOrder) {
5059
5098
  updatesToApply.push({
5060
5099
  order: {
@@ -5068,27 +5107,31 @@ async function processBatchResults(bot, result, opContexts) {
5068
5107
  // Success line mirrors the failure-path fingerprint below
5069
5108
  // (type/price/size) so both are greppable by the same keys —
5070
5109
  // 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)} ` +
5110
+ bot.manager.logger.log(`Placed ${ctxOrder.type} order ${ctxOrder.id} ` +
5111
+ `@${Format.formatPrice6(ctxOrder.price)} x${Format.formatAmount(ctxOrder.size)} ` +
5073
5112
  `-> ${chainOrderId}`, 'info');
5074
5113
  }
5075
5114
  else {
5076
5115
  const fingerprint = [
5077
- `type=${ctx.order.type || 'unknown'}`,
5078
- `price=${Format.formatPrice6(ctx.order.price)}`,
5079
- `size=${Format.formatAmount(ctx.order.size)}`
5116
+ `type=${ctxOrder.type || 'unknown'}`,
5117
+ `price=${Format.formatPrice6(ctxOrder.price)}`,
5118
+ `size=${Format.formatAmount(ctxOrder.size)}`
5080
5119
  ].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 ` +
5120
+ bot.manager.logger.log(`[COW] CRITICAL: Create op for slot ${ctxOrder.id} (type=${ctxOrder.type}) ` +
5121
+ `returned no chainOrderId. Identify orphaned on-chain orders by local fingerprint ` +
5083
5122
  `${fingerprint} before cancelling.`, 'error');
5084
5123
  }
5085
5124
  }
5086
5125
  else if (ctx.kind === 'rotation') {
5087
5126
  hadRotation = true;
5088
- const { rotation } = ctx;
5089
- const { oldOrder, newPrice, newGridId, newSize, type } = rotation;
5127
+ const rotation = (ctx.rotation ?? {});
5128
+ const oldOrder = rotation.oldOrder;
5129
+ const newPrice = rotation.newPrice;
5130
+ const newGridId = rotation.newGridId;
5131
+ const newSize = rotation.newSize;
5132
+ const type = rotation.type;
5090
5133
  if (!newGridId) {
5091
- const ord = bot.manager.orders.get(oldOrder.id || rotation.id);
5134
+ const ord = bot.manager.orders.get(String(oldOrder?.id || rotation.id));
5092
5135
  await applyOptimisticFeeBalance(bot, oldOrder, ord, 'order-update', btsFeeData?.updateFee || 0);
5093
5136
  if (ord) {
5094
5137
  const updatedSlot = { ...ord, size: newSize };
@@ -5104,7 +5147,7 @@ async function processBatchResults(bot, result, opContexts) {
5104
5147
  if (!slot) {
5105
5148
  bot.manager.logger.log(`[ROTATION] Destination slot ${newGridId} missing from master grid after COW commit - skipping activation, sync will reconcile`, 'error');
5106
5149
  if (oldOrder?.id && oldOrder.id !== newGridId) {
5107
- const staleSource = bot.manager.orders.get(oldOrder.id);
5150
+ const staleSource = bot.manager.orders.get(String(oldOrder.id));
5108
5151
  if (staleSource?.orderId) {
5109
5152
  updatesToApply.push({
5110
5153
  order: { ...staleSource, state: ORDER_STATES.VIRTUAL, orderId: null, rawOnChain: null },
@@ -5128,7 +5171,7 @@ async function processBatchResults(bot, result, opContexts) {
5128
5171
  }
5129
5172
  await applyOptimisticFeeBalance(bot, oldOrder, updatedSlot, 'order-update', btsFeeData?.updateFee || 0);
5130
5173
  if (oldOrder?.id && oldOrder.id !== newGridId) {
5131
- const currentSource = bot.manager.orders.get(oldOrder.id);
5174
+ const currentSource = bot.manager.orders.get(String(oldOrder.id));
5132
5175
  if (currentSource && currentSource.orderId) {
5133
5176
  updatesToApply.push({
5134
5177
  order: {
@@ -5153,7 +5196,7 @@ async function processBatchResults(bot, result, opContexts) {
5153
5196
  updateOperationCount
5154
5197
  };
5155
5198
  }
5156
- export { isLastFillGuardBlocked, resolveOnGridPivot, checkGridPriceInvariant, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast, reconcileAfterUncertainBroadcastImpl, executeWithRetryOnUncertain, executeChunkedWithRetryOnUncertain, formatPartialBroadcastSummary, executeOperationsWithStrategy, buildActionsFromPlan, buildCowResultFromPlan, applyRotationTransitionsToWorkingGrid, pollChainForConfirmation, updateOrdersOnChainBatchCOW, processBatchResults, adoptPlacedBatchFromChain, resolveRefillBoundaryHold, toRefillSlotIdSet, trackBoundaryHold };
5199
+ 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
5200
  // Exported for regression tests (issue #23 sibling): the uncertain-broadcast
5158
5201
  // discard path must never drop a placement silently when master lost the slot.
5159
5202
  export { restoreDiscardedCreates };
@@ -5177,7 +5220,6 @@ export default {
5177
5220
  executeWithRetryOnUncertain,
5178
5221
  executeChunkedWithRetryOnUncertain,
5179
5222
  formatPartialBroadcastSummary,
5180
- executeOperationsWithStrategy,
5181
5223
  validateOperationFunds,
5182
5224
  resolveIdealSizeForValidation,
5183
5225
  validateOrderSizeForExecution,