dexbot 1.6.12 → 1.6.14

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 (213) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/README.md +2 -2
  3. package/analysis/README.md +9 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/claw/README.md +1 -0
  6. package/claw/docs/AI_BOT_LIBRARY_API.md +3 -1
  7. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  8. package/claw/modules/claw_bridge.ts +0 -3
  9. package/claw/modules/claw_catalog.ts +8 -4
  10. package/claw/modules/claw_skill_md.ts +1 -0
  11. package/claw/modules/dexbot_profiles.ts +59 -15
  12. package/claw/modules/types.ts +2 -1
  13. package/claw/package.json +3 -3
  14. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  15. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  16. package/claw/skills/margin-trading/SKILL.md +1 -1
  17. package/claw/skills/margin-trading/references/position-management.md +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  20. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  21. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  22. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  23. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  24. package/dist/analysis/analyze_args.d.ts +12 -0
  25. package/dist/analysis/analyze_args.js +20 -0
  26. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  27. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  28. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  29. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  30. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  31. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  32. package/dist/analysis/chart_ui.d.ts +30 -1
  33. package/dist/analysis/chart_ui.js +37 -1
  34. package/dist/analysis/fills_cache.d.ts +3 -23
  35. package/dist/analysis/fills_cache.js +3 -84
  36. package/dist/analysis/fills_source.d.ts +31 -1
  37. package/dist/analysis/fills_source.js +69 -1
  38. package/dist/analysis/grid_correction_check.d.ts +1 -23
  39. package/dist/analysis/grid_correction_check.js +15 -58
  40. package/dist/analysis/math_utils.d.ts +85 -1
  41. package/dist/analysis/math_utils.js +116 -1
  42. package/dist/analysis/price_sources.d.ts +22 -1
  43. package/dist/analysis/price_sources.js +23 -0
  44. package/dist/analysis/resolve_source.js +31 -10
  45. package/dist/analysis/trade_profitability.d.ts +6 -0
  46. package/dist/analysis/trade_profitability.js +23 -97
  47. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  48. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  49. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +27 -40
  50. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  51. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  52. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  53. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  54. package/dist/analysis/worker_pool.d.ts +38 -0
  55. package/dist/analysis/worker_pool.js +67 -0
  56. package/dist/dexbot.js +67 -48
  57. package/dist/market_adapter/ama_signal_runner.js +21 -54
  58. package/dist/market_adapter/candle_utils.d.ts +7 -1
  59. package/dist/market_adapter/candle_utils.js +11 -1
  60. package/dist/market_adapter/cli_args.d.ts +22 -0
  61. package/dist/market_adapter/cli_args.js +30 -0
  62. package/dist/market_adapter/core/config_normalizers.js +11 -6
  63. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  64. package/dist/market_adapter/core/kibana_candles.js +3 -2
  65. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  66. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  67. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  68. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  69. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  70. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  71. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  72. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  73. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  74. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  75. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  76. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  77. package/dist/market_adapter/inputs/window_cache.js +52 -177
  78. package/dist/market_adapter/interval_utils.d.ts +11 -1
  79. package/dist/market_adapter/interval_utils.js +16 -1
  80. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  81. package/dist/market_adapter/lp_chart_runner.js +37 -19
  82. package/dist/market_adapter/market_adapter.js +27 -72
  83. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  84. package/dist/market_adapter/utils/data_discovery.js +220 -27
  85. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  86. package/dist/market_adapter/utils/month_shards.js +237 -0
  87. package/dist/modules/account_bots.d.ts +8 -6
  88. package/dist/modules/account_bots.js +112 -131
  89. package/dist/modules/account_orders.d.ts +49 -4
  90. package/dist/modules/account_orders.js +114 -49
  91. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  92. package/dist/modules/bitshares-native/chain_client.js +14 -13
  93. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  94. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  95. package/dist/modules/bitshares-native/resolvers.js +22 -25
  96. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  97. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  98. package/dist/modules/bitshares-native/serial/types.js +22 -50
  99. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  100. package/dist/modules/bot_defaults.d.ts +18 -3
  101. package/dist/modules/bot_defaults.js +34 -8
  102. package/dist/modules/bot_settings.d.ts +5 -1
  103. package/dist/modules/bot_settings.js +55 -21
  104. package/dist/modules/broadcast_failure.d.ts +2 -1
  105. package/dist/modules/chain_orders.d.ts +1 -1
  106. package/dist/modules/chain_orders.js +51 -96
  107. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  108. package/dist/modules/config.js +6 -1
  109. package/dist/modules/constants.d.ts +14 -6
  110. package/dist/modules/constants.js +32 -6
  111. package/dist/modules/cr_planner.d.ts +1 -1
  112. package/dist/modules/cr_planner.js +1 -5
  113. package/dist/modules/credit_pricing.d.ts +2 -1
  114. package/dist/modules/credit_pricing.js +36 -40
  115. package/dist/modules/credit_runtime.d.ts +7 -0
  116. package/dist/modules/credit_runtime.js +45 -73
  117. package/dist/modules/daemon_node_health.d.ts +4 -3
  118. package/dist/modules/dexbot_class.d.ts +33 -17
  119. package/dist/modules/dexbot_class.js +113 -61
  120. package/dist/modules/dexbot_cow_runtime.d.ts +62 -181
  121. package/dist/modules/dexbot_cow_runtime.js +380 -69
  122. package/dist/modules/dexbot_credential_client.d.ts +1 -23
  123. package/dist/modules/dexbot_credential_client.js +2 -3
  124. package/dist/modules/dexbot_fill_runtime.d.ts +2 -3
  125. package/dist/modules/dexbot_fill_runtime.js +17 -7
  126. package/dist/modules/dexbot_maintenance_runtime.d.ts +36 -81
  127. package/dist/modules/dexbot_maintenance_runtime.js +137 -133
  128. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  129. package/dist/modules/dexbot_startup_runtime.js +25 -14
  130. package/dist/modules/dexbot_state_recovery.js +16 -0
  131. package/dist/modules/general_settings.d.ts +1 -1
  132. package/dist/modules/graceful_shutdown.js +17 -11
  133. package/dist/modules/key_store.d.ts +0 -5
  134. package/dist/modules/key_store.js +1 -2
  135. package/dist/modules/lazy_shim.d.ts +11 -0
  136. package/dist/modules/lazy_shim.js +16 -0
  137. package/dist/modules/node_connect_policy.d.ts +3 -2
  138. package/dist/modules/node_failure_ledger.d.ts +6 -5
  139. package/dist/modules/order/accounting.js +11 -11
  140. package/dist/modules/order/export.js +2 -2
  141. package/dist/modules/order/format.d.ts +26 -3
  142. package/dist/modules/order/format.js +33 -3
  143. package/dist/modules/order/genesis_policy.d.ts +4 -4
  144. package/dist/modules/order/genesis_policy.js +6 -3
  145. package/dist/modules/order/grid.d.ts +26 -12
  146. package/dist/modules/order/grid.js +468 -80
  147. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  148. package/dist/modules/order/grid_reconcile.js +5 -5
  149. package/dist/modules/order/grid_reconcile_internal.js +48 -40
  150. package/dist/modules/order/index.d.ts +35 -8
  151. package/dist/modules/order/logger.d.ts +1 -8
  152. package/dist/modules/order/logger.js +2 -11
  153. package/dist/modules/order/manager.d.ts +18 -15
  154. package/dist/modules/order/manager.js +91 -74
  155. package/dist/modules/order/strategy.d.ts +2 -2
  156. package/dist/modules/order/strategy.js +51 -21
  157. package/dist/modules/order/sync_engine.js +4 -0
  158. package/dist/modules/order/utils/math.d.ts +3 -3
  159. package/dist/modules/order/utils/math.js +38 -27
  160. package/dist/modules/order/utils/order.d.ts +58 -58
  161. package/dist/modules/order/utils/order.js +158 -137
  162. package/dist/modules/order/utils/system.d.ts +202 -35
  163. package/dist/modules/order/utils/system.js +409 -31
  164. package/dist/modules/order/utils/validate.js +28 -6
  165. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  166. package/dist/modules/paths.js +32 -34
  167. package/dist/modules/runtime_settings.d.ts +3 -5
  168. package/dist/modules/runtime_settings.js +3 -3
  169. package/dist/modules/settings_merge.d.ts +2 -2
  170. package/dist/modules/socket_json_client.d.ts +2 -1
  171. package/dist/modules/types.d.ts +89 -30
  172. package/dist/modules/utils/errors.js +1 -3
  173. package/dist/modules/version_notice.d.ts +11 -10
  174. package/dist/pm2.d.ts +0 -1
  175. package/dist/pm2.js +56 -35
  176. package/dist/scripts/analyze-git.js +2 -15
  177. package/dist/scripts/analyze-orders.d.ts +1 -1
  178. package/dist/scripts/analyze-orders.js +4 -4
  179. package/dist/scripts/chart_command.js +2 -2
  180. package/dist/scripts/check_any.d.ts +4 -0
  181. package/dist/scripts/check_any.js +53 -21
  182. package/dist/scripts/diagnose-pool-history.js +1 -6
  183. package/dist/scripts/divergence-calc.js +6 -6
  184. package/dist/scripts/run-tests.js +0 -1
  185. package/dist/scripts/sync-version.js +0 -10
  186. package/dist/scripts/validate_bots.d.ts +1 -1
  187. package/dist/scripts/validate_bots.js +3 -3
  188. package/dist/unlock.js +7 -2
  189. package/docs/BITSHARES_ONBOARDING.md +8 -12
  190. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -3
  191. package/docs/COW_INVARIANTS.md +6 -6
  192. package/docs/DEXBOT_COMPARISON.md +7 -7
  193. package/docs/EVOLUTION.md +10 -8
  194. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  195. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  196. package/docs/GRID_RECALCULATION.md +4 -1
  197. package/docs/GRID_RECONCILE.md +4 -4
  198. package/docs/LIFECYCLE.md +11 -11
  199. package/docs/LOGGING.md +14 -0
  200. package/docs/MPA_CREDIT_USAGE.md +1 -1
  201. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +12 -4
  202. package/docs/README.md +3 -3
  203. package/docs/WORKFLOW.md +1 -0
  204. package/docs/architecture.md +25 -16
  205. package/docs/developer_guide.md +7 -2
  206. package/market_adapter/README.md +6 -4
  207. package/package.json +6 -9
  208. package/scripts/README.md +43 -38
  209. package/tests/README.md +26 -11
  210. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  211. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  212. package/scripts/git-viewer.sh +0 -489
  213. package/scripts/postinstall.js +0 -16
@@ -50,14 +50,14 @@ const require = createRequire(import.meta.url);
50
50
  import { path } from '../../path_api.js';
51
51
  import { getStorage } from '../../storage/index.js';
52
52
  const storage = getStorage();
53
- import { API_LIMITS, ORDER_TYPES, COW_ACTIONS, FEE_PARAMETERS, BTS_PRECISION, PIPELINE_TIMING, NATIVE_CLIENT, GRID_LIMITS } from '../../constants.js';
53
+ import { API_LIMITS, ORDER_TYPES, COW_ACTIONS, FEE_PARAMETERS, BTS_PRECISION, PIPELINE_TIMING, NATIVE_CLIENT, GRID_LIMITS, TIMING } from '../../constants.js';
54
54
  import { PATHS } from '../../paths.js';
55
- import { toFiniteNumber, isValidNumber } from '../format.js';
55
+ import { toFiniteNumber, isValidNumber, toKnownNumber } from '../format.js';
56
56
  import * as MathUtils from './math.js';
57
57
  import * as OrderUtils from './order.js';
58
58
  import Logger from '../../order/logger.js';
59
59
  import { runtime } from '../../runtime.js';
60
- import { getErrorMessage } from '../../utils/errors.js';
60
+ import { getErrorMessage, sleepMs } from '../../utils/errors.js';
61
61
  import { normalizeAssetRef } from '../../utils/asset_symbols.js';
62
62
  import { withTimeout } from './timeout.js';
63
63
  const { ensureDir, readJSON } = storage;
@@ -900,12 +900,15 @@ export async function persistGridSnapshot(manager, accountOrders, snapshotOrders
900
900
  // treats as an explicit clear; the row carries the CURRENT live
901
901
  // genesis hash so a restore that sees a re-derived genesis refuses it.
902
902
  const lastFillPivot = buildLastFillPivotPayload(manager);
903
+ // Bot-scoped market-fill reference: survives grid regeneration, used
904
+ // by spread correction as the price it must not trade through.
905
+ const lastMarketFill = buildLastMarketFillPayload(manager);
903
906
  await accountOrders.storeMasterGrid(orders, btsFeesOwed, manager.boundaryIdx, manager.assets || null, {
904
907
  persistedAt: nowIso(),
905
908
  config: debugConfig,
906
909
  accountTotals,
907
910
  btsBalance
908
- }, fillKeys, genesis, gapEvacStreaks, pendingFillCrawls, lastFillPivot);
911
+ }, fillKeys, genesis, gapEvacStreaks, pendingFillCrawls, lastFillPivot, lastMarketFill);
909
912
  return true;
910
913
  }
911
914
  catch (e) {
@@ -977,36 +980,385 @@ function buildLastFillPivotPayload(manager) {
977
980
  return { price, type, fillsAt, genesisHash };
978
981
  }
979
982
  /**
980
- * Normalize a persisted LAST-FILL-GUARD pivot row (shared by the
981
- * AccountOrders sanitizer/loader and the payload builder's row contract).
983
+ * Build the persist payload for the bot-scoped last-market-fill reference.
984
+ *
985
+ * Unlike buildLastFillPivotPayload this row has NO genesis binding and is
986
+ * never cleared by a grid regeneration/rejection: it records the last price
987
+ * the ACCOUNT traded at, which is market truth independent of the current
988
+ * grid. Returns `undefined` (storeMasterGrid no-op) while cold so a cold
989
+ * manager never erases a previously stored row; the restore path applies the
990
+ * TTL and drops an expired row instead.
991
+ *
992
+ * @param {Object} manager - OrderManager instance
993
+ * @returns {{price:number,type:string,fillsAt:number}|undefined} Row, or undefined to leave untouched
994
+ */
995
+ function buildLastMarketFillPayload(manager) {
996
+ const price = Number(manager?._lastMarketFillPrice);
997
+ const type = manager?._lastMarketFillType;
998
+ const fillsAt = Number(manager?._lastMarketFillAt);
999
+ if (!Number.isFinite(price) || price <= 0)
1000
+ return undefined;
1001
+ if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
1002
+ return undefined;
1003
+ if (!Number.isFinite(fillsAt) || fillsAt <= 0)
1004
+ return undefined;
1005
+ return { price, type, fillsAt };
1006
+ }
1007
+ /**
1008
+ * The single freshness window shared by the spread-correction trust decisions
1009
+ * that are time-based: snapshot staleness (and therefore the COW bypass) and
1010
+ * the live-market-price refresh pacing. Resolved once so a per-bot
1011
+ * `config.timing` override cannot make one check trust what another rejects.
1012
+ * The crossing floor itself does NOT use a time window — it picks the newer
1013
+ * of the live read and the fill.
1014
+ *
1015
+ * 0 (constant unset) => no time bound: staleness never triggers and the
1016
+ * live-price refresh is never forced, so the crossing floor stays on the fill
1017
+ * anchor. Fail-open, matching the never-synced first-tick behavior.
1018
+ *
1019
+ * @param {Object} manager - OrderManager instance
1020
+ * @returns {number} Freshness window in ms (0 => no bound => fail-open)
1021
+ */
1022
+ export function resolveSpreadFreshnessMs(manager) {
1023
+ const configured = Number(manager?.config?.timing?.SPREAD_CORRECTION_SYNC_FRESH_MS);
1024
+ if (configured > 0)
1025
+ return configured;
1026
+ const fallback = Number(TIMING?.SPREAD_CORRECTION_SYNC_FRESH_MS);
1027
+ return fallback > 0 ? fallback : 0;
1028
+ }
1029
+ /**
1030
+ * Resolve the crossing floor spread correction must not trade through.
1031
+ *
1032
+ * Two pieces of real market evidence can supply the floor: an externally
1033
+ * observed live price (order book/ticker) and the fill-derived reference
1034
+ * (last account trade). Neither is judged by a threshold — the NEWER one wins.
1035
+ * A live read older than the last fill loses to the fill (an executed trade is
1036
+ * fresher market truth); a live read at least as new wins; with no live read
1037
+ * at all the fill is used; with neither the floor is null (fail-open).
1038
+ *
1039
+ * This is what lets us drop the arbitrary "how far is too far" distance cap:
1040
+ * we keep the floor fresh and compare evidence by recency, rather than guessing
1041
+ * when an old floor went stale.
1042
+ *
1043
+ * @param {Object} manager - OrderManager instance
1044
+ * @returns {number|null} Crossing floor or null (fail-open)
1045
+ */
1046
+ export function resolveSpreadCrossingFloor(manager) {
1047
+ const fill = resolveSpreadMarketReference(manager);
1048
+ const live = Number(manager?._liveMarketPrice);
1049
+ const liveAt = Number(manager?._liveMarketPriceAt);
1050
+ const liveValid = Number.isFinite(live) && live > 0 && Number.isFinite(liveAt) && liveAt > 0;
1051
+ if (!liveValid)
1052
+ return fill;
1053
+ const fillAt = Math.max(Number(manager?._lastFilledAt) || 0, Number(manager?._lastMarketFillAt) || 0);
1054
+ if (fill == null || fillAt <= 0 || liveAt >= fillAt)
1055
+ return live;
1056
+ return fill;
1057
+ }
1058
+ /**
1059
+ * Refresh the cached live market price from the order book/ticker.
1060
+ * Best-effort; caches only a finite positive price. Returns the new price or
1061
+ * null. Call through maybeRefreshLiveMarketPrice to respect the pacing bound.
1062
+ *
1063
+ * @param {Object} manager - OrderManager instance
1064
+ * @param {unknown} BitShares - BitShares client
1065
+ * @returns {Promise<number|null>} New price or null
1066
+ */
1067
+ export async function refreshLiveMarketPrice(manager, BitShares) {
1068
+ try {
1069
+ const symA = manager?.assets?.assetA?.symbol;
1070
+ const symB = manager?.assets?.assetB?.symbol;
1071
+ // Require a real client surface: tests and dry paths pass `{}` and must
1072
+ // not trigger (or await) a pointless lookup.
1073
+ const client = BitShares;
1074
+ if (!symA || !symB || !client || !client.db)
1075
+ return null;
1076
+ const raw = await deriveMarketPrice(client, symA, symB);
1077
+ const price = Number(raw);
1078
+ if (Number.isFinite(price) && price > 0) {
1079
+ manager._liveMarketPrice = price;
1080
+ manager._liveMarketPriceAt = Date.now();
1081
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Live market price refreshed ${price} (${symA}/${symB})`, 'debug');
1082
+ return price;
1083
+ }
1084
+ }
1085
+ catch { /* best-effort: fall back to the fill anchor */ }
1086
+ return null;
1087
+ }
1088
+ /**
1089
+ * Refresh the live market price if none is fresh, pacing attempts to one per
1090
+ * freshness window so a chain that keeps failing cannot turn the spread check
1091
+ * into an RPC loop. The spread path stays RPC-free while the cache is fresh.
1092
+ *
1093
+ * @param {Object} manager - OrderManager instance
1094
+ * @param {unknown} BitShares - BitShares client
1095
+ * @param {Object} [options]
1096
+ * @param {number} [options.now] - Injectable clock (tests)
1097
+ * @returns {Promise<number|null>} Cached/new price or null
1098
+ */
1099
+ export async function maybeRefreshLiveMarketPrice(manager, BitShares, options = {}) {
1100
+ const now = Number.isFinite(options?.now) ? Number(options.now) : Date.now();
1101
+ const freshMs = resolveSpreadFreshnessMs(manager);
1102
+ if (freshMs <= 0)
1103
+ return Number(manager?._liveMarketPrice) || null; // no bound => never force a read
1104
+ const liveAt = Number(manager?._liveMarketPriceAt);
1105
+ if (Number.isFinite(liveAt) && liveAt > 0 && (now - liveAt) <= freshMs) {
1106
+ return Number(manager?._liveMarketPrice) || null;
1107
+ }
1108
+ const attemptedAt = Number(manager?._liveMarketPriceAttemptedAt);
1109
+ if (Number.isFinite(attemptedAt) && attemptedAt > 0 && (now - attemptedAt) <= freshMs) {
1110
+ return null; // attempted recently; do not storm the chain
1111
+ }
1112
+ // No usable client surface: leave the floor on the fill anchor. Debug only
1113
+ // (expected for tests/dry paths) and paced like a real attempt so it cannot
1114
+ // fire on every tick.
1115
+ const client = BitShares;
1116
+ if (!client || !client.db) {
1117
+ manager._liveMarketPriceAttemptedAt = now;
1118
+ manager.logger?.log?.('[SPREAD-CORRECTION] Live market price refresh skipped: no order-book client; crossing floor stays on the fill anchor', 'debug');
1119
+ return null;
1120
+ }
1121
+ manager._liveMarketPriceAttemptedAt = now;
1122
+ const refreshed = await refreshLiveMarketPrice(manager, BitShares);
1123
+ if (refreshed == null) {
1124
+ // One warn per pacing window: a persistently failing order-book/ticker
1125
+ // read silently degrades the floor to the fill anchor otherwise.
1126
+ manager.logger?.log?.('[SPREAD-CORRECTION] Live market price refresh failed; crossing floor stays on the fill anchor until the next attempt', 'warn');
1127
+ }
1128
+ return refreshed;
1129
+ }
1130
+ /**
1131
+ * Evaluate whether spread correction may act on the current local snapshot,
1132
+ * in ONE place. Pure: reads manager state, returns a verdict, no side effects;
1133
+ * the caller maps the reason to a stall and the existing wiring arms the
1134
+ * targeted sync.
1135
+ *
1136
+ * Premises:
1137
+ * - P-A cold book (no live order on either side): `ok=false` — hard refusal,
1138
+ * there is no realized spread to repair and only the reconcile path owns
1139
+ * the first window. Requires `options.onChainOrders`; skipped otherwise.
1140
+ * - P-B stale snapshot (a completed sync is older than the freshness window):
1141
+ * degraded-ok — the planner may still act, but `snapshotTrusted=false` so
1142
+ * the LAST-FILL-GUARD bypass is withheld. Never-synced is treated as fresh
1143
+ * (historical fail-open for the first tick).
1144
+ * - P-C known-unmatched chain orders: degraded-ok — plan, but the collision
1145
+ * filter drops their price levels and `snapshotTrusted=false`.
982
1146
  *
983
- * Returns the row normalized to {price:number, type, fillsAt:number,
984
- * genesisHash} when every field passes its gate, null otherwise:
985
- * - finite price > 0
986
- * - type is ORDER_TYPES.BUY or ORDER_TYPES.SELL
987
- * - finite fillsAt > 0
988
- * - non-empty string genesisHash
1147
+ * The market anchor is deliberately NOT a refusal premise — it is returned for
1148
+ * the crossing filter, and a real fill denies the bypass via `fillMarketRef`.
1149
+ *
1150
+ * @param {Object} manager - OrderManager instance
1151
+ * @param {Object} [options]
1152
+ * @param {number} [options.now] - Injectable clock (tests)
1153
+ * @param {Object|null} [options.onChainOrders] - Live local window view; enables P-A
1154
+ * @returns {SpreadCorrectionReadiness} Readiness verdict
1155
+ */
1156
+ export function evaluateSpreadCorrectionReadiness(manager, options = {}) {
1157
+ // The gate must never throw into the planner or the bypass check: a failure
1158
+ // is caught and turned into a refusal (correct-by-refusal), not a plan with
1159
+ // no floor. Callers surface it as the 'readiness-gate' stall.
1160
+ try {
1161
+ const now = Number.isFinite(options?.now) ? Number(options.now) : Date.now();
1162
+ const freshMs = resolveSpreadFreshnessMs(manager);
1163
+ const marketRef = resolveSpreadCrossingFloor(manager);
1164
+ const fillMarketRef = resolveSpreadMarketReference(manager);
1165
+ const unmatched = Array.isArray(manager?._lastUnmatchedChainOrders)
1166
+ ? manager._lastUnmatchedChainOrders
1167
+ : [];
1168
+ const synced = Number.isFinite(Number(manager?._lastSyncAt)) && Number(manager?._lastSyncAt) > 0;
1169
+ // Never-synced, or no usable window => fresh (fail-open for the first tick).
1170
+ const stale = synced && freshMs > 0 && (now - Number(manager?._lastSyncAt) > freshMs);
1171
+ const cold = !!options?.onChainOrders
1172
+ && options.onChainOrders.buys.length === 0
1173
+ && options.onChainOrders.sells.length === 0;
1174
+ const unmatchedPresent = unmatched.length > 0;
1175
+ let reason = null;
1176
+ if (cold)
1177
+ reason = 'cold-book';
1178
+ else if (stale)
1179
+ reason = 'stale-snapshot';
1180
+ else if (unmatchedPresent)
1181
+ reason = 'unmatched-orders';
1182
+ return {
1183
+ ok: !cold,
1184
+ reason,
1185
+ marketRef,
1186
+ fillMarketRef,
1187
+ snapshotTrusted: !stale && !unmatchedPresent,
1188
+ unmatched,
1189
+ };
1190
+ }
1191
+ catch (err) {
1192
+ // Correct-by-refusal: a gate that cannot read state refuses the cycle.
1193
+ // reason stays null (the cause is not a real premise, it is a fault);
1194
+ // callers map null to the 'readiness-gate' stall so the targeted sync
1195
+ // arms and triage logs name the fault. Detail-only log: the caller owns
1196
+ // the operator warning, so a gate-failure cycle is reported once.
1197
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Readiness gate failed (${getErrorMessage(err)}); refusing the cycle`, 'debug');
1198
+ return { ok: false, reason: null, marketRef: null, fillMarketRef: null, snapshotTrusted: false, unmatched: [] };
1199
+ }
1200
+ }
1201
+ /**
1202
+ * Resolve the last real FILL price — the fill-derived market reference.
1203
+ * Returns null (fail-open) when no real fill is known.
1204
+ *
1205
+ * The bot's grid anchor (AMA/startPrice) and its own book mid are NOT market
1206
+ * references — they are grid geometry or the bot's own quotes — so they are
1207
+ * deliberately not used here. Only a real fill price qualifies: the live
1208
+ * LAST-FILL-GUARD pivot when it is fill-provenanced, else the bot-scoped
1209
+ * persisted reference that survives grid regeneration.
1210
+ *
1211
+ * Feeds the COW bypass gate (via the readiness verdict's `fillMarketRef`) and
1212
+ * is the fallback crossing floor when no fresh live market read exists.
1213
+ *
1214
+ * @param {Object} manager - OrderManager instance
1215
+ * @returns {number|null} Reference price or null
1216
+ */
1217
+ export function resolveSpreadMarketReference(manager) {
1218
+ const live = Number(manager?._lastFilledPrice);
1219
+ const liveType = manager?._lastFilledType;
1220
+ if (manager?.lastFillPivotSource === 'fill' && Number.isFinite(live) && live > 0 && (liveType === ORDER_TYPES.BUY || liveType === ORDER_TYPES.SELL)) {
1221
+ return live;
1222
+ }
1223
+ const market = Number(manager?._lastMarketFillPrice);
1224
+ const marketType = manager?._lastMarketFillType;
1225
+ if (Number.isFinite(market) && market > 0 && (marketType === ORDER_TYPES.BUY || marketType === ORDER_TYPES.SELL)) {
1226
+ return market;
1227
+ }
1228
+ return null;
1229
+ }
1230
+ /**
1231
+ * Resolve the reference the generic LAST-FILL-GUARD judges against.
1232
+ *
1233
+ * Prefers the live armed pivot. When that is cold (a grid regeneration
1234
+ * cleared it, or a rejected-snapshot reset ran) it falls back to the
1235
+ * bot-scoped last-market-fill row — the same market truth spread correction
1236
+ * already uses. This is what stops a rebuild from silently un-arming the
1237
+ * guard until the next fill: the price the account last traded at is known,
1238
+ * so a CREATE/rotation must still not cross it.
1239
+ *
1240
+ * Read-time fallback only: it does NOT mutate the pivot or persist an
1241
+ * old-generation value, so the genesis-bound pivot/persist contract is
1242
+ * unchanged. The guard still validates the value onto the CURRENT ladder via
1243
+ * resolveOnGridPivot at the call site (off-ladder → raw value + warn), so a
1244
+ * regenerated geometry stays the authority on which placements are off-grid.
1245
+ *
1246
+ * @param {Object} manager - OrderManager instance
1247
+ * @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
1248
+ */
1249
+ export function resolveLastFillGuardReference(manager) {
1250
+ const livePrice = Number(manager?._lastFilledPrice);
1251
+ const liveType = manager?._lastFilledType;
1252
+ if (Number.isFinite(livePrice) && livePrice > 0 && (liveType === ORDER_TYPES.BUY || liveType === ORDER_TYPES.SELL)) {
1253
+ return { price: livePrice, type: liveType };
1254
+ }
1255
+ const marketPrice = Number(manager?._lastMarketFillPrice);
1256
+ const marketType = manager?._lastMarketFillType;
1257
+ if (Number.isFinite(marketPrice) && marketPrice > 0 && (marketType === ORDER_TYPES.BUY || marketType === ORDER_TYPES.SELL)) {
1258
+ return { price: marketPrice, type: marketType };
1259
+ }
1260
+ return { price: null, type: null };
1261
+ }
1262
+ /**
1263
+ * Restore the persisted bot-scoped last-market-fill reference into the
1264
+ * manager. Deliberately independent of the boundary and the genesis: this is
1265
+ * the anchor spread correction uses to avoid trading through the last real
1266
+ * fill price, and it must survive a grid regeneration (the genesis-bound
1267
+ * LAST-FILL-GUARD pivot does not). TTL-expired rows are erased from disk,
1268
+ * mirroring restoreLastFillPivot's dead-row hygiene.
1269
+ *
1270
+ * @param {Object} manager - OrderManager instance
1271
+ * @param {unknown} persisted - {price, type, fillsAt} from loadLastMarketFill
1272
+ * @param {Object} [options]
1273
+ * @param {number} [options.now] - Injectable clock (tests)
1274
+ * @returns {boolean} True when the reference was restored
1275
+ */
1276
+ export function restoreLastMarketFill(manager, persisted, options = {}) {
1277
+ if (!manager)
1278
+ return false;
1279
+ const row = normalizeLastMarketFill(persisted);
1280
+ if (!row)
1281
+ return false;
1282
+ // Shared dead-row contract with restoreLastFillPivot: erase a rejected
1283
+ // row so it cannot re-arm the same rejection on every restart.
1284
+ const dropPersistedRow = () => {
1285
+ try {
1286
+ const acct = manager.accountOrders;
1287
+ if (acct && typeof acct.clearPersistedLastMarketFill === 'function') {
1288
+ void acct.clearPersistedLastMarketFill();
1289
+ }
1290
+ }
1291
+ catch { /* best-effort */ }
1292
+ };
1293
+ const now = Number.isFinite(options?.now) ? Number(options.now) : Date.now();
1294
+ const ttl = Number(GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS);
1295
+ if (Number.isFinite(ttl) && ttl > 0 && now - row.fillsAt > ttl) {
1296
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Persisted last-market-fill expired (age ${Math.round((now - row.fillsAt) / 1000)}s > TTL ${Math.round(ttl / 1000)}s) — reference dropped`, 'info');
1297
+ dropPersistedRow();
1298
+ return false;
1299
+ }
1300
+ manager._lastMarketFillPrice = row.price;
1301
+ manager._lastMarketFillType = row.type;
1302
+ manager._lastMarketFillAt = row.fillsAt;
1303
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Restored last-market-fill ${row.price}(${row.type}) age=${Math.round((now - row.fillsAt) / 1000)}s — spread correction will not trade through it`, 'info');
1304
+ return true;
1305
+ }
1306
+ /**
1307
+ * Shared field gate for a persisted fill-derived row: finite price > 0,
1308
+ * BUY/SELL side, finite positive timestamp. One shape contract for the
1309
+ * LAST-FILL-GUARD pivot row and the bot-scoped last-market-fill row.
989
1310
  *
990
1311
  * @param {unknown} row - Raw candidate row
991
- * @returns {Object|null} Normalized row or null
1312
+ * @returns {{price:number,type:string,fillsAt:number}|null} Core fields or null
992
1313
  */
993
- export function normalizeLastFillPivot(row) {
1314
+ function normalizeFillRow(row) {
994
1315
  if (!row || typeof row !== 'object')
995
1316
  return null;
996
1317
  const r = row;
997
1318
  const price = Number(r.price);
998
1319
  const type = r.type;
999
1320
  const fillsAt = Number(r.fillsAt);
1000
- const genesisHash = r.genesisHash;
1001
1321
  if (!Number.isFinite(price) || price <= 0)
1002
1322
  return null;
1003
1323
  if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
1004
1324
  return null;
1005
1325
  if (!Number.isFinite(fillsAt) || fillsAt <= 0)
1006
1326
  return null;
1327
+ return { price, type, fillsAt };
1328
+ }
1329
+ /**
1330
+ * Normalize a persisted LAST-FILL-GUARD pivot row (shared by the
1331
+ * AccountOrders sanitizer/loader and the payload builder's row contract).
1332
+ *
1333
+ * The shared normalizeFillRow gate plus a non-empty string genesisHash (the
1334
+ * pivot is bound to the grid generation; the market row deliberately is not).
1335
+ *
1336
+ * @param {unknown} row - Raw candidate row
1337
+ * @returns {Object|null} Normalized row or null
1338
+ */
1339
+ export function normalizeLastFillPivot(row) {
1340
+ const core = normalizeFillRow(row);
1341
+ if (!core)
1342
+ return null;
1343
+ const genesisHash = row.genesisHash;
1007
1344
  if (typeof genesisHash !== 'string' || genesisHash.length === 0)
1008
1345
  return null;
1009
- return { price, type, fillsAt, genesisHash };
1346
+ return { ...core, genesisHash };
1347
+ }
1348
+ /**
1349
+ * Normalize a persisted bot-scoped last-market-fill row.
1350
+ *
1351
+ * Same normalizeFillRow contract as normalizeLastFillPivot but deliberately
1352
+ * WITHOUT the genesisHash binding: this row is market truth about the account
1353
+ * (the last price it traded at), not grid geometry, so it must survive a grid
1354
+ * regeneration/rejection. It is used only as a market reference by spread
1355
+ * correction, never as the COW LAST-FILL-GUARD pivot.
1356
+ *
1357
+ * @param {unknown} row - Raw candidate row
1358
+ * @returns {{price:number,type:string,fillsAt:number}|null} Normalized row or null
1359
+ */
1360
+ export function normalizeLastMarketFill(row) {
1361
+ return normalizeFillRow(row);
1010
1362
  }
1011
1363
  /**
1012
1364
  * Write the LAST-FILL-GUARD pivot scalar family in one place (free
@@ -1044,6 +1396,15 @@ export function setLastFillPivot(manager, type, price, provenance, atMs) {
1044
1396
  manager._lastFilledBuyPrice = p;
1045
1397
  else
1046
1398
  manager._lastFilledSellPrice = p;
1399
+ // Bot-scoped market-fill reference: only a real fill is market truth. It
1400
+ // is deliberately NOT cleared by resetLastFillPivot/clearGrid — it must
1401
+ // survive a grid regeneration so spread correction still has a price it
1402
+ // cannot trade through (the genesis-bound pivot above does not).
1403
+ if (provenance === 'fill') {
1404
+ manager._lastMarketFillPrice = p;
1405
+ manager._lastMarketFillType = type;
1406
+ manager._lastMarketFillAt = now;
1407
+ }
1047
1408
  return true;
1048
1409
  }
1049
1410
  /**
@@ -1270,7 +1631,9 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
1270
1631
  // the sell rail parked at 111-130 with the bottom three, 111-113,
1271
1632
  // inside the new spread gap; real spread 0.5% instead of the 2.0%
1272
1633
  // target).
1273
- const workingBoundaryIdx = (pendingBoundaryIdx !== null && pendingBoundaryIdx !== undefined && Number.isFinite(Number(pendingBoundaryIdx)))
1634
+ // Absent-aware: Number(null)/Number('') === 0 would fabricate a
1635
+ // boundary-0 rail; only a real finite pending boundary wins.
1636
+ const workingBoundaryIdx = Number.isFinite(toKnownNumber(pendingBoundaryIdx))
1274
1637
  ? Number(pendingBoundaryIdx)
1275
1638
  : manager.boundaryIdx;
1276
1639
  const gapSlots = manager._genesis?.gapSlots ?? manager._gapSlots ?? MathUtils.calculateGapSlots(manager.config?.incrementPercent, manager.config?.targetSpreadPercent, manager.config?.gridLimits);
@@ -1303,24 +1666,24 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
1303
1666
  .filter(inRailByType(orderType))
1304
1667
  .sort((a, b) => sideName === 'buy' ? b.price - a.price : a.price - b.price);
1305
1668
  // Calculate target count
1306
- const activeOrdersCfg = manager.config.activeOrders;
1307
- const baseTargetCount = (activeOrdersCfg && typeof activeOrdersCfg === 'object' && Number.isFinite(Number(activeOrdersCfg[sideName])))
1308
- ? Math.max(1, Number(activeOrdersCfg[sideName]))
1669
+ const coreOrdersCfg = manager.config.coreOrders;
1670
+ const baseTargetCount = (coreOrdersCfg && typeof coreOrdersCfg === 'object' && Number.isFinite(Number(coreOrdersCfg[sideName])))
1671
+ ? Math.max(1, Number(coreOrdersCfg[sideName]))
1309
1672
  : currentOnChainOrders.length;
1310
1673
  const targetCount = baseTargetCount;
1311
- // Determine desired slots (closest to market) + edge-pinned reserves.
1312
- // Buys pin at the floor, sells at the ceiling. Reserves rest live
1674
+ // Determine desired slots (closest to market) + edge-pinned orders.
1675
+ // Buys pin at the floor, sells at the ceiling. Edge orders rest live
1313
1676
  // without consuming the window: the middle stays undesired and gets
1314
1677
  // cancelled as surplus.
1315
1678
  const windowSlots = allSideSlots.slice(0, targetCount);
1316
1679
  let desiredSlots = windowSlots;
1317
- const reserveCount = OrderUtils.resolveReserveCount(manager.config, sideName);
1318
- if (reserveCount > 0) {
1680
+ const edgeCount = OrderUtils.resolveEdgeCount(manager.config, sideName);
1681
+ if (edgeCount > 0) {
1319
1682
  const asc = allSideSlots.slice().sort((a, b) => a.price - b.price);
1320
1683
  const edge = sideName === 'sell' ? 'ceiling' : 'floor';
1321
1684
  // Both edges anchor at the live grid's own edge (single source).
1322
- const edgeAnchor = OrderUtils.resolveLiveReserveEdgeAnchorPrice(manager, sideName);
1323
- const edgeSlots = OrderUtils.selectReserveEdgeSlots(asc, reserveCount, new Set(windowSlots.map((s) => s.id)), edge, edgeAnchor);
1685
+ const edgeAnchor = OrderUtils.resolveLiveEdgeAnchorPrice(manager, sideName);
1686
+ const edgeSlots = OrderUtils.selectEdgeSlots(asc, edgeCount, new Set(windowSlots.map((s) => s.id)), edge, edgeAnchor);
1324
1687
  desiredSlots = [...windowSlots, ...edgeSlots];
1325
1688
  }
1326
1689
  const desiredSlotIds = new Set(desiredSlots.map((s) => s.id));
@@ -1427,7 +1790,7 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
1427
1790
  // executor already handles rotation UPDATEs (newGridId + newPrice remap).
1428
1791
  const optimizedActions = optimizeRebalanceActions(actions, manager.orders, {
1429
1792
  logger: (msg, level) => manager.logger?.log?.(msg, level),
1430
- boundaryIdx: pendingBoundaryIdx,
1793
+ boundaryIdx: pendingBoundaryIdx ?? undefined,
1431
1794
  gapSlots: manager._gapSlots,
1432
1795
  assets: manager.assets
1433
1796
  });
@@ -1438,14 +1801,14 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
1438
1801
  // Refill-slot wire (boundary-hold): unpairable hole-CREATEs surviving
1439
1802
  // the fold above justify the pending boundary shift. The executor
1440
1803
  // holds the committed boundary when a listed refill is guard-skipped.
1441
- // Reserve-ladder CREATEs are excluded by collectRefillSlotIds — static
1804
+ // Edge-ladder CREATEs are excluded by collectRefillSlotIds — static
1442
1805
  // edge insurance, never a justification for a boundary shift.
1443
1806
  const refillSlotIds = OrderUtils.collectRefillSlotIds(actions, {
1444
1807
  config: manager.config,
1445
1808
  slots: manager.orders,
1446
1809
  edgeAnchors: {
1447
- buy: OrderUtils.resolveLiveReserveEdgeAnchorPrice(manager, 'buy'),
1448
- sell: OrderUtils.resolveLiveReserveEdgeAnchorPrice(manager, 'sell')
1810
+ buy: OrderUtils.resolveLiveEdgeAnchorPrice(manager, 'buy'),
1811
+ sell: OrderUtils.resolveLiveEdgeAnchorPrice(manager, 'sell')
1449
1812
  },
1450
1813
  manager
1451
1814
  });
@@ -1558,7 +1921,7 @@ export function nowIso() {
1558
1921
  * @returns {Promise<void>}
1559
1922
  */
1560
1923
  export function sleep(ms) {
1561
- return new Promise((resolve) => setTimeout(resolve, ms));
1924
+ return sleepMs(ms);
1562
1925
  }
1563
1926
  /**
1564
1927
  * Read user input from stdin with optional masking.
@@ -1881,6 +2244,21 @@ export function deepFreeze(obj) {
1881
2244
  export function cloneMap(map) {
1882
2245
  return new Map(map);
1883
2246
  }
2247
+ /**
2248
+ * Fire-and-forget structural grid resync. Invokes the manager's handler and
2249
+ * logs both a synchronous throw and an async rejection through the manager
2250
+ * logger, so escalation sites share one error-handling footer. No-op when the
2251
+ * manager has no handler.
2252
+ */
2253
+ export function fireStructuralResync(bot, reason, details, errorLabel, level = 'error') {
2254
+ try {
2255
+ const res = bot.manager?.requestStructuralGridResync?.(reason, details);
2256
+ res?.catch?.((err) => bot.manager?.logger?.log?.(`${errorLabel}: ${getErrorMessage(err)}`, level));
2257
+ }
2258
+ catch (err) {
2259
+ bot.manager?.logger?.log?.(`${errorLabel}: ${getErrorMessage(err)}`, level);
2260
+ }
2261
+ }
1884
2262
  /**
1885
2263
  * Parses JSON content that may contain comments (/* or //).
1886
2264
  * Strips block comments then line comments before parsing.
@@ -34,7 +34,7 @@
34
34
  // SECTION 1: EXTERNAL DEPENDENCIES
35
35
  // ===============================================================================
36
36
  import * as Format from '../format.js';
37
- import { ORDER_STATES, ORDER_TYPES, COW_ACTIONS, GRID_LIMITS } from '../../constants.js';
37
+ import { ORDER_STATES, ORDER_TYPES, COW_ACTIONS, COW_ORIGINS, GRID_LIMITS } from '../../constants.js';
38
38
  import { floatToBlockchainInt, blockchainToFloat, getPrecisionSlack, getPrecisionByOrderType, getDoubleDustThreshold, getSellStartIdx, isSlotIndexInGapBand, isEvacuationRotationAllowed, clamp, priceSlotEqual } from './math.js';
39
39
  import { parseSlotIndex } from './slot.js';
40
40
  import { isOrderOnChain, isPhantomOrder, convertToSpreadPlaceholder, detectGapEvacuationCandidates, updateGapEvacuationStreaks, isNonBlockingUnmatchedOrder } from './order.js';
@@ -356,6 +356,15 @@ function clampRotationSizeForPartial(surplusMaster, holeSize, logger = null, hol
356
356
  * @returns {Object} The action, stamped when it qualifies
357
357
  */
358
358
  function stampGapEvacuationRotation(action, sourceMaster, destPrice, destSize, type, frozenBoundary, frozenGapSlots, assets = null) {
359
+ // Explicit null/undefined/'' guard BEFORE Number(): Number(null) === 0 is
360
+ // finite and would stamp a bogus gap-evacuation bypass at boundary 0 when
361
+ // the plan geometry is unknown (absent geometry means no stamp, never
362
+ // fail-open — same trap guarded across the COW/gap-evacuation stack).
363
+ if (frozenBoundary === null || frozenBoundary === undefined || frozenBoundary === '')
364
+ return action;
365
+ const rawFrozenGapSlots = frozenGapSlots;
366
+ if (rawFrozenGapSlots === null || rawFrozenGapSlots === undefined || rawFrozenGapSlots === '')
367
+ return action;
359
368
  const b = Number(frozenBoundary);
360
369
  const g = Number(frozenGapSlots);
361
370
  if (!Number.isFinite(b) || !Number.isFinite(g) || g < 0)
@@ -385,7 +394,7 @@ function stampGapEvacuationRotation(action, sourceMaster, destPrice, destSize, t
385
394
  const check = isEvacuationRotationAllowed(sourceMaster?.price, sourceMaster?.size, destPrice, destSize, type, stampPrecision);
386
395
  if (!check.allowed)
387
396
  return action;
388
- return { ...action, origin: 'gap-evacuation', evacBoundary: b, evacGapSlots: Math.floor(g) };
397
+ return { ...action, origin: COW_ORIGINS.GAP_EVACUATION, evacBoundary: b, evacGapSlots: Math.floor(g) };
389
398
  }
390
399
  /**
391
400
  * Reconcile target grid against master state
@@ -399,8 +408,11 @@ function reconcileGrid(masterGrid, targetGrid, targetBoundary, options = {}) {
399
408
  const { logger = null, dustThresholdPercent = GRID_LIMITS.PARTIAL_DUST_THRESHOLD_PERCENTAGE } = options;
400
409
  // B-stamp inputs for gap-evacuation rotation stamping (frozen at
401
410
  // plan-build): callers pass the geometry this plan was built for. Absent
402
- // or non-finite => no stamping (guarded default, never fail-open).
403
- const planGapSlots = Number(options?.gapSlots);
411
+ // (null/undefined/'') or non-finite => no stamping (guarded default, never
412
+ // fail-open). Absent-aware coercion: Number(null) === 0 would otherwise
413
+ // feed 0 into stampGapEvacuationRotation/detectGapEvacuationCandidates and
414
+ // defeat their own null guards.
415
+ const planGapSlots = Format.toKnownNumber(options?.gapSlots);
404
416
  const hasPlanGeometry = Number.isFinite(planGapSlots) && planGapSlots >= 0;
405
417
  const evacAssets = options?.assets ?? null;
406
418
  const actions = [];
@@ -593,8 +605,18 @@ function optimizeRebalanceActions(actions, masterGrid, options = {}) {
593
605
  // B-stamp inputs (same contract as reconcileGrid): frozen plan-build
594
606
  // boundary + gap width for gap-evacuation rotation stamping. Absent =>
595
607
  // no stamping, guarded default.
596
- const optBoundary = Number(options?.boundaryIdx);
597
- const optGapSlots = Number(options?.gapSlots);
608
+ // Explicit null/undefined guard BEFORE Number(): Number(null) === 0 is
609
+ // finite and would turn an absent boundary into a valid slot-0 geometry,
610
+ // stamping a bogus gap-evacuation bypass (undefined already fails open via
611
+ // NaN, so only null was hazardous).
612
+ const rawOptBoundary = options?.boundaryIdx;
613
+ const rawOptGapSlots = options?.gapSlots;
614
+ const optBoundary = (rawOptBoundary === null || rawOptBoundary === undefined)
615
+ ? NaN
616
+ : Number(rawOptBoundary);
617
+ const optGapSlots = (rawOptGapSlots === null || rawOptGapSlots === undefined)
618
+ ? NaN
619
+ : Number(rawOptGapSlots);
598
620
  const hasOptGeometry = Number.isFinite(optBoundary) && Number.isFinite(optGapSlots) && optGapSlots >= 0;
599
621
  const optAssets = options?.assets ?? null;
600
622
  const creates = [];
@@ -1,5 +1,5 @@
1
1
  import type { BitSharesClient } from './system.js';
2
- export interface PoolPriceOverrides {
2
+ interface PoolPriceOverrides {
3
3
  derivePoolPrice(symA: string, symB: string): Promise<number | null>;
4
4
  }
5
5
  export declare function withPoolRef(BitShares: BitSharesClient, poolRef: string | null | undefined): PoolPriceOverrides | null;
@@ -16,4 +16,5 @@ export declare function withPoolRef(BitShares: BitSharesClient, poolRef: string
16
16
  */
17
17
  export declare function resolveStartPriceMode(startPrice: unknown, fallback?: string): string;
18
18
  export declare function derivePriceWithPoolRef(BitShares: BitSharesClient, symA: string, symB: string, mode: string, poolRef: string | null | undefined): Promise<number | null>;
19
+ export {};
19
20
  //# sourceMappingURL=withPoolRef.d.ts.map