dexbot 1.6.6 → 1.6.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (632) hide show
  1. package/CHANGELOG.md +89 -1
  2. package/README.md +8 -5
  3. package/analysis/README.md +2 -3
  4. package/analysis/tradingview/README.md +78 -1
  5. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/tradingview/analyze_tradingview.d.ts +4 -0
  10. package/dist/analysis/tradingview/analyze_tradingview.js +55 -0
  11. package/dist/analysis/tradingview/grid_reset_config.d.ts +61 -0
  12. package/dist/analysis/tradingview/grid_reset_config.js +235 -0
  13. package/dist/analysis/tradingview/grid_reset_sim.d.ts +67 -0
  14. package/dist/analysis/tradingview/grid_reset_sim.js +307 -0
  15. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +419 -3
  16. package/dist/dexbot.js +44 -15
  17. package/dist/market_adapter/core/market_adapter_service.js +14 -2
  18. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +8 -1
  19. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +5 -1
  20. package/dist/market_adapter/inputs/window_cache.d.ts +97 -19
  21. package/dist/market_adapter/inputs/window_cache.js +302 -48
  22. package/dist/market_adapter/market_adapter.d.ts +8 -1
  23. package/dist/market_adapter/market_adapter.js +22 -4
  24. package/dist/modules/account_bots.js +20 -9
  25. package/dist/modules/account_orders.d.ts +44 -4
  26. package/dist/modules/account_orders.js +104 -7
  27. package/dist/modules/bitshares-native/chain_client.d.ts +10 -0
  28. package/dist/modules/bitshares-native/chain_client.js +197 -28
  29. package/dist/modules/bitshares-native/subscriptions.js +312 -10
  30. package/dist/modules/bitshares-native/transport.d.ts +1 -0
  31. package/dist/modules/bitshares-native/transport.js +97 -3
  32. package/dist/modules/bitshares_client.d.ts +20 -0
  33. package/dist/modules/bitshares_client.js +29 -0
  34. package/dist/modules/bot_settings.js +10 -1
  35. package/dist/modules/chain_keys.d.ts +37 -22
  36. package/dist/modules/chain_keys.js +145 -44
  37. package/dist/modules/cli_start_onboarding.d.ts +10 -0
  38. package/dist/modules/cli_start_onboarding.js +15 -0
  39. package/dist/modules/cli_start_output.d.ts +6 -0
  40. package/dist/modules/cli_start_output.js +8 -0
  41. package/dist/modules/config.d.ts +1 -0
  42. package/dist/modules/config.js +1 -0
  43. package/dist/modules/constants.d.ts +23 -2
  44. package/dist/modules/constants.js +196 -15
  45. package/dist/modules/dexbot_class.d.ts +6 -76
  46. package/dist/modules/dexbot_class.js +0 -32
  47. package/dist/modules/dexbot_cow_runtime.d.ts +3 -58
  48. package/dist/modules/dexbot_cow_runtime.js +53 -96
  49. package/dist/modules/dexbot_fill_runtime.d.ts +6 -1
  50. package/dist/modules/dexbot_fill_runtime.js +22 -3
  51. package/dist/modules/dexbot_maintenance_runtime.d.ts +38 -1
  52. package/dist/modules/dexbot_maintenance_runtime.js +103 -11
  53. package/dist/modules/dexbot_startup_runtime.js +73 -20
  54. package/dist/modules/dexbot_state_recovery.d.ts +6 -0
  55. package/dist/modules/dexbot_state_recovery.js +34 -1
  56. package/dist/modules/order/async_lock.d.ts +8 -0
  57. package/dist/modules/order/async_lock.js +15 -0
  58. package/dist/modules/order/genesis_policy.d.ts +162 -0
  59. package/dist/modules/order/genesis_policy.js +267 -0
  60. package/dist/modules/order/grid.js +109 -135
  61. package/dist/modules/order/grid_reconcile.d.ts +9 -0
  62. package/dist/modules/order/grid_reconcile.js +13 -4
  63. package/dist/modules/order/grid_reconcile_internal.js +13 -2
  64. package/dist/modules/order/logger.d.ts +12 -2
  65. package/dist/modules/order/logger.js +29 -7
  66. package/dist/modules/order/manager.d.ts +53 -0
  67. package/dist/modules/order/manager.js +86 -25
  68. package/dist/modules/order/sync_engine.d.ts +19 -0
  69. package/dist/modules/order/sync_engine.js +284 -344
  70. package/dist/modules/order/utils/math.d.ts +22 -1
  71. package/dist/modules/order/utils/math.js +64 -1
  72. package/dist/modules/order/utils/order.d.ts +43 -58
  73. package/dist/modules/order/utils/order.js +302 -194
  74. package/dist/modules/order/utils/system.d.ts +97 -0
  75. package/dist/modules/order/utils/system.js +282 -3
  76. package/dist/modules/paths.d.ts +8 -1
  77. package/dist/modules/paths.js +11 -3
  78. package/dist/modules/utils/text_width.d.ts +19 -0
  79. package/dist/modules/utils/text_width.js +97 -0
  80. package/dist/modules/version_notice.d.ts +165 -0
  81. package/dist/modules/version_notice.js +364 -0
  82. package/dist/pm2.js +104 -18
  83. package/dist/scripts/update.js +62 -13
  84. package/dist/unlock.d.ts +14 -2
  85. package/dist/unlock.js +101 -4
  86. package/docs/BITSHARES_ONBOARDING.md +8 -1
  87. package/docs/COW_INVARIANTS.md +11 -2
  88. package/docs/CREDENTIAL_SECURITY.md +26 -0
  89. package/docs/DEXBOT_COMPARISON.md +4 -4
  90. package/docs/EVOLUTION.md +20 -18
  91. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  92. package/docs/GRID_PRICE_INVARIANT.md +204 -31
  93. package/docs/GRID_RECALCULATION.md +12 -0
  94. package/docs/LOGGING.md +17 -2
  95. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +6 -7
  96. package/docs/README.md +3 -1
  97. package/docs/WORKFLOW.md +16 -5
  98. package/market_adapter/README.md +1 -1
  99. package/modules/README.md +18 -1
  100. package/package.json +14 -6
  101. package/scripts/README.md +28 -2
  102. package/scripts/clear-all.sh +13 -4
  103. package/scripts/clear-logs.sh +13 -4
  104. package/scripts/clear-market-adapter.sh +6 -0
  105. package/scripts/clear-orders.sh +5 -0
  106. package/scripts/lib/dexbot-paths.sh +108 -0
  107. package/tests/README.md +11 -3
  108. package/analysis/account_resolver.ts +0 -161
  109. package/analysis/ama_fitting/analyze_ama_price_changes.ts +0 -155
  110. package/analysis/ama_fitting/analyze_lambda_vs_slow.ts +0 -404
  111. package/analysis/ama_fitting/calibrate_convergence_er.ts +0 -201
  112. package/analysis/ama_fitting/fetch_lp_candles.ts +0 -184
  113. package/analysis/ama_fitting/generate_unified_comparison_chart.ts +0 -232
  114. package/analysis/ama_fitting/optimizer_high_resolution.ts +0 -802
  115. package/analysis/analyze_dynamic_weight.ts +0 -243
  116. package/analysis/analyze_kalman.ts +0 -157
  117. package/analysis/analyze_regime.ts +0 -158
  118. package/analysis/analyze_regime_windows.ts +0 -470
  119. package/analysis/analyze_risk_profile.ts +0 -199
  120. package/analysis/analyze_trade_heatmap.ts +0 -362
  121. package/analysis/analyze_volatility.ts +0 -182
  122. package/analysis/bot_fitting/backtest_ama_sweep.ts +0 -934
  123. package/analysis/bot_fitting/backtest_bot_fitting.ts +0 -861
  124. package/analysis/bot_fitting/shared_utils.ts +0 -52
  125. package/analysis/bot_key_utils.ts +0 -426
  126. package/analysis/bot_usage/discover_bot_accounts.ts +0 -635
  127. package/analysis/bot_usage/kibana_bot_queries.ts +0 -211
  128. package/analysis/chain_pool.ts +0 -47
  129. package/analysis/chart_css.ts +0 -62
  130. package/analysis/chart_ui.ts +0 -105
  131. package/analysis/chart_utils.ts +0 -210
  132. package/analysis/fills_source.ts +0 -228
  133. package/analysis/grid_correction_check.ts +0 -786
  134. package/analysis/math_utils.ts +0 -53
  135. package/analysis/price_sources.ts +0 -136
  136. package/analysis/resolve_bot_accounts.ts +0 -199
  137. package/analysis/resolve_source.ts +0 -99
  138. package/analysis/results/ama_sweep_results_lp_pool_133_1h.json +0 -2455
  139. package/analysis/results/bot_fitting_results_lp_pool_133_1h.json +0 -218
  140. package/analysis/trade_profitability.ts +0 -1335
  141. package/analysis/tradingview/analyze_tradingview.ts +0 -280
  142. package/analysis/tradingview/h-bts_tradingview.html +0 -1570
  143. package/analysis/tradingview/t-bts_tradingview.html +0 -1570
  144. package/analysis/tradingview/tradingview_uplot_chart_generator.ts +0 -3268
  145. package/analysis/trend_detection/dynamic_weight_chart_generator.ts +0 -1481
  146. package/analysis/trend_detection/hurst_analyzer.ts +0 -7
  147. package/analysis/trend_detection/kalman_chart_generator.ts +0 -398
  148. package/analysis/trend_detection/kalman_trend_analyzer.ts +0 -9
  149. package/analysis/trend_detection/kalman_velocity_smoothing.ts +0 -7
  150. package/analysis/trend_detection/package.json +0 -23
  151. package/analysis/trend_detection/permutation_entropy_analyzer.ts +0 -7
  152. package/analysis/trend_detection/regime_chart_generator.ts +0 -338
  153. package/analysis/trend_detection/tests/test_kalman_trend.ts +0 -153
  154. package/analysis/trend_detection/tests/test_kalman_velocity_smoothing.ts +0 -64
  155. package/analysis/trend_detection/volatility_chart_generator.ts +0 -654
  156. package/analysis/tsconfig.json +0 -29
  157. package/claw/tests/package.json +0 -3
  158. package/claw/tests/test_claw_bridge.ts +0 -570
  159. package/claw/tests/test_claw_catalog_and_credentials.ts +0 -156
  160. package/claw/tests/test_claw_chain_layer.ts +0 -739
  161. package/claw/tests/test_claw_data_flow.ts +0 -525
  162. package/claw/tests/test_claw_domain_logic.ts +0 -471
  163. package/claw/tests/test_claw_manifest_and_matrix.ts +0 -222
  164. package/claw/tests/test_claw_mcp_transport.ts +0 -243
  165. package/claw/tests/test_claw_regressions.ts +0 -711
  166. package/claw/tests/test_claw_skill_generation.ts +0 -103
  167. package/claw/tests/test_claw_state_store.ts +0 -44
  168. package/claw/tests/test_dexbot_profiles.ts +0 -654
  169. package/claw/tests/test_memu_bridge.ts +0 -189
  170. package/claw/tests/test_nullclaw_tmp_integration.ts +0 -57
  171. package/claw/tests/test_position_health.ts +0 -343
  172. package/claw/tests/test_position_manager.ts +0 -429
  173. package/claw/tests/test_position_manager_watch_health.ts +0 -100
  174. package/claw/tests/test_short_mpa_strategy.ts +0 -232
  175. package/dist/analysis/account_resolver.d.ts.map +0 -1
  176. package/dist/analysis/account_resolver.js.map +0 -1
  177. package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts.map +0 -1
  178. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js.map +0 -1
  179. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts.map +0 -1
  180. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +0 -1
  181. package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts.map +0 -1
  182. package/dist/analysis/ama_fitting/calibrate_convergence_er.js.map +0 -1
  183. package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts.map +0 -1
  184. package/dist/analysis/ama_fitting/fetch_lp_candles.js.map +0 -1
  185. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts.map +0 -1
  186. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js.map +0 -1
  187. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts.map +0 -1
  188. package/dist/analysis/ama_fitting/optimizer_high_resolution.js.map +0 -1
  189. package/dist/analysis/analyze_dynamic_weight.d.ts.map +0 -1
  190. package/dist/analysis/analyze_dynamic_weight.js.map +0 -1
  191. package/dist/analysis/analyze_kalman.d.ts.map +0 -1
  192. package/dist/analysis/analyze_kalman.js.map +0 -1
  193. package/dist/analysis/analyze_regime.d.ts.map +0 -1
  194. package/dist/analysis/analyze_regime.js.map +0 -1
  195. package/dist/analysis/analyze_regime_windows.d.ts.map +0 -1
  196. package/dist/analysis/analyze_regime_windows.js.map +0 -1
  197. package/dist/analysis/analyze_risk_profile.d.ts.map +0 -1
  198. package/dist/analysis/analyze_risk_profile.js.map +0 -1
  199. package/dist/analysis/analyze_trade_heatmap.d.ts.map +0 -1
  200. package/dist/analysis/analyze_trade_heatmap.js.map +0 -1
  201. package/dist/analysis/analyze_volatility.d.ts.map +0 -1
  202. package/dist/analysis/analyze_volatility.js.map +0 -1
  203. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts.map +0 -1
  204. package/dist/analysis/bot_fitting/backtest_ama_sweep.js.map +0 -1
  205. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts.map +0 -1
  206. package/dist/analysis/bot_fitting/backtest_bot_fitting.js.map +0 -1
  207. package/dist/analysis/bot_fitting/shared_utils.d.ts.map +0 -1
  208. package/dist/analysis/bot_fitting/shared_utils.js.map +0 -1
  209. package/dist/analysis/bot_key_utils.d.ts.map +0 -1
  210. package/dist/analysis/bot_key_utils.js.map +0 -1
  211. package/dist/analysis/bot_usage/discover_bot_accounts.d.ts.map +0 -1
  212. package/dist/analysis/bot_usage/discover_bot_accounts.js.map +0 -1
  213. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +0 -1
  214. package/dist/analysis/bot_usage/kibana_bot_queries.js.map +0 -1
  215. package/dist/analysis/chain_pool.d.ts.map +0 -1
  216. package/dist/analysis/chain_pool.js.map +0 -1
  217. package/dist/analysis/chart_css.d.ts.map +0 -1
  218. package/dist/analysis/chart_css.js.map +0 -1
  219. package/dist/analysis/chart_ui.d.ts.map +0 -1
  220. package/dist/analysis/chart_ui.js.map +0 -1
  221. package/dist/analysis/chart_utils.d.ts.map +0 -1
  222. package/dist/analysis/chart_utils.js.map +0 -1
  223. package/dist/analysis/fills_source.d.ts.map +0 -1
  224. package/dist/analysis/fills_source.js.map +0 -1
  225. package/dist/analysis/grid_correction_check.d.ts.map +0 -1
  226. package/dist/analysis/grid_correction_check.js.map +0 -1
  227. package/dist/analysis/math_utils.d.ts.map +0 -1
  228. package/dist/analysis/math_utils.js.map +0 -1
  229. package/dist/analysis/price_sources.d.ts.map +0 -1
  230. package/dist/analysis/price_sources.js.map +0 -1
  231. package/dist/analysis/resolve_bot_accounts.d.ts.map +0 -1
  232. package/dist/analysis/resolve_bot_accounts.js.map +0 -1
  233. package/dist/analysis/resolve_source.d.ts.map +0 -1
  234. package/dist/analysis/resolve_source.js.map +0 -1
  235. package/dist/analysis/trade_profitability.d.ts.map +0 -1
  236. package/dist/analysis/trade_profitability.js.map +0 -1
  237. package/dist/analysis/tradingview/analyze_tradingview.d.ts.map +0 -1
  238. package/dist/analysis/tradingview/analyze_tradingview.js.map +0 -1
  239. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts.map +0 -1
  240. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js.map +0 -1
  241. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +0 -1
  242. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +0 -1
  243. package/dist/analysis/trend_detection/hurst_analyzer.d.ts.map +0 -1
  244. package/dist/analysis/trend_detection/hurst_analyzer.js.map +0 -1
  245. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts.map +0 -1
  246. package/dist/analysis/trend_detection/kalman_chart_generator.js.map +0 -1
  247. package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts.map +0 -1
  248. package/dist/analysis/trend_detection/kalman_trend_analyzer.js.map +0 -1
  249. package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts.map +0 -1
  250. package/dist/analysis/trend_detection/kalman_velocity_smoothing.js.map +0 -1
  251. package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts.map +0 -1
  252. package/dist/analysis/trend_detection/permutation_entropy_analyzer.js.map +0 -1
  253. package/dist/analysis/trend_detection/regime_chart_generator.d.ts.map +0 -1
  254. package/dist/analysis/trend_detection/regime_chart_generator.js.map +0 -1
  255. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts +0 -2
  256. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts.map +0 -1
  257. package/dist/analysis/trend_detection/tests/test_kalman_trend.js +0 -128
  258. package/dist/analysis/trend_detection/tests/test_kalman_trend.js.map +0 -1
  259. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts +0 -2
  260. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts.map +0 -1
  261. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js +0 -37
  262. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js.map +0 -1
  263. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts.map +0 -1
  264. package/dist/analysis/trend_detection/volatility_chart_generator.js.map +0 -1
  265. package/dist/bot.d.ts.map +0 -1
  266. package/dist/bot.js.map +0 -1
  267. package/dist/credential-daemon.d.ts.map +0 -1
  268. package/dist/credential-daemon.js.map +0 -1
  269. package/dist/dexbot.d.ts.map +0 -1
  270. package/dist/dexbot.js.map +0 -1
  271. package/dist/market_adapter/ama_signal_runner.d.ts.map +0 -1
  272. package/dist/market_adapter/ama_signal_runner.js.map +0 -1
  273. package/dist/market_adapter/candle_utils.d.ts.map +0 -1
  274. package/dist/market_adapter/candle_utils.js.map +0 -1
  275. package/dist/market_adapter/core/asymmetric_bounds.d.ts.map +0 -1
  276. package/dist/market_adapter/core/asymmetric_bounds.js.map +0 -1
  277. package/dist/market_adapter/core/config_normalizers.d.ts.map +0 -1
  278. package/dist/market_adapter/core/config_normalizers.js.map +0 -1
  279. package/dist/market_adapter/core/kibana_candles.d.ts.map +0 -1
  280. package/dist/market_adapter/core/kibana_candles.js.map +0 -1
  281. package/dist/market_adapter/core/kibana_client.d.ts.map +0 -1
  282. package/dist/market_adapter/core/kibana_client.js.map +0 -1
  283. package/dist/market_adapter/core/kibana_market_candles.d.ts.map +0 -1
  284. package/dist/market_adapter/core/kibana_market_candles.js.map +0 -1
  285. package/dist/market_adapter/core/market_adapter_service.d.ts.map +0 -1
  286. package/dist/market_adapter/core/market_adapter_service.js.map +0 -1
  287. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts.map +0 -1
  288. package/dist/market_adapter/core/signals/hurst_analyzer.js.map +0 -1
  289. package/dist/market_adapter/core/signals/kalman_trend_analyzer.d.ts.map +0 -1
  290. package/dist/market_adapter/core/signals/kalman_trend_analyzer.js.map +0 -1
  291. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.d.ts.map +0 -1
  292. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.js.map +0 -1
  293. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts.map +0 -1
  294. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js.map +0 -1
  295. package/dist/market_adapter/core/strategies/ama.d.ts.map +0 -1
  296. package/dist/market_adapter/core/strategies/ama.js.map +0 -1
  297. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts.map +0 -1
  298. package/dist/market_adapter/core/strategies/ama_slope_model.js.map +0 -1
  299. package/dist/market_adapter/core/strategies/atr/calculator.d.ts.map +0 -1
  300. package/dist/market_adapter/core/strategies/atr/calculator.js.map +0 -1
  301. package/dist/market_adapter/core/strategies/collateral_manager.d.ts.map +0 -1
  302. package/dist/market_adapter/core/strategies/collateral_manager.js.map +0 -1
  303. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts.map +0 -1
  304. package/dist/market_adapter/core/strategies/dynamic_weight_series.js.map +0 -1
  305. package/dist/market_adapter/core/strategies/regime_gate.d.ts.map +0 -1
  306. package/dist/market_adapter/core/strategies/regime_gate.js.map +0 -1
  307. package/dist/market_adapter/core/strategies/regime_interp.d.ts.map +0 -1
  308. package/dist/market_adapter/core/strategies/regime_interp.js.map +0 -1
  309. package/dist/market_adapter/core/strategies/volatility_shift.d.ts.map +0 -1
  310. package/dist/market_adapter/core/strategies/volatility_shift.js.map +0 -1
  311. package/dist/market_adapter/inputs/fetch_book_data.d.ts.map +0 -1
  312. package/dist/market_adapter/inputs/fetch_book_data.js.map +0 -1
  313. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.d.ts.map +0 -1
  314. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js.map +0 -1
  315. package/dist/market_adapter/inputs/fetch_lp_data.d.ts.map +0 -1
  316. package/dist/market_adapter/inputs/fetch_lp_data.js.map +0 -1
  317. package/dist/market_adapter/inputs/kibana_feed_source.d.ts.map +0 -1
  318. package/dist/market_adapter/inputs/kibana_feed_source.js.map +0 -1
  319. package/dist/market_adapter/inputs/kibana_source.d.ts.map +0 -1
  320. package/dist/market_adapter/inputs/kibana_source.js.map +0 -1
  321. package/dist/market_adapter/inputs/window_cache.d.ts.map +0 -1
  322. package/dist/market_adapter/inputs/window_cache.js.map +0 -1
  323. package/dist/market_adapter/interval_utils.d.ts.map +0 -1
  324. package/dist/market_adapter/interval_utils.js.map +0 -1
  325. package/dist/market_adapter/log_format.d.ts.map +0 -1
  326. package/dist/market_adapter/log_format.js.map +0 -1
  327. package/dist/market_adapter/lp_chart_core.d.ts.map +0 -1
  328. package/dist/market_adapter/lp_chart_core.js.map +0 -1
  329. package/dist/market_adapter/lp_chart_runner.d.ts.map +0 -1
  330. package/dist/market_adapter/lp_chart_runner.js.map +0 -1
  331. package/dist/market_adapter/lp_chart_strategy_loader.d.ts.map +0 -1
  332. package/dist/market_adapter/lp_chart_strategy_loader.js.map +0 -1
  333. package/dist/market_adapter/market_adapter.d.ts.map +0 -1
  334. package/dist/market_adapter/market_adapter.js.map +0 -1
  335. package/dist/market_adapter/test_helpers.d.ts.map +0 -1
  336. package/dist/market_adapter/test_helpers.js.map +0 -1
  337. package/dist/market_adapter/utils/adapter_client.d.ts.map +0 -1
  338. package/dist/market_adapter/utils/adapter_client.js.map +0 -1
  339. package/dist/market_adapter/utils/atomic_write.d.ts.map +0 -1
  340. package/dist/market_adapter/utils/atomic_write.js.map +0 -1
  341. package/dist/market_adapter/utils/chain.d.ts.map +0 -1
  342. package/dist/market_adapter/utils/chain.js.map +0 -1
  343. package/dist/market_adapter/utils/data_discovery.d.ts.map +0 -1
  344. package/dist/market_adapter/utils/data_discovery.js.map +0 -1
  345. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts.map +0 -1
  346. package/dist/market_adapter/utils/dynamic_grid_snapshot.js.map +0 -1
  347. package/dist/market_adapter/utils/file_lock.d.ts.map +0 -1
  348. package/dist/market_adapter/utils/file_lock.js.map +0 -1
  349. package/dist/market_adapter/utils/native_history.d.ts.map +0 -1
  350. package/dist/market_adapter/utils/native_history.js.map +0 -1
  351. package/dist/modules/account_bots.d.ts.map +0 -1
  352. package/dist/modules/account_bots.js.map +0 -1
  353. package/dist/modules/account_orders.d.ts.map +0 -1
  354. package/dist/modules/account_orders.js.map +0 -1
  355. package/dist/modules/authority_resolver.d.ts.map +0 -1
  356. package/dist/modules/authority_resolver.js.map +0 -1
  357. package/dist/modules/bitshares-native/chain_client.d.ts.map +0 -1
  358. package/dist/modules/bitshares-native/chain_client.js.map +0 -1
  359. package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts.map +0 -1
  360. package/dist/modules/bitshares-native/crypto/ecc.browser.js.map +0 -1
  361. package/dist/modules/bitshares-native/crypto/ecc.d.ts.map +0 -1
  362. package/dist/modules/bitshares-native/crypto/ecc.js.map +0 -1
  363. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts.map +0 -1
  364. package/dist/modules/bitshares-native/crypto/ecc_selector.js.map +0 -1
  365. package/dist/modules/bitshares-native/index.d.ts.map +0 -1
  366. package/dist/modules/bitshares-native/index.js.map +0 -1
  367. package/dist/modules/bitshares-native/lru_cache.d.ts.map +0 -1
  368. package/dist/modules/bitshares-native/lru_cache.js.map +0 -1
  369. package/dist/modules/bitshares-native/resolvers.d.ts.map +0 -1
  370. package/dist/modules/bitshares-native/resolvers.js.map +0 -1
  371. package/dist/modules/bitshares-native/serial/chain_constants.d.ts.map +0 -1
  372. package/dist/modules/bitshares-native/serial/chain_constants.js.map +0 -1
  373. package/dist/modules/bitshares-native/serial/index.d.ts.map +0 -1
  374. package/dist/modules/bitshares-native/serial/index.js.map +0 -1
  375. package/dist/modules/bitshares-native/serial/operations.d.ts.map +0 -1
  376. package/dist/modules/bitshares-native/serial/operations.js.map +0 -1
  377. package/dist/modules/bitshares-native/serial/serializer.d.ts.map +0 -1
  378. package/dist/modules/bitshares-native/serial/serializer.js.map +0 -1
  379. package/dist/modules/bitshares-native/serial/types.d.ts.map +0 -1
  380. package/dist/modules/bitshares-native/serial/types.js.map +0 -1
  381. package/dist/modules/bitshares-native/signing_client.d.ts.map +0 -1
  382. package/dist/modules/bitshares-native/signing_client.js.map +0 -1
  383. package/dist/modules/bitshares-native/subscriptions.d.ts.map +0 -1
  384. package/dist/modules/bitshares-native/subscriptions.js.map +0 -1
  385. package/dist/modules/bitshares-native/transport.d.ts.map +0 -1
  386. package/dist/modules/bitshares-native/transport.js.map +0 -1
  387. package/dist/modules/bitshares-native/tx/builder.d.ts.map +0 -1
  388. package/dist/modules/bitshares-native/tx/builder.js.map +0 -1
  389. package/dist/modules/bitshares-native/tx/tx_cache.d.ts.map +0 -1
  390. package/dist/modules/bitshares-native/tx/tx_cache.js.map +0 -1
  391. package/dist/modules/bitshares_client.d.ts.map +0 -1
  392. package/dist/modules/bitshares_client.js.map +0 -1
  393. package/dist/modules/bot_defaults.d.ts.map +0 -1
  394. package/dist/modules/bot_defaults.js.map +0 -1
  395. package/dist/modules/bot_settings.d.ts.map +0 -1
  396. package/dist/modules/bot_settings.js.map +0 -1
  397. package/dist/modules/bots_file_lock.d.ts.map +0 -1
  398. package/dist/modules/bots_file_lock.js.map +0 -1
  399. package/dist/modules/broadcast_failure.d.ts.map +0 -1
  400. package/dist/modules/broadcast_failure.js.map +0 -1
  401. package/dist/modules/chain_keys.d.ts.map +0 -1
  402. package/dist/modules/chain_keys.js.map +0 -1
  403. package/dist/modules/chain_orders.d.ts.map +0 -1
  404. package/dist/modules/chain_orders.js.map +0 -1
  405. package/dist/modules/cli_colors.d.ts.map +0 -1
  406. package/dist/modules/cli_colors.js.map +0 -1
  407. package/dist/modules/config.d.ts.map +0 -1
  408. package/dist/modules/config.js.map +0 -1
  409. package/dist/modules/constants.d.ts.map +0 -1
  410. package/dist/modules/constants.js.map +0 -1
  411. package/dist/modules/cr_planner.d.ts.map +0 -1
  412. package/dist/modules/cr_planner.js.map +0 -1
  413. package/dist/modules/credential_policy.d.ts.map +0 -1
  414. package/dist/modules/credential_policy.js.map +0 -1
  415. package/dist/modules/credential_runtime.d.ts.map +0 -1
  416. package/dist/modules/credential_runtime.js.map +0 -1
  417. package/dist/modules/credential_session_cache.d.ts.map +0 -1
  418. package/dist/modules/credential_session_cache.js.map +0 -1
  419. package/dist/modules/credit_pricing.d.ts.map +0 -1
  420. package/dist/modules/credit_pricing.js.map +0 -1
  421. package/dist/modules/credit_runtime.d.ts.map +0 -1
  422. package/dist/modules/credit_runtime.js.map +0 -1
  423. package/dist/modules/crypto/browser_provider.d.ts.map +0 -1
  424. package/dist/modules/crypto/browser_provider.js.map +0 -1
  425. package/dist/modules/crypto/index.d.ts.map +0 -1
  426. package/dist/modules/crypto/index.js.map +0 -1
  427. package/dist/modules/crypto/node_provider.d.ts.map +0 -1
  428. package/dist/modules/crypto/node_provider.js.map +0 -1
  429. package/dist/modules/crypto/provider.d.ts.map +0 -1
  430. package/dist/modules/crypto/provider.js.map +0 -1
  431. package/dist/modules/crypto/pure_ripemd160.d.ts.map +0 -1
  432. package/dist/modules/crypto/pure_ripemd160.js.map +0 -1
  433. package/dist/modules/crypto/pure_scrypt.d.ts.map +0 -1
  434. package/dist/modules/crypto/pure_scrypt.js.map +0 -1
  435. package/dist/modules/crypto/pure_secp256k1.d.ts.map +0 -1
  436. package/dist/modules/crypto/pure_secp256k1.js.map +0 -1
  437. package/dist/modules/crypto/sync.d.ts.map +0 -1
  438. package/dist/modules/crypto/sync.js.map +0 -1
  439. package/dist/modules/daemon_node_health.d.ts.map +0 -1
  440. package/dist/modules/daemon_node_health.js.map +0 -1
  441. package/dist/modules/dexbot_class.d.ts.map +0 -1
  442. package/dist/modules/dexbot_class.js.map +0 -1
  443. package/dist/modules/dexbot_cow_runtime.d.ts.map +0 -1
  444. package/dist/modules/dexbot_cow_runtime.js.map +0 -1
  445. package/dist/modules/dexbot_credential_client.d.ts.map +0 -1
  446. package/dist/modules/dexbot_credential_client.js.map +0 -1
  447. package/dist/modules/dexbot_fill_runtime.d.ts.map +0 -1
  448. package/dist/modules/dexbot_fill_runtime.js.map +0 -1
  449. package/dist/modules/dexbot_maintenance_runtime.d.ts.map +0 -1
  450. package/dist/modules/dexbot_maintenance_runtime.js.map +0 -1
  451. package/dist/modules/dexbot_startup_runtime.d.ts.map +0 -1
  452. package/dist/modules/dexbot_startup_runtime.js.map +0 -1
  453. package/dist/modules/dexbot_state_recovery.d.ts.map +0 -1
  454. package/dist/modules/dexbot_state_recovery.js.map +0 -1
  455. package/dist/modules/env.d.ts.map +0 -1
  456. package/dist/modules/env.js.map +0 -1
  457. package/dist/modules/fund_registry.d.ts.map +0 -1
  458. package/dist/modules/fund_registry.js.map +0 -1
  459. package/dist/modules/general_settings.d.ts.map +0 -1
  460. package/dist/modules/general_settings.js.map +0 -1
  461. package/dist/modules/graceful_shutdown.d.ts.map +0 -1
  462. package/dist/modules/graceful_shutdown.js.map +0 -1
  463. package/dist/modules/grid_price_source.d.ts.map +0 -1
  464. package/dist/modules/grid_price_source.js.map +0 -1
  465. package/dist/modules/key_store.d.ts.map +0 -1
  466. package/dist/modules/key_store.js.map +0 -1
  467. package/dist/modules/launcher/adapter_requirement.d.ts.map +0 -1
  468. package/dist/modules/launcher/adapter_requirement.js.map +0 -1
  469. package/dist/modules/launcher/bot_supervisor.d.ts.map +0 -1
  470. package/dist/modules/launcher/bot_supervisor.js.map +0 -1
  471. package/dist/modules/launcher/child_env.d.ts.map +0 -1
  472. package/dist/modules/launcher/child_env.js.map +0 -1
  473. package/dist/modules/launcher/credential_bootstrap.d.ts.map +0 -1
  474. package/dist/modules/launcher/credential_bootstrap.js.map +0 -1
  475. package/dist/modules/launcher/credential_daemon.d.ts.map +0 -1
  476. package/dist/modules/launcher/credential_daemon.js.map +0 -1
  477. package/dist/modules/launcher/credential_secret.d.ts.map +0 -1
  478. package/dist/modules/launcher/credential_secret.js.map +0 -1
  479. package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +0 -1
  480. package/dist/modules/launcher/foreign_cred_daemon.js.map +0 -1
  481. package/dist/modules/launcher/headless_password.d.ts.map +0 -1
  482. package/dist/modules/launcher/headless_password.js.map +0 -1
  483. package/dist/modules/launcher/launch_modes.d.ts.map +0 -1
  484. package/dist/modules/launcher/launch_modes.js.map +0 -1
  485. package/dist/modules/launcher/market_adapter_runtime.d.ts.map +0 -1
  486. package/dist/modules/launcher/market_adapter_runtime.js.map +0 -1
  487. package/dist/modules/launcher/market_adapter_watchdog.d.ts.map +0 -1
  488. package/dist/modules/launcher/market_adapter_watchdog.js.map +0 -1
  489. package/dist/modules/launcher/monolithic_runtime.d.ts.map +0 -1
  490. package/dist/modules/launcher/monolithic_runtime.js.map +0 -1
  491. package/dist/modules/launcher/runtime_entry.d.ts.map +0 -1
  492. package/dist/modules/launcher/runtime_entry.js.map +0 -1
  493. package/dist/modules/launcher/status_reporting.d.ts.map +0 -1
  494. package/dist/modules/launcher/status_reporting.js.map +0 -1
  495. package/dist/modules/launcher/supervisor_control.d.ts.map +0 -1
  496. package/dist/modules/launcher/supervisor_control.js.map +0 -1
  497. package/dist/modules/market_adapter_whitelist.d.ts.map +0 -1
  498. package/dist/modules/market_adapter_whitelist.js.map +0 -1
  499. package/dist/modules/node_connect_policy.d.ts.map +0 -1
  500. package/dist/modules/node_connect_policy.js.map +0 -1
  501. package/dist/modules/node_failure_ledger.d.ts.map +0 -1
  502. package/dist/modules/node_failure_ledger.js.map +0 -1
  503. package/dist/modules/node_health_cache.d.ts.map +0 -1
  504. package/dist/modules/node_health_cache.js.map +0 -1
  505. package/dist/modules/node_manager.d.ts.map +0 -1
  506. package/dist/modules/node_manager.js.map +0 -1
  507. package/dist/modules/order/accounting.d.ts.map +0 -1
  508. package/dist/modules/order/accounting.js.map +0 -1
  509. package/dist/modules/order/async_lock.d.ts.map +0 -1
  510. package/dist/modules/order/async_lock.js.map +0 -1
  511. package/dist/modules/order/export.d.ts.map +0 -1
  512. package/dist/modules/order/export.js.map +0 -1
  513. package/dist/modules/order/format.d.ts.map +0 -1
  514. package/dist/modules/order/format.js.map +0 -1
  515. package/dist/modules/order/grid.d.ts.map +0 -1
  516. package/dist/modules/order/grid.js.map +0 -1
  517. package/dist/modules/order/grid_reconcile.d.ts.map +0 -1
  518. package/dist/modules/order/grid_reconcile.js.map +0 -1
  519. package/dist/modules/order/grid_reconcile_internal.d.ts.map +0 -1
  520. package/dist/modules/order/grid_reconcile_internal.js.map +0 -1
  521. package/dist/modules/order/index.d.ts.map +0 -1
  522. package/dist/modules/order/index.js.map +0 -1
  523. package/dist/modules/order/logger.d.ts.map +0 -1
  524. package/dist/modules/order/logger.js.map +0 -1
  525. package/dist/modules/order/logger_state.d.ts.map +0 -1
  526. package/dist/modules/order/logger_state.js.map +0 -1
  527. package/dist/modules/order/manager.d.ts.map +0 -1
  528. package/dist/modules/order/manager.js.map +0 -1
  529. package/dist/modules/order/processed_fill_store.d.ts.map +0 -1
  530. package/dist/modules/order/processed_fill_store.js.map +0 -1
  531. package/dist/modules/order/strategy.d.ts.map +0 -1
  532. package/dist/modules/order/strategy.js.map +0 -1
  533. package/dist/modules/order/sync_engine.d.ts.map +0 -1
  534. package/dist/modules/order/sync_engine.js.map +0 -1
  535. package/dist/modules/order/utils/math.d.ts.map +0 -1
  536. package/dist/modules/order/utils/math.js.map +0 -1
  537. package/dist/modules/order/utils/order.d.ts.map +0 -1
  538. package/dist/modules/order/utils/order.js.map +0 -1
  539. package/dist/modules/order/utils/slot.d.ts.map +0 -1
  540. package/dist/modules/order/utils/slot.js.map +0 -1
  541. package/dist/modules/order/utils/system.d.ts.map +0 -1
  542. package/dist/modules/order/utils/system.js.map +0 -1
  543. package/dist/modules/order/utils/timeout.d.ts.map +0 -1
  544. package/dist/modules/order/utils/timeout.js.map +0 -1
  545. package/dist/modules/order/utils/validate.d.ts.map +0 -1
  546. package/dist/modules/order/utils/validate.js.map +0 -1
  547. package/dist/modules/order/utils/withPoolRef.d.ts.map +0 -1
  548. package/dist/modules/order/utils/withPoolRef.js.map +0 -1
  549. package/dist/modules/order/working_grid.d.ts.map +0 -1
  550. package/dist/modules/order/working_grid.js.map +0 -1
  551. package/dist/modules/path_api.d.ts.map +0 -1
  552. package/dist/modules/path_api.js.map +0 -1
  553. package/dist/modules/paths.d.ts.map +0 -1
  554. package/dist/modules/paths.js.map +0 -1
  555. package/dist/modules/process_discovery.d.ts.map +0 -1
  556. package/dist/modules/process_discovery.js.map +0 -1
  557. package/dist/modules/runtime.d.ts.map +0 -1
  558. package/dist/modules/runtime.js.map +0 -1
  559. package/dist/modules/runtime_settings.d.ts.map +0 -1
  560. package/dist/modules/runtime_settings.js.map +0 -1
  561. package/dist/modules/settings_merge.d.ts.map +0 -1
  562. package/dist/modules/settings_merge.js.map +0 -1
  563. package/dist/modules/socket_json_client.d.ts.map +0 -1
  564. package/dist/modules/socket_json_client.js.map +0 -1
  565. package/dist/modules/storage/browser_adapter.d.ts.map +0 -1
  566. package/dist/modules/storage/browser_adapter.js.map +0 -1
  567. package/dist/modules/storage/index.d.ts.map +0 -1
  568. package/dist/modules/storage/index.js.map +0 -1
  569. package/dist/modules/storage/node_adapter.d.ts.map +0 -1
  570. package/dist/modules/storage/node_adapter.js.map +0 -1
  571. package/dist/modules/storage/types.d.ts.map +0 -1
  572. package/dist/modules/storage/types.js.map +0 -1
  573. package/dist/modules/types.d.ts.map +0 -1
  574. package/dist/modules/types.js.map +0 -1
  575. package/dist/modules/utils/base58check.d.ts.map +0 -1
  576. package/dist/modules/utils/base58check.js.map +0 -1
  577. package/dist/modules/utils/build_dir.d.ts.map +0 -1
  578. package/dist/modules/utils/build_dir.js.map +0 -1
  579. package/dist/modules/utils/chain_logs.d.ts.map +0 -1
  580. package/dist/modules/utils/chain_logs.js.map +0 -1
  581. package/dist/modules/utils/errors.d.ts.map +0 -1
  582. package/dist/modules/utils/errors.js.map +0 -1
  583. package/dist/modules/utils/sanitize_key.d.ts.map +0 -1
  584. package/dist/modules/utils/sanitize_key.js.map +0 -1
  585. package/dist/modules/validate_profiles.d.ts.map +0 -1
  586. package/dist/modules/validate_profiles.js.map +0 -1
  587. package/dist/pm2.d.ts.map +0 -1
  588. package/dist/pm2.js.map +0 -1
  589. package/dist/scripts/analyze-credit.d.ts.map +0 -1
  590. package/dist/scripts/analyze-credit.js.map +0 -1
  591. package/dist/scripts/analyze-git.d.ts.map +0 -1
  592. package/dist/scripts/analyze-git.js.map +0 -1
  593. package/dist/scripts/analyze-orders.d.ts.map +0 -1
  594. package/dist/scripts/analyze-orders.js.map +0 -1
  595. package/dist/scripts/chart_command.d.ts.map +0 -1
  596. package/dist/scripts/chart_command.js.map +0 -1
  597. package/dist/scripts/diagnose-kibana-candles.d.ts.map +0 -1
  598. package/dist/scripts/diagnose-kibana-candles.js.map +0 -1
  599. package/dist/scripts/diagnose-pool-history.d.ts.map +0 -1
  600. package/dist/scripts/diagnose-pool-history.js.map +0 -1
  601. package/dist/scripts/divergence-calc.d.ts.map +0 -1
  602. package/dist/scripts/divergence-calc.js.map +0 -1
  603. package/dist/scripts/dw.d.ts.map +0 -1
  604. package/dist/scripts/dw.js.map +0 -1
  605. package/dist/scripts/generate_lp_chart.d.ts.map +0 -1
  606. package/dist/scripts/generate_lp_chart.js.map +0 -1
  607. package/dist/scripts/generate_mainnet_corpus_report.d.ts.map +0 -1
  608. package/dist/scripts/generate_mainnet_corpus_report.js.map +0 -1
  609. package/dist/scripts/native_release_gates.d.ts.map +0 -1
  610. package/dist/scripts/native_release_gates.js.map +0 -1
  611. package/dist/scripts/print_grid.d.ts.map +0 -1
  612. package/dist/scripts/print_grid.js.map +0 -1
  613. package/dist/scripts/run-tests.d.ts.map +0 -1
  614. package/dist/scripts/run-tests.js.map +0 -1
  615. package/dist/scripts/runner.d.ts.map +0 -1
  616. package/dist/scripts/runner.js.map +0 -1
  617. package/dist/scripts/sync-version.d.ts.map +0 -1
  618. package/dist/scripts/sync-version.js.map +0 -1
  619. package/dist/scripts/test-credit-renewal.d.ts.map +0 -1
  620. package/dist/scripts/test-credit-renewal.js.map +0 -1
  621. package/dist/scripts/tv.d.ts.map +0 -1
  622. package/dist/scripts/tv.js.map +0 -1
  623. package/dist/scripts/update.d.ts.map +0 -1
  624. package/dist/scripts/update.js.map +0 -1
  625. package/dist/scripts/update_dist_freshness.d.ts.map +0 -1
  626. package/dist/scripts/update_dist_freshness.js.map +0 -1
  627. package/dist/scripts/validate_bots.d.ts.map +0 -1
  628. package/dist/scripts/validate_bots.js.map +0 -1
  629. package/dist/scripts/verify-browser-bundle.d.ts.map +0 -1
  630. package/dist/scripts/verify-browser-bundle.js.map +0 -1
  631. package/dist/unlock.d.ts.map +0 -1
  632. package/dist/unlock.js.map +0 -1
@@ -123,10 +123,11 @@ function batchReadOrdersSeam(mgr, orderIds, timeoutMs) {
123
123
  const { BitShares } = client;
124
124
  import { NATIVE_CLIENT } from '../constants.js';
125
125
  const { toFiniteNumber } = Format;
126
- import { blockchainToFloat, floatToBlockchainInt, calculatePriceTolerance, getAssetFees, getBtsSide, getSellStartIdx, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, isSlotIndexInGapBand, priceForSlot, priceSlotEqual } from './utils/math.js';
127
- import { parseChainOrder, findMatchingGridOrderByOpenOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance } from './utils/order.js';
126
+ import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, priceForSlot, priceSlotEqual } from './utils/math.js';
127
+ import { parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance } from './utils/order.js';
128
128
  import { parseSlotIndex } from './utils/slot.js';
129
129
  import { resolveProcessedFillPersistenceMode } from './processed_fill_store.js';
130
+ import { hasGenesisLadder } from './genesis_policy.js';
130
131
  import { getErrorMessage } from '../utils/errors.js';
131
132
  /**
132
133
  * Confirming re-read for the suspect-empty-read guard: after
@@ -200,7 +201,16 @@ async function confirmSuspectEmptyRead(mgr) {
200
201
  return 'ambiguous';
201
202
  }
202
203
  }
203
- function describeNearestAdoptionCandidates(mgr, chainOrder, precision, calcTolerance, matchedGridOrderIds = null) {
204
+ /**
205
+ * Describe the nearest same-side (or spread) candidate slots for a chain order
206
+ * that could not be adopted, so a log read says WHICH slot blocked it.
207
+ *
208
+ * Ladder-based, not tolerance-based: a candidate is "at this price" when the
209
+ * chain order and the candidate's slot price map to the same ladder level
210
+ * (`chainPriceOnSameLevel` — the adoption rule itself). The price diff is
211
+ * reported against the slot's own level for the human reader.
212
+ */
213
+ function describeNearestAdoptionCandidates(mgr, chainOrder, precision, matchedGridOrderIds = null) {
204
214
  if (!mgr?.orders || !chainOrder || typeof precision !== 'number')
205
215
  return 'candidate diagnostics unavailable';
206
216
  const chainPrice = toFiniteNumber(chainOrder.price);
@@ -216,26 +226,31 @@ function describeNearestAdoptionCandidates(mgr, chainOrder, precision, calcToler
216
226
  continue;
217
227
  const price = toFiniteNumber(slot.price);
218
228
  const priceDiff = Math.abs(price - chainPrice);
219
- const effectiveSize = slot.size > 0 ? toFiniteNumber(slot.size) : chainSize;
220
- const tolerance = calcTolerance(price, effectiveSize, chainOrder.type) || 0;
229
+ let priceEqual = false;
230
+ try {
231
+ priceEqual = chainPriceOnSameLevel(chainPrice, price, mgr?._genesis, precision);
232
+ }
233
+ catch {
234
+ priceEqual = chainPrice === price;
235
+ }
221
236
  const gridInt = floatToBlockchainInt(toFiniteNumber(slot.size), precision);
222
237
  const sizeDiffInt = chainInt - gridInt;
223
238
  const hasOrderId = Boolean(slot.orderId);
224
239
  const alreadyMatched = Boolean(matchedGridOrderIds?.has?.(slot.id));
225
240
  const sizeOk = Math.abs(sizeDiffInt) <= 1;
226
- const primaryEligible = typeMatch && priceDiff <= tolerance && sizeOk;
227
- const fallbackEligible = (typeMatch || spreadMatch) && priceDiff <= tolerance && sizeOk && !hasOrderId && !alreadyMatched;
241
+ const primaryEligible = typeMatch && priceEqual && sizeOk;
242
+ const adoptable = (typeMatch || spreadMatch) && priceEqual && sizeOk && !hasOrderId && !alreadyMatched;
228
243
  candidates.push({
229
244
  slot,
230
245
  typeMatch,
231
246
  spreadMatch,
232
247
  priceDiff,
233
- tolerance,
248
+ priceEqual,
234
249
  sizeDiffInt,
235
250
  hasOrderId,
236
251
  alreadyMatched,
237
252
  primaryEligible,
238
- fallbackEligible,
253
+ adoptable,
239
254
  });
240
255
  }
241
256
  candidates.sort((a, b) => a.priceDiff - b.priceDiff);
@@ -246,7 +261,7 @@ function describeNearestAdoptionCandidates(mgr, chainOrder, precision, calcToler
246
261
  const reasons = [];
247
262
  if (!candidate.typeMatch && !candidate.spreadMatch)
248
263
  reasons.push('type');
249
- if (candidate.priceDiff > candidate.tolerance)
264
+ if (!candidate.priceEqual)
250
265
  reasons.push('price');
251
266
  if (Math.abs(candidate.sizeDiffInt) > 1)
252
267
  reasons.push('size');
@@ -256,65 +271,74 @@ function describeNearestAdoptionCandidates(mgr, chainOrder, precision, calcToler
256
271
  reasons.push('alreadyMatched');
257
272
  if (candidate.primaryEligible)
258
273
  reasons.push('primary-matchable');
259
- if (candidate.fallbackEligible)
260
- reasons.push('fallback-adoptable');
274
+ if (candidate.adoptable)
275
+ reasons.push('adoptable');
261
276
  return `${slot.id || 'unknown'} ${slot.type}/${slot.state}` +
262
277
  ` orderId=${slot.orderId || 'none'}` +
263
278
  ` price=${Format.formatPrice6(slot.price)}` +
264
279
  ` diff=${Format.formatPrice6(candidate.priceDiff)}` +
265
- ` tol=${Format.formatPrice6(candidate.tolerance)}` +
266
280
  ` size=${Format.formatSizeByOrderType(slot.size || 0, chainOrder.type, mgr.assets)}` +
267
281
  ` sizeDiffInt=${candidate.sizeDiffInt}` +
268
282
  ` reason=${reasons.join('|') || 'unknown'}`;
269
283
  }).join('; ');
270
284
  }
271
285
  /**
272
- * Find the closest same-side (or spread) candidate slot for a chain order and
273
- * return a "price-drift-orphan" tag if the slot's price diff is larger than the
274
- * strict tolerance but small enough to be considered a meaningful drift.
275
- *
276
- * Rationale: when the chain order has drifted from the planned slot price by
277
- * more than the matcher's strict tolerance (so the matcher correctly rejects
278
- * the adoption), the next planning cycle's pre-broadcast guard will refuse
279
- * new CREATEs and the structural resync will cancel+recreate. Tagging the
280
- * entry as a price-drift-orphan lets the auto-cancel path prioritize it and
281
- * the diagnostics surface the exact slot the orphan drifted from.
286
+ * Whether a chain order rests on the SAME LADDER LEVEL as a slot (the slot's
287
+ * own index), which is the "has this order moved?" test the pass-1 path needs.
282
288
  *
283
- * "Meaningful drift" = price diff > strict tolerance AND price diff
284
- * <= strict tolerance * PRICE_DRIFT_TOLERANCE_MULTIPLIER. Larger diffs are
285
- * considered wildly-out-of-tolerance orphans (e.g. legacy orders from a
286
- * previous config) and are NOT tagged — the resync will discard them
287
- * structurally instead.
288
- *
289
- * @param {Object} mgr - OrderManager instance
290
- * @param {Object} chainOrder - Parsed chain order { price, size, type }
291
- * @param {Function} calcToleranceFn - calculatePriceTolerance function
292
- * @returns {{candidateSlotId: string, candidateSlotPrice: number, priceDiff: number, tolerance: number}|null}
289
+ * Level identity, not float equality: a chain order legitimately rests a few
290
+ * quanta off its slot's level (a regeneration leaves old orders at old levels,
291
+ * a broadcast rounds), and both prices still map to the same slot. An order that
292
+ * maps to a DIFFERENT slot really has moved, and only then is a price
293
+ * correction / duplicate / re-slot warranted. Unjudgeable inputs (no ladder,
294
+ * non-finite price) fall back to integer equality at the asset precision.
293
295
  */
296
+ function chainPriceOnSameLevel(chainPrice, slotPrice, genesis, precision) {
297
+ if (hasGenesisLadder(genesis)) {
298
+ try {
299
+ return slotIndexForPrice(chainPrice, genesis) === slotIndexForPrice(slotPrice, genesis);
300
+ }
301
+ catch { /* unjudgeable — fall through to integer equality */ }
302
+ }
303
+ try {
304
+ return priceSlotEqual(chainPrice, slotPrice, precision);
305
+ }
306
+ catch {
307
+ return chainPrice === slotPrice;
308
+ }
309
+ }
294
310
  /**
295
311
  * Assert (non-fatally) that an adopted slot still carries its own genesis
296
312
  * level, not a price inherited from the chain order.
297
313
  *
298
- * Both adoption paths keep the slot's price by NOT assigning it — an absence of
299
- * a write. That is correct but invisible: nothing would notice if a later edit
300
- * added `price: chainOrder.price` back, and nothing would notice a slot whose
301
- * price had already been corrupted before it reached adoption. This makes the
302
- * rule explicit and warns when it is broken.
314
+ * Adoption keeps the slot's price by NOT assigning it — an absence of a write.
315
+ * That is correct but invisible: nothing would notice if a later edit added
316
+ * `price: chainOrder.price` back, and nothing would notice a slot whose price
317
+ * had already been corrupted before it reached adoption. This makes the rule
318
+ * explicit and warns when it is broken.
303
319
  *
304
320
  * Deliberately non-throwing: adoption already has handled rejection paths, and
305
321
  * turning a warning into a crash here would strand a live chain order. The
306
322
  * caller's existing rejection handling stays the enforcement; this is the
307
323
  * signal that surfaces the corruption in the log.
308
324
  *
309
- * @returns {boolean} true when the slot's price is its genesis level (or cannot
310
- * be judged), false when it demonstrably is not.
325
+ * @returns {boolean} true when the slot's price is its genesis level (or its id
326
+ * cannot address a level); false when it demonstrably is not, or when the
327
+ * manager holds no ladder at all (INV-GRID-004 fault, not a pass).
311
328
  */
312
329
  function adoptedSlotKeepsItsOwnPrice(mgr, adopted, chainOrderId, path) {
313
330
  try {
314
331
  const genesis = mgr?._genesis;
315
332
  const levels = genesis?.priceLevels;
316
- if (!Array.isArray(levels) || levels.length === 0)
317
- return true; // no ladder: unjudgeable, fail open
333
+ if (!Array.isArray(levels) || levels.length === 0) {
334
+ // Undefined grid (INV-GRID-004): no ladder means no authority for
335
+ // the slot's price, so there is nothing to check the adoption
336
+ // against. Report it — the caller's return value is informational
337
+ // (adoption is never blocked), so the log is the signal.
338
+ mgr.logger?.log?.(`[SYNC] Adoption (${path}) for ${chainOrderId} into slot ${adopted?.id}: the manager holds no price ladder ` +
339
+ `(INV-GRID-004), so the slot's price cannot be verified against its genesis level.`, 'error');
340
+ return false;
341
+ }
318
342
  const idx = parseSlotIndex(adopted?.id);
319
343
  if (idx === null || !Number.isFinite(idx) || idx < 0 || idx >= levels.length)
320
344
  return true;
@@ -368,7 +392,7 @@ async function adoptChainOrderIntoSlot(mgr, slot, chainOrder, chainOrderId, rawC
368
392
  // validateOrder treats SPREAD + orderId/on-chain state as fatal
369
393
  // ILLEGAL_SPREAD_STATE, and the size precision below depends on the
370
394
  // resolved side. Every other activation path (COW rotation destinations,
371
- // legacy fallback adoption, grid load) performs the same re-type.
395
+ // grid load) performs the same re-type.
372
396
  if (bestMatch.type === ORDER_TYPES.SPREAD && (chainOrder.type === ORDER_TYPES.BUY || chainOrder.type === ORDER_TYPES.SELL)) {
373
397
  bestMatch.type = chainOrder.type;
374
398
  }
@@ -436,49 +460,6 @@ async function adoptChainOrderIntoSlot(mgr, slot, chainOrder, chainOrderId, rawC
436
460
  chainOrderIdsOnGrid.add(chainOrderId);
437
461
  return true;
438
462
  }
439
- function computeOutOfToleranceDriftTag(mgr, chainOrder, calcToleranceFn) {
440
- if (!mgr?.orders || !chainOrder)
441
- return null;
442
- const chainPrice = toFiniteNumber(chainOrder.price);
443
- if (!Number.isFinite(chainPrice))
444
- return null;
445
- const chainSize = toFiniteNumber(chainOrder.size);
446
- const orderType = chainOrder.type;
447
- if (orderType !== ORDER_TYPES.BUY && orderType !== ORDER_TYPES.SELL)
448
- return null;
449
- let bestDrift = null;
450
- for (const slot of mgr.orders.values()) {
451
- if (!slot)
452
- continue;
453
- if (slot.type !== orderType && slot.type !== ORDER_TYPES.SPREAD)
454
- continue;
455
- if (slot.orderId)
456
- continue;
457
- if (![ORDER_STATES.ACTIVE, ORDER_STATES.PARTIAL, ORDER_STATES.VIRTUAL].includes(slot.state))
458
- continue;
459
- const slotPrice = toFiniteNumber(slot.price);
460
- if (!Number.isFinite(slotPrice))
461
- continue;
462
- const priceDiff = Math.abs(slotPrice - chainPrice);
463
- const effectiveSize = slot.size > 0 ? toFiniteNumber(slot.size) : chainSize;
464
- const tolerance = (calcToleranceFn ? (calcToleranceFn(slotPrice, effectiveSize, orderType) || 0) : 0);
465
- if (priceDiff <= tolerance)
466
- continue;
467
- const driftMultiplier = mgr?.config?.gridLimits?.PRICE_DRIFT_TOLERANCE_MULTIPLIER;
468
- const driftBudget = tolerance * driftMultiplier;
469
- if (driftBudget > 0 && priceDiff > driftBudget)
470
- continue;
471
- if (!bestDrift || priceDiff < bestDrift.priceDiff) {
472
- bestDrift = {
473
- candidateSlotId: slot.id,
474
- candidateSlotPrice: slotPrice,
475
- priceDiff,
476
- tolerance
477
- };
478
- }
479
- }
480
- return bestDrift;
481
- }
482
463
  class SyncEngine {
483
464
  manager;
484
465
  /**
@@ -560,6 +541,23 @@ class SyncEngine {
560
541
  if (!mgr) {
561
542
  throw new Error('manager required for syncFromOpenOrders');
562
543
  }
544
+ // E2 (defence in depth): a populated grid MUST have a price ladder
545
+ // before the first sync touches it. loadGrid (E1) and the startup gate
546
+ // (E3) establish that invariant; this assert exists to catch a future
547
+ // path that skips both. It is FAIL-CLOSED: without a ladder there is no
548
+ // authority for a slot's price, so the sync returns without touching
549
+ // the grid (no locks taken, nothing adopted, nothing queued for
550
+ // correction) and a structural resync re-derives the ladder. There is no
551
+ // tolerance matcher left to fall back to. See docs/GRID_PRICE_INVARIANT.md.
552
+ //
553
+ // Note: unlike the normal path (which snapshots the result into
554
+ // `_lastUnmatchedChainOrders`), this early return does NOT rewrite that
555
+ // snapshot. The refusal is itself the resync signal, and leaving any
556
+ // prior holds in place keeps the maintenance stranded-hold escalation
557
+ // able to act on them until the next successful sync.
558
+ if (!this._assertGenesisInvariant(mgr)) {
559
+ return { filledOrders: [], updatedOrders: [], ordersNeedingCorrection: [], unmatchedChainOrders: [] };
560
+ }
563
561
  if (!mgr._syncLock) {
564
562
  mgr.logger?.log?.('Error: syncLock not initialized', 'error');
565
563
  return { filledOrders: [], updatedOrders: [], ordersNeedingCorrection: [], unmatchedChainOrders: [] };
@@ -949,23 +947,12 @@ class SyncEngine {
949
947
  continue;
950
948
  }
951
949
  else {
952
- const genesisForPass1 = mgr._genesis;
953
- let isPriceEqual = false;
954
- if (genesisForPass1 && Array.isArray(genesisForPass1.priceLevels)) {
955
- const precision = gridOrder.type === ORDER_TYPES.SELL ? assetAPrecision : assetBPrecision;
956
- // Genesis path: single epsilon via integer round-trip
957
- try {
958
- isPriceEqual = priceSlotEqual(chainOrder.price, gridOrder.price, precision);
959
- }
960
- catch {
961
- isPriceEqual = chainOrder.price === gridOrder.price;
962
- }
963
- }
964
- else {
965
- const priceTolerance = calculatePriceTolerance(gridOrder.price, gridOrder.size, gridOrder.type, mgr.assets);
966
- const normalizedTolerance = (priceTolerance === null) ? 0 : priceTolerance;
967
- isPriceEqual = Math.abs(chainOrder.price - gridOrder.price) <= normalizedTolerance;
968
- }
950
+ // "Did the chain order move?" is level identity: both prices
951
+ // must map to the same slot (see chainPriceOnSameLevel). A
952
+ // drift of a few quanta inside one level is normal and must
953
+ // not queue a price correction.
954
+ const precision = gridOrder.type === ORDER_TYPES.SELL ? assetAPrecision : assetBPrecision;
955
+ const isPriceEqual = chainPriceOnSameLevel(chainOrder.price, gridOrder.price, mgr._genesis, precision);
969
956
  if (!isPriceEqual) {
970
957
  queueCorrection({
971
958
  gridOrder: { ...gridOrder },
@@ -1003,23 +990,11 @@ class SyncEngine {
1003
990
  continue;
1004
991
  if (!candidateOrder || candidateOrder.type !== chainOrder.type)
1005
992
  continue;
1006
- // Per-candidate price check: genesis → priceSlotEqual, else tolerance
1007
- const genesisForSwap = mgr._genesis;
1008
- let swapPriceEqual = false;
1009
- if (genesisForSwap && Array.isArray(genesisForSwap.priceLevels)) {
1010
- const precision = gridOrder.type === ORDER_TYPES.SELL ? assetAPrecision : assetBPrecision;
1011
- try {
1012
- swapPriceEqual = priceSlotEqual(candidateOrder.price, gridOrder.price, precision);
1013
- }
1014
- catch {
1015
- swapPriceEqual = candidateOrder.price === gridOrder.price;
1016
- }
1017
- }
1018
- else {
1019
- const candidateTolerance = calculatePriceTolerance(Math.min(candidateOrder.price, gridOrder.price), Math.max(candidateOrder.size, gridOrder.size), gridOrder.type, mgr.assets);
1020
- swapPriceEqual = Math.abs(candidateOrder.price - gridOrder.price) <= (candidateTolerance ?? 0);
1021
- }
1022
- if (!swapPriceEqual)
993
+ // Price check: the candidate must belong to the same
994
+ // ladder level as the slot (the swap tiebreak's whole
995
+ // premise — a duplicate at this level).
996
+ const precision = gridOrder.type === ORDER_TYPES.SELL ? assetAPrecision : assetBPrecision;
997
+ if (!chainPriceOnSameLevel(candidateOrder.price, gridOrder.price, mgr._genesis, precision))
1023
998
  continue;
1024
999
  if (floatToBlockchainInt(candidateOrder.size, precision) !== currentSizeInt)
1025
1000
  continue;
@@ -1182,8 +1157,13 @@ class SyncEngine {
1182
1157
  // PASS 2: CHAIN → GRID - Nearest-slot deterministic adoption (genesis-frozen)
1183
1158
  // ====================================================================
1184
1159
  const genesis = mgr._genesis;
1185
- const hasGenesis = genesis && Array.isArray(genesis.priceLevels) && genesis.priceLevels.length > 0;
1186
- const anchorPrice = hasGenesis ? genesis.startPrice : mgr.config?.startPrice;
1160
+ // Genesis is mandatory for any populated grid, but an EMPTY grid
1161
+ // (slotCount 0) passes the E2 gate without a ladder, so the
1162
+ // `!hasGenesis` branch below is reachable when live chain orders exist
1163
+ // against no slots. There the anchor is meaningless and only orders the
1164
+ // deferred holds (every price is measured against 0, i.e. ascending).
1165
+ const hasGenesis = hasGenesisLadder(genesis);
1166
+ const anchorPrice = hasGenesis ? genesis.startPrice : 0;
1187
1167
  const sortedChainEntries = [...parsedChainOrders.entries()].sort((a, b) => {
1188
1168
  const pa = toFiniteNumber(a[1].price);
1189
1169
  const pb = toFiniteNumber(b[1].price);
@@ -1194,224 +1174,98 @@ class SyncEngine {
1194
1174
  for (const [chainOrderId, chainOrder] of sortedChainEntries) {
1195
1175
  if (chainOrderIdsOnGrid.has(chainOrderId))
1196
1176
  continue;
1197
- // Genesis path: nearest-slot is single authority (no tolerance)
1198
- if (hasGenesis) {
1199
- let idx;
1200
- try {
1201
- idx = slotIndexForPrice(chainOrder.price, genesis);
1202
- }
1203
- catch {
1204
- unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'no-available-nearest-slot' });
1205
- queueCorrection({ gridOrder: { id: `slot-unknown-${chainOrderId}`, type: chainOrder.type }, chainOrderId, expectedPrice: chainOrder.price, size: chainOrder.size, type: chainOrder.type, isSurplus: true, cancelOnly: true });
1206
- continue;
1207
- }
1208
- const slotId = `slot-${idx}`;
1209
- // Out-of-grid hold: slotIndexForPrice clamps below/above-rail
1210
- // prices onto the edge slots (0/N-1), so the clamp is not a
1211
- // real match. A below-grid buy is not slot-0 and an
1212
- // above-grid sell is not slot-(N-1): never adopt into the
1213
- // rail slot and never cancel as its duplicate — hold/defer
1214
- // (no adopt, no cancelOnly), e.g. dip-protection levels
1215
- // sitting below a fresh grid after a reset.
1216
- {
1217
- const precision = (chainOrder.type === ORDER_TYPES.SELL) ? assetAPrecision : assetBPrecision;
1218
- if (isChainPriceOutOfGrid(chainOrder.price, genesis, precision)) {
1219
- unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'out-of-grid-deferred', candidateSlotId: slotId });
1220
- mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: price outside grid range, deferred (nearest slot ${slotId})`, 'warn');
1221
- continue;
1222
- }
1223
- }
1224
- const gapSlots = genesis.gapSlots ?? mgr._gapSlots ?? 0;
1225
- const boundaryIdx = mgr.boundaryIdx;
1226
- // Pre-boundary sync: gap geometry is unknown, so adoption is
1227
- // deferred entirely — touch nothing (no adopt, no cancelOnly).
1228
- // The orphan stays visible to the crossing guards and the
1229
- // validate orphan layer via _lastUnmatchedChainOrders and is
1230
- // re-evaluated once the boundary commits. Accepted cost: a
1231
- // legitimate in-rail orphan waits one sync cycle
1232
- // post-boundary-commit before adoption. Strictly better than
1233
- // adopting a gap stray into the wrong slot.
1234
- if (boundaryIdx == null || !Number.isFinite(Number(boundaryIdx))) {
1235
- unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'boundary-unknown-deferred', candidateSlotId: slotId });
1236
- mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: boundary unknown, deferred until boundary commits (nearest slot ${slotId})`, 'warn');
1237
- continue;
1238
- }
1239
- // Duplicate-price guard becomes slotId equality: if placed order already occupies this slot
1240
- const occupying = mgr.orders.get(slotId);
1241
- if (occupying && isOrderPlaced(occupying) && occupying.type === chainOrder.type) {
1242
- unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'duplicate-price-level', candidateSlotId: slotId });
1243
- const { level, suffix } = duplicateOrphanLogInfo(chainOrderId);
1244
- mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: duplicates slot ${slotId} (${occupying.orderId})${suffix}`, level);
1245
- queueCorrection({ gridOrder: occupying, chainOrderId, expectedPrice: chainOrder.price, size: chainOrder.size, type: chainOrder.type, isSurplus: true, cancelOnly: true });
1246
- continue;
1247
- }
1248
- // Gap exclusion: nearest slot in SPREAD gap → no adopt (boundary
1249
- // is known here — the pre-boundary case continued above).
1250
- {
1251
- const inRail = isSlotInRail(boundaryIdx, gapSlots, chainOrder.type, { id: slotId });
1252
- if (!inRail) {
1253
- unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'no-available-nearest-slot', candidateSlotId: slotId });
1254
- queueCorrection({ gridOrder: { id: slotId, type: chainOrder.type }, chainOrderId, expectedPrice: chainOrder.price, size: chainOrder.size, type: chainOrder.type, isSurplus: true, cancelOnly: true });
1255
- continue;
1256
- }
1257
- }
1258
- const slot = mgr.orders.get(slotId);
1259
- if (!slot || matchedGridOrderIds.has(slot.id) || slot.orderId) {
1260
- unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'no-available-nearest-slot', candidateSlotId: slotId });
1261
- const diag = describeNearestAdoptionCandidates(mgr, chainOrder, (chainOrder.type === ORDER_TYPES.SELL ? assetAPrecision : assetBPrecision), (p, s, t) => calculatePriceTolerance(p, s, t, mgr.assets), matchedGridOrderIds);
1262
- mgr.logger?.log?.(`[SYNC] Unmatched chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}): nearest slot ${slotId} not adoptable. Nearest candidates: ${diag}`, 'warn');
1263
- continue;
1264
- }
1265
- const typeCompat = slot.type === chainOrder.type || slot.type === ORDER_TYPES.SPREAD;
1266
- if (!typeCompat) {
1267
- unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'no-available-nearest-slot', candidateSlotId: slotId });
1177
+ // Genesis is mandatory (INV-GRID-004): the frozen ladder is the single
1178
+ // authority for which slot a chain order belongs to. No tolerance
1179
+ // matcher remains — the E2 gate refuses to sync a ladder-less grid and
1180
+ // loadGrid cannot produce one — so this guard is defence in depth
1181
+ // against a future bypass, not a supported state. A chain order is
1182
+ // never price-matched into a slot.
1183
+ if (!hasGenesis) {
1184
+ // No candidateSlotId: without a ladder no slot index can be
1185
+ // derived, so there is nothing meaningful to name (unlike the
1186
+ // out-of-grid / rail holds, which have a resolved nearest slot).
1187
+ unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'no-genesis-deferred' });
1188
+ mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: the grid has no price ladder (INV-GRID-004); deferred, never price-matched`, 'error');
1189
+ continue;
1190
+ }
1191
+ let idx;
1192
+ try {
1193
+ idx = slotIndexForPrice(chainOrder.price, genesis);
1194
+ }
1195
+ catch {
1196
+ unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'no-available-nearest-slot' });
1197
+ queueCorrection({ gridOrder: { id: `slot-unknown-${chainOrderId}`, type: chainOrder.type }, chainOrderId, expectedPrice: chainOrder.price, size: chainOrder.size, type: chainOrder.type, isSurplus: true, cancelOnly: true });
1198
+ continue;
1199
+ }
1200
+ const slotId = `slot-${idx}`;
1201
+ // Out-of-grid hold: slotIndexForPrice clamps below/above-rail
1202
+ // prices onto the edge slots (0/N-1), so the clamp is not a
1203
+ // real match. A below-grid buy is not slot-0 and an
1204
+ // above-grid sell is not slot-(N-1): never adopt into the
1205
+ // rail slot and never cancel as its duplicate — hold/defer
1206
+ // (no adopt, no cancelOnly), e.g. dip-protection levels
1207
+ // sitting below a fresh grid after a reset.
1208
+ {
1209
+ const precision = (chainOrder.type === ORDER_TYPES.SELL) ? assetAPrecision : assetBPrecision;
1210
+ if (isChainPriceOutOfGrid(chainOrder.price, genesis, precision)) {
1211
+ unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'out-of-grid-deferred', candidateSlotId: slotId });
1212
+ mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: price outside grid range, deferred (nearest slot ${slotId})`, 'warn');
1268
1213
  continue;
1269
1214
  }
1270
- const adopted = await adoptChainOrderIntoSlot(mgr, slot, chainOrder, chainOrderId, rawChainOrders, matchedGridOrderIds, chainOrderIdsOnGrid, filledOrders, updatedOrders, skipAccounting);
1271
- if (!adopted) {
1272
- // Order update was rejected (fatal validation) — the chain
1273
- // order stays untracked and must not dangle on the book.
1274
- unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'adoption-rejected', candidateSlotId: slotId });
1275
- queueCorrection({ gridOrder: slot, chainOrderId, expectedPrice: chainOrder.price, size: chainOrder.size, type: chainOrder.type, isSurplus: true, cancelOnly: true });
1276
- mgr.logger?.log?.(`[SYNC] Chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}) NOT adopted into slot ${slotId}: order update rejected — queued for cancellation`, 'error');
1277
- }
1215
+ }
1216
+ const gapSlots = genesis.gapSlots ?? mgr._gapSlots ?? 0;
1217
+ const boundaryIdx = mgr.boundaryIdx;
1218
+ // Pre-boundary sync: gap geometry is unknown, so adoption is
1219
+ // deferred entirely — touch nothing (no adopt, no cancelOnly).
1220
+ // The orphan stays visible to the crossing guards and the
1221
+ // validate orphan layer via _lastUnmatchedChainOrders and is
1222
+ // re-evaluated once the boundary commits. Accepted cost: a
1223
+ // legitimate in-rail orphan waits one sync cycle
1224
+ // post-boundary-commit before adoption. Strictly better than
1225
+ // adopting a gap stray into the wrong slot.
1226
+ if (boundaryIdx == null || !Number.isFinite(Number(boundaryIdx))) {
1227
+ unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'boundary-unknown-deferred', candidateSlotId: slotId });
1228
+ mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: boundary unknown, deferred until boundary commits (nearest slot ${slotId})`, 'warn');
1278
1229
  continue;
1279
1230
  }
1280
- // Legacy fallback when genesis unavailable (migration)
1281
- const duplicatePriceOrder = Array.from(mgr.orders.values()).find((o) => {
1282
- const co = chainOrder;
1283
- return o.type === co.type && isOrderPlaced(o) && co != null && Math.abs(o.price - co.price) <= calculatePriceTolerance(Math.min(o.price, co.price), Math.max(o.size, co.size), o.type, mgr.assets);
1284
- });
1285
- if (duplicatePriceOrder) {
1286
- unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'duplicate-price-level', candidateSlotId: duplicatePriceOrder.id });
1231
+ // Duplicate-price guard becomes slotId equality: if placed order already occupies this slot
1232
+ const occupying = mgr.orders.get(slotId);
1233
+ if (occupying && isOrderPlaced(occupying) && occupying.type === chainOrder.type) {
1234
+ unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'duplicate-price-level', candidateSlotId: slotId });
1287
1235
  const { level, suffix } = duplicateOrphanLogInfo(chainOrderId);
1288
- mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: duplicates price level of active ${duplicatePriceOrder.id} (${duplicatePriceOrder.orderId} at ${duplicatePriceOrder.price})${suffix}`, level);
1289
- queueCorrection({ gridOrder: duplicatePriceOrder, chainOrderId, expectedPrice: chainOrder.price, size: chainOrder.size, type: chainOrder.type, isSurplus: true, cancelOnly: true });
1236
+ mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: duplicates slot ${slotId} (${occupying.orderId})${suffix}`, level);
1237
+ queueCorrection({ gridOrder: occupying, chainOrderId, expectedPrice: chainOrder.price, size: chainOrder.size, type: chainOrder.type, isSurplus: true, cancelOnly: true });
1290
1238
  continue;
1291
1239
  }
1292
- const match = findMatchingGridOrderByOpenOrder({ orderId: chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size }, { orders: mgr.orders, assets: mgr.assets, calcToleranceFn: (p, s, t) => calculatePriceTolerance(p, s, t, mgr.assets), logger: mgr.logger, allowSmallerChainSize: true, requireAvailableSlot: true, excludeGridOrderIds: matchedGridOrderIds });
1293
- if (match && !matchedGridOrderIds.has(match.id)) {
1294
- const adopted = await adoptChainOrderIntoSlot(mgr, match, chainOrder, chainOrderId, rawChainOrders, matchedGridOrderIds, chainOrderIdsOnGrid, filledOrders, updatedOrders, skipAccounting);
1295
- if (!adopted) {
1296
- unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'adoption-rejected', candidateSlotId: match.id });
1297
- queueCorrection({ gridOrder: match, chainOrderId, expectedPrice: chainOrder.price, size: chainOrder.size, type: chainOrder.type, isSurplus: true, cancelOnly: true });
1298
- mgr.logger?.log?.(`[SYNC] Chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}) NOT adopted into slot ${match.id}: order update rejected — queued for cancellation`, 'error');
1240
+ // Gap exclusion: nearest slot in SPREAD gap → no adopt (boundary
1241
+ // is known here — the pre-boundary case continued above).
1242
+ {
1243
+ const inRail = isSlotInRail(boundaryIdx, gapSlots, chainOrder.type, { id: slotId });
1244
+ if (!inRail) {
1245
+ unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'no-available-nearest-slot', candidateSlotId: slotId });
1246
+ queueCorrection({ gridOrder: { id: slotId, type: chainOrder.type }, chainOrderId, expectedPrice: chainOrder.price, size: chainOrder.size, type: chainOrder.type, isSurplus: true, cancelOnly: true });
1247
+ continue;
1299
1248
  }
1300
1249
  }
1301
- else if (match) {
1302
- mgr.logger?.log?.(`Warning: Orphan chain order ${chainOrderId} matched grid order ${match.id}, but grid order was already matched to another chain order. Queuing orphan for cancellation.`, 'warn');
1303
- queueCorrection({ gridOrder: match, chainOrderId, expectedPrice: chainOrder.price, size: chainOrder.size, type: chainOrder.type, isSurplus: true, cancelOnly: true });
1304
- unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'already-matched-slot', candidateSlotId: match.id });
1250
+ const slot = mgr.orders.get(slotId);
1251
+ if (!slot || matchedGridOrderIds.has(slot.id) || slot.orderId) {
1252
+ unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'no-available-nearest-slot', candidateSlotId: slotId });
1253
+ const diag = describeNearestAdoptionCandidates(mgr, chainOrder, (chainOrder.type === ORDER_TYPES.SELL ? assetAPrecision : assetBPrecision), matchedGridOrderIds);
1254
+ mgr.logger?.log?.(`[SYNC] Unmatched chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}): nearest slot ${slotId} not adoptable. Nearest candidates: ${diag}`, 'warn');
1255
+ continue;
1305
1256
  }
1306
- else {
1307
- // Legacy spread-orphan fallback: adopt into nearest VIRTUAL/spread slot (allowSpreadType + skipSizeMatch) with widened tolerance
1308
- const adoptedSlot = findMatchingGridOrderByOpenOrder({ orderId: chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size }, {
1309
- orders: mgr.orders,
1310
- assets: mgr.assets,
1311
- calcToleranceFn: (p, s, t) => {
1312
- const strict = calculatePriceTolerance(p, s, t, mgr.assets);
1313
- const mult = mgr?.config?.gridLimits?.ORPHAN_ADOPTION_TOLERANCE_MULTIPLIER || 4;
1314
- return strict == null ? null : strict * mult;
1315
- },
1316
- allowSpreadType: true,
1317
- skipSizeMatch: true,
1318
- requireAvailableSlot: true,
1319
- excludeGridOrderIds: matchedGridOrderIds
1320
- });
1321
- if (adoptedSlot && !matchedGridOrderIds.has(adoptedSlot.id) && !adoptedSlot.orderId) {
1322
- const precision = (chainOrder.type === ORDER_TYPES.SELL) ? assetAPrecision : assetBPrecision;
1323
- // Legacy path parity with the genesis adoption path: the
1324
- // slot's price is its GENESIS level and is never overwritten
1325
- // with the chain order's price. Adopting chainOrder.price
1326
- // here made the slot's price whichever price happened to be
1327
- // on the book, which is how an off-grid order could become a
1328
- // grid level and then be re-emitted as a plan price. The
1329
- // size below is still the chain value: size is real state,
1330
- // price is a ladder position.
1331
- const legacyRail = isSlotInRail(mgr.boundaryIdx, mgr._gapSlots ?? 0, chainOrder.type, adoptedSlot);
1332
- if (!legacyRail) {
1333
- unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'out-of-rail-deferred', candidateSlotId: adoptedSlot.id });
1334
- mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted into slot ${adoptedSlot.id}: slot is outside the active rail for a ${chainOrder.type}; deferred`, 'warn');
1335
- continue;
1336
- }
1337
- const chainInt = floatToBlockchainInt(chainOrder.size, precision);
1338
- const adoptedRaw = rawChainOrders.get(chainOrderId);
1339
- const adoptedState = chainInt > 0 ? ORDER_STATES.PARTIAL : ORDER_STATES.VIRTUAL;
1340
- const adoptedBtsFeeState = (adoptedRaw) ? (() => {
1341
- const rawFee = toFiniteNumber(adoptedRaw.deferred_fee, null);
1342
- return rawFee !== null && rawFee > 0 ? { deferredFee: blockchainToFloat(rawFee, BTS_PRECISION) } : undefined;
1343
- })() : undefined;
1344
- // ADOPTION NEVER TAKES THE CHAIN ORDER'S PRICE (legacy parity).
1345
- //
1346
- // Same rule as adoptChainOrderIntoSlot, stated here because
1347
- // this path is the one that used to get it wrong: it set
1348
- // `price: chainOrder.price`, so a slot's id and its price
1349
- // could disagree — an off-grid order became a grid level and
1350
- // was then re-emitted as a plan price (S1).
1351
- //
1352
- // `...adoptedSlot` below carries the slot's own level and
1353
- // `price` is deliberately NOT reassigned. A differing
1354
- // chainOrder.price is expected (a regeneration leaves old
1355
- // orders resting at old levels) and is not corruption; it
1356
- // simply is not this slot's price.
1357
- //
1358
- // Size differs: size is real state, so the chain value is
1359
- // adopted. Price is a ladder position; it is not.
1360
- const adoptedOrder = {
1361
- ...adoptedSlot,
1362
- orderId: chainOrderId,
1363
- type: chainOrder.type,
1364
- state: adoptedState,
1365
- size: chainOrder.size,
1366
- rawOnChain: adoptedRaw ? { ...adoptedRaw, fetchedAt: Date.now() } : adoptedRaw,
1367
- ...(adoptedBtsFeeState ? { btsFeeState: adoptedBtsFeeState } : {}),
1368
- };
1369
- adoptedSlotKeepsItsOwnPrice(mgr, adoptedOrder, chainOrderId, 'legacy-fallback');
1370
- const applied = await mgr._applyOrderUpdate(adoptedOrder, 'sync-pass2-adopt-orphan', { skipAccounting: skipAccounting, fee: 0 });
1371
- if (applied === false) {
1372
- // Fatal rejection: parity with the genesis adoption path —
1373
- // the slot must not be marked matched and the chain order
1374
- // must not dangle untracked on the book.
1375
- unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'adoption-rejected', candidateSlotId: adoptedSlot.id });
1376
- queueCorrection({ gridOrder: adoptedSlot, chainOrderId, expectedPrice: chainOrder.price, size: chainOrder.size, type: chainOrder.type, isSurplus: true, cancelOnly: true });
1377
- mgr.logger?.log?.(`[SYNC] Chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}) NOT adopted into slot ${adoptedSlot.id}: order update rejected — queued for cancellation`, 'error');
1378
- continue;
1379
- }
1380
- matchedGridOrderIds.add(adoptedSlot.id);
1381
- chainOrderIdsOnGrid.add(chainOrderId);
1382
- updatedOrders.push(adoptedOrder);
1383
- // Phase 4 attribution: log the adoption slot's geometry
1384
- // (idx vs frozen boundary/gap) so the next re-map incident
1385
- // can tell an in-rail adoption from a gap-band re-map
1386
- // without on-chain archaeology.
1387
- let adoptGeo = '';
1388
- try {
1389
- const adoptIdx = parseSlotIndex(adoptedSlot.id);
1390
- const adoptB = Number(mgr?.boundaryIdx);
1391
- const adoptG = Number(mgr?._gapSlots);
1392
- if (adoptIdx !== null && adoptIdx !== undefined && Number.isFinite(adoptB) && Number.isFinite(adoptG)) {
1393
- const inBand = isSlotIndexInGapBand(adoptIdx, adoptB, adoptG);
1394
- adoptGeo = ` geo(idx=${adoptIdx},boundary=${adoptB},gap=${adoptG},sellStart=${getSellStartIdx(adoptB, adoptG)},band=${inBand ? 'gap' : 'rail'})`;
1395
- }
1396
- }
1397
- catch { /* geometry is diagnostic-only */ }
1398
- mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) adopted into slot ${adoptedSlot.id} (was ${adoptedSlot.type})${adoptGeo}`, 'warn');
1399
- }
1400
- else {
1401
- const precision = (chainOrder.type === ORDER_TYPES.SELL) ? assetAPrecision : assetBPrecision;
1402
- const candidateDiagnostics = describeNearestAdoptionCandidates(mgr, chainOrder, precision, (p, s, t) => calculatePriceTolerance(p, s, t, mgr.assets), matchedGridOrderIds);
1403
- const driftTag = computeOutOfToleranceDriftTag(mgr, chainOrder, (p, s, t) => calculatePriceTolerance(p, s, t, mgr.assets));
1404
- const unmatchedEntry = { chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), candidateDiagnostics };
1405
- if (driftTag) {
1406
- unmatchedEntry.reason = 'price-drift-orphan';
1407
- unmatchedEntry.candidateSlotId = driftTag.candidateSlotId;
1408
- unmatchedEntry.candidateSlotPrice = driftTag.candidateSlotPrice;
1409
- unmatchedEntry.priceDiff = driftTag.priceDiff;
1410
- unmatchedEntry.tolerance = driftTag.tolerance;
1411
- }
1412
- unmatchedChainOrders.push(unmatchedEntry);
1413
- mgr.logger?.log?.(`[SYNC] Unmatched chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}): no adoptable slot found` + (driftTag ? ` (price-drift-orphan slot=${driftTag.candidateSlotId}@${driftTag.candidateSlotPrice} diff=${driftTag.priceDiff} tol=${driftTag.tolerance})` : '') + `. Nearest candidates: ${candidateDiagnostics}`, 'warn');
1414
- }
1257
+ const typeCompat = slot.type === chainOrder.type || slot.type === ORDER_TYPES.SPREAD;
1258
+ if (!typeCompat) {
1259
+ unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'no-available-nearest-slot', candidateSlotId: slotId });
1260
+ continue;
1261
+ }
1262
+ const adopted = await adoptChainOrderIntoSlot(mgr, slot, chainOrder, chainOrderId, rawChainOrders, matchedGridOrderIds, chainOrderIdsOnGrid, filledOrders, updatedOrders, skipAccounting);
1263
+ if (!adopted) {
1264
+ // Order update was rejected (fatal validation) — the chain
1265
+ // order stays untracked and must not dangle on the book.
1266
+ unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'adoption-rejected', candidateSlotId: slotId });
1267
+ queueCorrection({ gridOrder: slot, chainOrderId, expectedPrice: chainOrder.price, size: chainOrder.size, type: chainOrder.type, isSurplus: true, cancelOnly: true });
1268
+ mgr.logger?.log?.(`[SYNC] Chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}) NOT adopted into slot ${slotId}: order update rejected — queued for cancellation`, 'error');
1415
1269
  }
1416
1270
  }
1417
1271
  return { filledOrders, updatedOrders, ordersNeedingCorrection, unmatchedChainOrders };
@@ -2084,6 +1938,56 @@ class SyncEngine {
2084
1938
  * @param {string} source - Source identifier ('createOrder', 'cancelOrder', 'readOpenOrders', etc.)
2085
1939
  * @returns {Promise<Object>} { newOrders, ordersNeedingCorrection }
2086
1940
  */
1941
+ /**
1942
+ * E2 invariant assert: a manager holding grid slots but no price ladder is
1943
+ * in the undefined state the grid-price invariant forbids (INV-GRID-004).
1944
+ *
1945
+ * Reports once per grid generation (latched on the manager, counted in
1946
+ * `_genesisInvariantViolations`) and, when the bot wired the structural
1947
+ * resync, requests one so the ladder is re-derived. Returns FALSE so the
1948
+ * caller ABORTS the sync untouched: with no ladder there is no authority for
1949
+ * a slot's price, and the legacy tolerance matcher that used to cover this
1950
+ * state is gone — continuing would let an off-grid chain price be adopted
1951
+ * into a slot.
1952
+ *
1953
+ * Non-throwing on purpose: the load-side gates (E1/E3) own the fail-closed
1954
+ * decision, this one makes a bypass loud without stranding a live manager.
1955
+ * @param {any} mgr - OrderManager instance
1956
+ * @returns {boolean} true when the grid may be synced (no slots, or a usable
1957
+ * ladder is present); false when the sync must not run.
1958
+ */
1959
+ _assertGenesisInvariant(mgr) {
1960
+ try {
1961
+ const orders = mgr?.orders;
1962
+ const slotCount = orders instanceof Map ? orders.size : (Array.isArray(orders) ? orders.length : 0);
1963
+ if (slotCount === 0)
1964
+ return true;
1965
+ if (hasGenesisLadder(mgr._genesis))
1966
+ return true;
1967
+ const count = (mgr._genesisInvariantViolations || 0) + 1;
1968
+ mgr._genesisInvariantViolations = count;
1969
+ const fault = mgr._missingGenesis;
1970
+ if (count > 1)
1971
+ return false; // already reported for this generation
1972
+ mgr._genesisInvariantLoggedAt = Date.now();
1973
+ mgr.logger?.log?.(`[GENESIS] INVARIANT: sync REFUSED against ${slotCount} grid slot(s) with NO price ladder` +
1974
+ (fault ? ` (refused earlier: ${fault.reason} — ${fault.detail})` : '') +
1975
+ `. Slot prices have no authority, so no chain order is matched, adopted or corrected this cycle. ` +
1976
+ `A structural resync re-derives the ladder.`, 'error');
1977
+ if (typeof mgr.requestStructuralGridResync === 'function') {
1978
+ Promise.resolve(mgr.requestStructuralGridResync('missing-genesis', { violations: count }))
1979
+ .catch((err) => {
1980
+ mgr.logger?.log?.(`[GENESIS] Structural resync request failed: ${getErrorMessage(err)}`, 'warn');
1981
+ });
1982
+ }
1983
+ return false;
1984
+ }
1985
+ catch {
1986
+ // Never let observability break a sync — but an unevaluatable
1987
+ // check must not hand a ladder-less grid to the reconciler either.
1988
+ return false;
1989
+ }
1990
+ }
2087
1991
  async synchronizeWithChain(chainData, source) {
2088
1992
  const mgr = this.manager;
2089
1993
  if (!mgr.assets)
@@ -2190,17 +2094,51 @@ class SyncEngine {
2190
2094
  // disagreeing in one order object.
2191
2095
  const materializeIdx = parseSlotIndex(gridOrderId);
2192
2096
  let ladderLevel = null;
2097
+ // Distinguish the two reasons the ladder cannot
2098
+ // price this slot, so the fault log names the
2099
+ // real one: a missing ladder (INV-GRID-004) vs a
2100
+ // ladder that exists but does not address this
2101
+ // index (out-of-range slot id).
2102
+ let ladderFault = null;
2193
2103
  try {
2194
2104
  const genesis = mgr._genesis;
2195
- if (materializeIdx !== null && Array.isArray(genesis?.priceLevels) && genesis.priceLevels.length > 0) {
2196
- const onLadder = Number(priceForSlot(materializeIdx, genesis));
2197
- if (Number.isFinite(onLadder) && onLadder > 0)
2198
- ladderLevel = onLadder;
2105
+ if (materializeIdx !== null) {
2106
+ if (hasGenesisLadder(genesis)) {
2107
+ const onLadder = Number(priceForSlot(materializeIdx, genesis));
2108
+ if (Number.isFinite(onLadder) && onLadder > 0)
2109
+ ladderLevel = onLadder;
2110
+ else
2111
+ ladderFault = 'out-of-range';
2112
+ }
2113
+ else {
2114
+ ladderFault = 'missing-ladder';
2115
+ }
2116
+ }
2117
+ }
2118
+ catch {
2119
+ ladderFault = 'out-of-range';
2120
+ }
2121
+ // A `slot-N` id the ladder cannot price leaves the
2122
+ // slot with no authority for its price, so the
2123
+ // descriptor can only be a stopgap. Keep the live
2124
+ // chain order tracked (stranding it would be
2125
+ // worse) but make the fault loud and ask for the
2126
+ // ladder/slot to be re-derived, which re-prices
2127
+ // the slot on reload.
2128
+ if (materializeIdx !== null && ladderLevel === null) {
2129
+ const reason = ladderFault === 'out-of-range'
2130
+ ? `slot index ${materializeIdx} is outside the price ladder (${hasGenesisLadder(mgr._genesis) ? 'the ladder exists but does not address this slot' : 'no usable ladder'}); the slot id and ladder disagree`
2131
+ : 'the grid has no price ladder (INV-GRID-004)';
2132
+ mgr.logger?.log?.(`[GENESIS] createOrder materialized ${gridOrderId} from the placement descriptor ` +
2133
+ `because ${reason} — the slot price is unverified ` +
2134
+ `and will be re-derived on the next grid build`, 'error');
2135
+ if (typeof mgr.requestStructuralGridResync === 'function') {
2136
+ Promise.resolve(mgr.requestStructuralGridResync('missing-genesis', { reason: 'createOrder-materialize' }))
2137
+ .catch((err) => mgr.logger?.log?.(`[GENESIS] Structural resync request failed: ${getErrorMessage(err)}`, 'warn'));
2199
2138
  }
2200
2139
  }
2201
- catch { /* fall back to the descriptor below */ }
2202
- // Only fall back to the descriptor when the ladder
2203
- // cannot speak (migration / unparseable id).
2140
+ // Only fall back to the descriptor price when the
2141
+ // ladder cannot address the slot (unparseable id).
2204
2142
  if (!materializeType && Number.isFinite(descriptorPrice)) {
2205
2143
  const sidePrice = ladderLevel ?? descriptorPrice;
2206
2144
  materializeType = resolveSpreadOrderSide(sidePrice, mgr.config.startPrice);
@@ -2229,9 +2167,9 @@ class SyncEngine {
2229
2167
  // and for a slot being materialized at a new
2230
2168
  // index it can be a price from a different
2231
2169
  // grid entirely. The descriptor price is kept
2232
- // only when genesis is unavailable
2233
- // (migration), where there is no ladder to
2234
- // derive from.
2170
+ // only when the ladder cannot address the slot
2171
+ // (unparseable id, or the undefined-grid fault
2172
+ // logged above).
2235
2173
  let materializePrice = descriptorPrice;
2236
2174
  let priceSource = 'descriptor';
2237
2175
  if (ladderLevel !== null && materializeIdx !== null) {
@@ -2246,10 +2184,10 @@ class SyncEngine {
2246
2184
  state: isPartialPlacement ? ORDER_STATES.PARTIAL : ORDER_STATES.ACTIVE,
2247
2185
  orderId: chainOrderId,
2248
2186
  };
2249
- if (priceSource === 'descriptor' && materializeIdx !== null) {
2187
+ if (priceSource === 'descriptor' && materializeIdx === null) {
2250
2188
  mgr.logger?.log?.(`[SYNC] createOrder for ${gridOrderId}: materialized with the DESCRIPTOR price ` +
2251
- `${descriptorPrice} because no genesis ladder was available to derive ` +
2252
- `the slot level — verify this slot's price on the next sync`, 'warn');
2189
+ `${descriptorPrice} because the grid order id is not a slot-N addressable by the ` +
2190
+ `price ladder — verify this slot's price on the next sync`, 'warn');
2253
2191
  }
2254
2192
  if (chainData.deferredFee !== undefined && chainData.deferredFee !== null) {
2255
2193
  materializedOrder.btsFeeState = { deferredFee: Math.max(0, chainData.deferredFee) };
@@ -2301,7 +2239,9 @@ class SyncEngine {
2301
2239
  };
2302
2240
  }
2303
2241
  const runCancel = async () => {
2304
- const gridOrder = findMatchingGridOrderByOpenOrder({ orderId }, { orders: mgr.orders, assets: mgr.assets, calcToleranceFn: (p, s, t) => calculatePriceTolerance(p, s, t, mgr.assets), logger: mgr.logger });
2242
+ // Linkage is by chain orderId (authoritative) — no price matching: the slot
2243
+ // that owns this order id is the slot, whatever its level.
2244
+ const gridOrder = Array.from(mgr.orders.values()).find((o) => o && o.orderId === orderId);
2305
2245
  if (gridOrder) {
2306
2246
  // Lock both chain orderId and grid order ID to prevent concurrent modifications
2307
2247
  const orderIds = [orderId, gridOrder.id].filter(Boolean);