dexbot 1.6.12 → 1.6.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/CHANGELOG.md +33 -1
  2. package/analysis/README.md +9 -11
  3. package/analysis/ama_fitting/README.md +5 -3
  4. package/claw/README.md +1 -0
  5. package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
  6. package/claw/modules/claw_bridge.ts +0 -3
  7. package/claw/modules/claw_skill_md.ts +1 -0
  8. package/claw/package.json +3 -3
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/claw/tsconfig.json +2 -2
  12. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  13. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  14. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  15. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  16. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  17. package/dist/analysis/analyze_args.d.ts +12 -0
  18. package/dist/analysis/analyze_args.js +20 -0
  19. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  20. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  21. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  22. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  23. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  24. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  25. package/dist/analysis/chart_ui.d.ts +30 -1
  26. package/dist/analysis/chart_ui.js +37 -1
  27. package/dist/analysis/fills_cache.d.ts +3 -23
  28. package/dist/analysis/fills_cache.js +3 -84
  29. package/dist/analysis/fills_source.d.ts +31 -1
  30. package/dist/analysis/fills_source.js +69 -1
  31. package/dist/analysis/grid_correction_check.d.ts +1 -23
  32. package/dist/analysis/grid_correction_check.js +15 -58
  33. package/dist/analysis/math_utils.d.ts +85 -1
  34. package/dist/analysis/math_utils.js +116 -1
  35. package/dist/analysis/price_sources.d.ts +22 -1
  36. package/dist/analysis/price_sources.js +23 -0
  37. package/dist/analysis/resolve_source.js +31 -10
  38. package/dist/analysis/trade_profitability.d.ts +6 -0
  39. package/dist/analysis/trade_profitability.js +23 -97
  40. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  41. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  42. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +2 -15
  43. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  44. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  45. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  46. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  47. package/dist/analysis/worker_pool.d.ts +38 -0
  48. package/dist/analysis/worker_pool.js +67 -0
  49. package/dist/dexbot.js +67 -48
  50. package/dist/market_adapter/ama_signal_runner.js +21 -54
  51. package/dist/market_adapter/candle_utils.d.ts +7 -1
  52. package/dist/market_adapter/candle_utils.js +11 -1
  53. package/dist/market_adapter/cli_args.d.ts +22 -0
  54. package/dist/market_adapter/cli_args.js +30 -0
  55. package/dist/market_adapter/core/config_normalizers.js +11 -6
  56. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  57. package/dist/market_adapter/core/kibana_candles.js +3 -2
  58. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  59. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  60. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  61. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  62. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  63. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  64. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  65. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  66. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  67. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  68. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  69. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  70. package/dist/market_adapter/inputs/window_cache.js +52 -177
  71. package/dist/market_adapter/interval_utils.d.ts +11 -1
  72. package/dist/market_adapter/interval_utils.js +16 -1
  73. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  74. package/dist/market_adapter/lp_chart_runner.js +37 -19
  75. package/dist/market_adapter/market_adapter.js +27 -72
  76. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  77. package/dist/market_adapter/utils/data_discovery.js +220 -27
  78. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  79. package/dist/market_adapter/utils/month_shards.js +237 -0
  80. package/dist/modules/account_bots.d.ts +1 -0
  81. package/dist/modules/account_bots.js +102 -121
  82. package/dist/modules/account_orders.d.ts +13 -0
  83. package/dist/modules/account_orders.js +38 -44
  84. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  85. package/dist/modules/bitshares-native/chain_client.js +14 -13
  86. package/dist/modules/bitshares-native/resolvers.js +22 -25
  87. package/dist/modules/bitshares-native/serial/types.js +22 -50
  88. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  89. package/dist/modules/bot_defaults.d.ts +2 -1
  90. package/dist/modules/bot_settings.d.ts +1 -1
  91. package/dist/modules/broadcast_failure.d.ts +2 -1
  92. package/dist/modules/chain_orders.d.ts +1 -1
  93. package/dist/modules/chain_orders.js +51 -96
  94. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  95. package/dist/modules/constants.d.ts +7 -1
  96. package/dist/modules/constants.js +20 -1
  97. package/dist/modules/cr_planner.d.ts +1 -1
  98. package/dist/modules/cr_planner.js +1 -5
  99. package/dist/modules/credit_pricing.d.ts +2 -1
  100. package/dist/modules/credit_pricing.js +36 -40
  101. package/dist/modules/credit_runtime.d.ts +7 -0
  102. package/dist/modules/credit_runtime.js +45 -73
  103. package/dist/modules/daemon_node_health.d.ts +4 -3
  104. package/dist/modules/dexbot_class.d.ts +28 -17
  105. package/dist/modules/dexbot_class.js +105 -58
  106. package/dist/modules/dexbot_cow_runtime.d.ts +0 -7
  107. package/dist/modules/dexbot_cow_runtime.js +54 -28
  108. package/dist/modules/dexbot_credential_client.d.ts +0 -7
  109. package/dist/modules/dexbot_credential_client.js +1 -2
  110. package/dist/modules/dexbot_fill_runtime.d.ts +1 -2
  111. package/dist/modules/dexbot_fill_runtime.js +5 -6
  112. package/dist/modules/dexbot_maintenance_runtime.d.ts +20 -3
  113. package/dist/modules/dexbot_maintenance_runtime.js +84 -69
  114. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  115. package/dist/modules/dexbot_startup_runtime.js +13 -14
  116. package/dist/modules/general_settings.d.ts +1 -1
  117. package/dist/modules/graceful_shutdown.js +17 -11
  118. package/dist/modules/key_store.js +0 -1
  119. package/dist/modules/lazy_shim.d.ts +11 -0
  120. package/dist/modules/lazy_shim.js +16 -0
  121. package/dist/modules/node_connect_policy.d.ts +3 -2
  122. package/dist/modules/node_failure_ledger.d.ts +6 -5
  123. package/dist/modules/order/format.d.ts +12 -3
  124. package/dist/modules/order/format.js +15 -3
  125. package/dist/modules/order/genesis_policy.d.ts +3 -3
  126. package/dist/modules/order/genesis_policy.js +5 -2
  127. package/dist/modules/order/grid.d.ts +4 -2
  128. package/dist/modules/order/grid.js +91 -35
  129. package/dist/modules/order/index.d.ts +1 -0
  130. package/dist/modules/order/logger.d.ts +1 -8
  131. package/dist/modules/order/logger.js +0 -9
  132. package/dist/modules/order/manager.d.ts +9 -13
  133. package/dist/modules/order/manager.js +33 -50
  134. package/dist/modules/order/utils/order.js +39 -35
  135. package/dist/modules/order/utils/system.d.ts +9 -29
  136. package/dist/modules/order/utils/system.js +17 -2
  137. package/dist/modules/order/utils/validate.js +2 -2
  138. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  139. package/dist/modules/paths.js +32 -34
  140. package/dist/modules/runtime_settings.d.ts +2 -4
  141. package/dist/modules/settings_merge.d.ts +2 -2
  142. package/dist/modules/socket_json_client.d.ts +2 -1
  143. package/dist/modules/types.d.ts +42 -27
  144. package/dist/modules/utils/errors.js +1 -3
  145. package/dist/modules/version_notice.d.ts +11 -10
  146. package/dist/pm2.d.ts +0 -1
  147. package/dist/pm2.js +56 -35
  148. package/dist/scripts/analyze-git.js +2 -15
  149. package/dist/scripts/chart_command.js +2 -2
  150. package/dist/scripts/check_any.d.ts +4 -0
  151. package/dist/scripts/check_any.js +53 -21
  152. package/dist/scripts/diagnose-pool-history.js +1 -6
  153. package/dist/scripts/run-tests.js +0 -1
  154. package/dist/scripts/sync-version.js +0 -10
  155. package/docs/BITSHARES_ONBOARDING.md +8 -12
  156. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  157. package/docs/DEXBOT_COMPARISON.md +6 -6
  158. package/docs/EVOLUTION.md +9 -8
  159. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  160. package/docs/README.md +1 -1
  161. package/docs/WORKFLOW.md +1 -0
  162. package/docs/architecture.md +19 -10
  163. package/market_adapter/README.md +6 -4
  164. package/package.json +6 -9
  165. package/scripts/README.md +43 -38
  166. package/tests/README.md +25 -10
  167. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  168. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  169. package/scripts/git-viewer.sh +0 -489
  170. package/scripts/postinstall.js +0 -16
@@ -5,9 +5,10 @@ import { dirname as _esmDirname } from 'node:path';
5
5
  const __filename = fileURLToPath(import.meta.url);
6
6
  const __dirname = _esmDirname(__filename);
7
7
  const require = createRequire(import.meta.url);
8
+ import { lazyShim } from './lazy_shim.js';
8
9
  import fs from 'node:fs';
9
10
  import { spawn } from 'node:child_process';
10
- import { nowIso } from './order/utils/system.js';
11
+ import { nowIso, fireStructuralResync } from './order/utils/system.js';
11
12
  import { path } from './path_api.js';
12
13
  import * as chainOrders from './chain_orders.js';
13
14
  import * as grid from './order/grid.js';
@@ -29,48 +30,48 @@ const { Config } = configModule;
29
30
  import { getErrorMessage } from './utils/errors.js';
30
31
  import { isSameBotName } from './utils/sanitize_key.js';
31
32
  import { usesAmaGridPrice } from './grid_price_source.js';
32
- function hasOpenOrdersSyncLoopMsSet(...args) { return require('./config').hasOpenOrdersSyncLoopMsSet(...args); }
33
- function getOpenOrdersSyncLoopMs(...args) { return require('./config').getOpenOrdersSyncLoopMs(...args); }
33
+ const hasOpenOrdersSyncLoopMsSet = lazyShim('./config', 'hasOpenOrdersSyncLoopMsSet');
34
+ const getOpenOrdersSyncLoopMs = lazyShim('./config', 'getOpenOrdersSyncLoopMs');
34
35
  function isGridBloated(...args) { return grid.isGridBloated(...args); }
35
36
  function isGridBloatGraceActive(...args) { return grid.isGridBloatGraceActive(...args); }
36
37
  function clearGridBloatFlag(...args) { return grid.clearGridBloatFlag(...args); }
37
38
  function recalculateGrid(...args) { return grid.recalculateGrid(...args); }
38
- function buildRuntimeScriptPath(...args) { return require('./launcher/runtime_entry').buildRuntimeScriptPath(...args); }
39
- function applyGridDivergenceCorrections(...args) { return require('./order/utils/system').applyGridDivergenceCorrections(...args); }
40
- function updateGridFromBlockchainSnapshot(...args) { return require('./order/grid').updateGridFromBlockchainSnapshot(...args); }
41
- function loadAmaCenterSnapshot(...args) { return require('./order/utils/system').loadAmaCenterSnapshot(...args); }
42
- function sleep(...args) { return require('./order/utils/system').sleep(...args); }
43
- function parseJsonWithComments(...args) { return require('./order/utils/system').parseJsonWithComments(...args); }
44
- function isPm2Runtime(...args) { return require('./order/logger').isPm2Runtime(...args); }
45
- function isWrapperAdapterOwner(...args) { return require('./launcher/adapter_requirement').isWrapperAdapterOwner(...args); }
46
- function readAdapterRequirement(...args) { return require('./launcher/adapter_requirement').readAdapterRequirement(...args); }
47
- function getSharedMarketAdapterRuntime(...args) { return require('./launcher/market_adapter_runtime').getSharedMarketAdapterRuntime(...args); }
48
- function resetMarketAdapterWhitelistCache(...args) { return require('./market_adapter_whitelist').resetMarketAdapterWhitelistCache(...args); }
49
- function isBotDynamicWeightWhitelisted(...args) { return require('./market_adapter_whitelist').isBotDynamicWeightWhitelisted(...args); }
39
+ const buildRuntimeScriptPath = lazyShim('./launcher/runtime_entry', 'buildRuntimeScriptPath');
40
+ const applyGridDivergenceCorrections = lazyShim('./order/utils/system', 'applyGridDivergenceCorrections');
41
+ const updateGridFromBlockchainSnapshot = lazyShim('./order/grid', 'updateGridFromBlockchainSnapshot');
42
+ const loadAmaCenterSnapshot = lazyShim('./order/utils/system', 'loadAmaCenterSnapshot');
43
+ const sleep = lazyShim('./order/utils/system', 'sleep');
44
+ const parseJsonWithComments = lazyShim('./order/utils/system', 'parseJsonWithComments');
45
+ const isPm2Runtime = lazyShim('./order/logger', 'isPm2Runtime');
46
+ const isWrapperAdapterOwner = lazyShim('./launcher/adapter_requirement', 'isWrapperAdapterOwner');
47
+ const readAdapterRequirement = lazyShim('./launcher/adapter_requirement', 'readAdapterRequirement');
48
+ const getSharedMarketAdapterRuntime = lazyShim('./launcher/market_adapter_runtime', 'getSharedMarketAdapterRuntime');
49
+ const resetMarketAdapterWhitelistCache = lazyShim('./market_adapter_whitelist', 'resetMarketAdapterWhitelistCache');
50
+ const isBotDynamicWeightWhitelisted = lazyShim('./market_adapter_whitelist', 'isBotDynamicWeightWhitelisted');
50
51
  function getRuntimeSettingsKeys() { return require('./runtime_settings').RUNTIME_SETTINGS_KEYS; }
51
- function cloneWeightDistribution(...args) { return require('./order/utils/math').cloneWeightDistribution(...args); }
52
- function calculateOrderCreationFees(...args) { return require('./order/utils/math').calculateOrderCreationFees(...args); }
53
- function calculateSwapInAmount(...args) { return require('./order/utils/math').calculateSwapInAmount(...args); }
54
- function floatToBlockchainInt(...args) { return require('./order/utils/math').floatToBlockchainInt(...args); }
55
- function blockchainToFloat(...args) { return require('./order/utils/math').blockchainToFloat(...args); }
56
- function updateDynamicGridSnapshotSync(...args) { return require('../market_adapter/utils/dynamic_grid_snapshot').updateDynamicGridSnapshotSync(...args); }
52
+ const cloneWeightDistribution = lazyShim('./order/utils/math', 'cloneWeightDistribution');
53
+ const calculateOrderCreationFees = lazyShim('./order/utils/math', 'calculateOrderCreationFees');
54
+ const calculateSwapInAmount = lazyShim('./order/utils/math', 'calculateSwapInAmount');
55
+ const floatToBlockchainInt = lazyShim('./order/utils/math', 'floatToBlockchainInt');
56
+ const blockchainToFloat = lazyShim('./order/utils/math', 'blockchainToFloat');
57
+ const updateDynamicGridSnapshotSync = lazyShim('../market_adapter/utils/dynamic_grid_snapshot', 'updateDynamicGridSnapshotSync');
57
58
  // Lazy require: dexbot_fill_runtime imports this module, so a static import
58
59
  // would be circular; at call time both modules are fully loaded.
59
- function scheduleFillConsumerRestartFn(...args) { return require('./dexbot_fill_runtime').scheduleFillConsumerRestart(...args); }
60
- function reconcileGridOrders(...args) { return require('./order/grid_reconcile').reconcileGridOrders(...args); }
61
- function resolveReserveCount(...args) { return require('./order/utils/order').resolveReserveCount(...args); }
62
- function reserveEdgeIdSet(...args) { return require('./order/utils/order').reserveEdgeIdSet(...args); }
63
- function liveWindowIdSet(...args) { return require('./order/utils/order').liveWindowIdSet(...args); }
64
- function resolveLiveReserveEdgeAnchorPrice(...args) { return require('./order/utils/order').resolveLiveReserveEdgeAnchorPrice(...args); }
65
- function formatUnmatchedChainOrder(...args) { return require('./order/utils/order').formatUnmatchedChainOrder(...args); }
66
- function isNonBlockingUnmatchedOrder(...args) { return require('./order/utils/order').isNonBlockingUnmatchedOrder(...args); }
67
- function isStrandedHoldOrder(...args) { return require('./order/utils/order').isStrandedHoldOrder(...args); }
68
- function getSideBudget(...args) { return require('./order/utils/order').getSideBudget(...args); }
60
+ const scheduleFillConsumerRestartFn = lazyShim('./dexbot_fill_runtime', 'scheduleFillConsumerRestart');
61
+ const reconcileGridOrders = lazyShim('./order/grid_reconcile', 'reconcileGridOrders');
62
+ const resolveReserveCount = lazyShim('./order/utils/order', 'resolveReserveCount');
63
+ const reserveEdgeIdSet = lazyShim('./order/utils/order', 'reserveEdgeIdSet');
64
+ const liveWindowIdSet = lazyShim('./order/utils/order', 'liveWindowIdSet');
65
+ const resolveLiveReserveEdgeAnchorPrice = lazyShim('./order/utils/order', 'resolveLiveReserveEdgeAnchorPrice');
66
+ const formatUnmatchedChainOrder = lazyShim('./order/utils/order', 'formatUnmatchedChainOrder');
67
+ const isNonBlockingUnmatchedOrder = lazyShim('./order/utils/order', 'isNonBlockingUnmatchedOrder');
68
+ const isStrandedHoldOrder = lazyShim('./order/utils/order', 'isStrandedHoldOrder');
69
+ const getSideBudget = lazyShim('./order/utils/order', 'getSideBudget');
69
70
  function getActiveOrdersTotal(config) { return require('./order/utils/order').getActiveOrdersTotal(config); }
70
- function correctAllPriceMismatches(...args) { return require('./order/utils/order').correctAllPriceMismatches(...args); }
71
- function isOrderOnChain(...args) { return require('./order/utils/order').isOrderOnChain(...args); }
72
- function parseChainOrder(...args) { return require('./order/utils/order').parseChainOrder(...args); }
73
- function parseSlotIndex(...args) { return require('./order/utils/order').parseSlotIndex(...args); }
71
+ const correctAllPriceMismatches = lazyShim('./order/utils/order', 'correctAllPriceMismatches');
72
+ const isOrderOnChain = lazyShim('./order/utils/order', 'isOrderOnChain');
73
+ const parseChainOrder = lazyShim('./order/utils/order', 'parseChainOrder');
74
+ const parseSlotIndex = lazyShim('./order/utils/order', 'parseSlotIndex');
74
75
  const CODE_ROOT = path.join(__dirname, '..');
75
76
  const PROFILES_DIR = PATHS.PROFILES_DIR;
76
77
  const PROFILES_BOTS_FILE = PATHS.PROFILES.BOTS_JSON;
@@ -651,6 +652,25 @@ function _hasBudgetForSide(manager, config, side) {
651
652
  return true;
652
653
  }
653
654
  }
655
+ /**
656
+ * Mirror a spread-check stall into the flags the targeted-sync gate reads.
657
+ *
658
+ * ANY stall — fund, batch, or structural — arms the refresh. When the
659
+ * correction cannot act on the local snapshot, that snapshot may simply be
660
+ * stale relative to the chain: a missed fill leaves an ACTIVE slot occupying
661
+ * the window edge, so `isSlotAvailable` hides every tightening slot and the
662
+ * check reports 'no-candidates' even though real geometry exists. A refresh is
663
+ * the only way to tell a genuinely structural stall from a stale one, so we
664
+ * sync rather than wait for the out-of-spread staleness watchdog to re-center.
665
+ * The stall cause is kept alongside the flag so the log states the truth.
666
+ * Exported for tests.
667
+ * @param {BotLike} bot
668
+ * @param {SpreadCorrectionStall|null|undefined} stall
669
+ */
670
+ export function mirrorSpreadStall(bot, stall) {
671
+ bot._spreadCorrectionStall = stall ?? null;
672
+ bot._spreadFundsExhausted = stall != null;
673
+ }
654
674
  function getTargetedSyncReason(bot) {
655
675
  if (!bot.manager || bot.config?.dryRun)
656
676
  return null;
@@ -688,14 +708,18 @@ function getTargetedSyncReason(bot) {
688
708
  if (drift && drift.isValid === false) {
689
709
  return { reason: `fund drift: ${drift.reason}`, targetBuy, targetSell, liveBuy, liveSell, drift };
690
710
  }
691
- // Spread correction placed no effective orders: either it found no free
692
- // funds on either side, or the prepared batch did not execute. The balances
693
- // or holds may simply be a stale snapshot (the grid does not lose funds, it
694
- // holds them in resting/virtual slots), so the only fallback is to refresh
695
- // account totals + open orders and let the next correction cycle re-check.
711
+ // Spread correction placed no effective order for ANY cause. The local
712
+ // snapshot the check reasoned over may be stale relative to the chain —
713
+ // balances/holds can be a stale read (the grid does not lose funds, it
714
+ // holds them in resting/virtual slots), and a missed fill can leave an
715
+ // ACTIVE slot occupying the window edge so no tightening slot appears to
716
+ // exist ('no-candidates'). Only a chain sync can tell a genuinely
717
+ // structural stall from a stale one, so arm the refresh for every cause
718
+ // instead of waiting up to SPREAD_STALE_ESCALATE_MS for the watchdog.
696
719
  // Never recycle resting inventory.
697
720
  if (bot._spreadFundsExhausted === true) {
698
- return { reason: 'spread correction had no free funds', targetBuy, targetSell, liveBuy, liveSell, drift };
721
+ const cause = bot._spreadCorrectionStall || 'funds-exhausted';
722
+ return { reason: `spread correction stalled (${cause})`, targetBuy, targetSell, liveBuy, liveSell, drift };
699
723
  }
700
724
  if (shortfalls.length > 0) {
701
725
  return { reason: `active order shortfall: ${shortfalls.join(', ')}`, targetBuy, targetSell, liveBuy, liveSell, drift };
@@ -737,6 +761,9 @@ async function maybeRunTargetedDriftReconciliation(bot, context) {
737
761
  // tick (subject to the cooldown below).
738
762
  if (bot._spreadFundsExhausted === true)
739
763
  bot._spreadFundsExhausted = false;
764
+ // Clear the companion cause with the flag so the two never drift apart
765
+ // (a leftover cause would mislabel the next tick's reason).
766
+ bot._spreadCorrectionStall = null;
740
767
  const remaining = getTargetedSyncReason(bot);
741
768
  const unmatchedCount = Number(syncResult?.unmatchedChainOrders?.length || 0);
742
769
  if (remaining || unmatchedCount > 0) {
@@ -1654,19 +1681,11 @@ function considerDeferredHoldEscalation(bot, strandedOrders, strandedMs) {
1654
1681
  `requesting structural resync to resolve the hold (reconcile is update-first, ` +
1655
1682
  `so funds are released by price-updating onto rail slots) — ` +
1656
1683
  `${describeDeferredHolds(bot, strandedOrders)}`, 'error');
1657
- try {
1658
- const res = bot.manager.requestStructuralGridResync('deferred-hold-stale', {
1659
- reason: `${held} deferred chain order(s) held unchanged for ~${heldHours}h`,
1660
- heldCount: held,
1661
- heldMs,
1662
- });
1663
- res?.catch?.((err) => {
1664
- bot.manager?.logger?.log?.(`[HOLD] Structural resync for stale hold failed: ${getErrorMessage(err)}`, 'error');
1665
- });
1666
- }
1667
- catch (err) {
1668
- bot.manager?.logger?.log?.(`[HOLD] Structural resync for stale hold failed: ${getErrorMessage(err)}`, 'error');
1669
- }
1684
+ fireStructuralResync(bot, 'deferred-hold-stale', {
1685
+ reason: `${held} deferred chain order(s) held unchanged for ~${heldHours}h`,
1686
+ heldCount: held,
1687
+ heldMs,
1688
+ }, '[HOLD] Structural resync for stale hold failed');
1670
1689
  }
1671
1690
  /**
1672
1691
  * Render the per-order detail for a deferred-hold summary: side, price, size,
@@ -2464,10 +2483,13 @@ async function executeMaintenanceLogic(bot, context) {
2464
2483
  const spreadResult = await bot.manager.checkSpreadCondition(BitShares, bot.updateOrdersOnChainPlan.bind(bot));
2465
2484
  if (await bot._abortFlowIfIllegalState(`${context} spread check`))
2466
2485
  return;
2467
- // Mirror the check result so the next tick's targeted-sync gate
2468
- // (getTargetedSyncReason) refreshes funds/open orders when the
2469
- // correction could not find any free funds.
2470
- bot._spreadFundsExhausted = spreadResult?.fundsExhausted === true;
2486
+ // Mirror the stall cause and arm the targeted-sync refresh for
2487
+ // every cause. The check can report 'no-candidates' on a stale
2488
+ // local snapshot (a missed fill leaves an ACTIVE slot hiding the
2489
+ // tightening slot), so the refresh must fire here too rather than
2490
+ // wait for trackOutOfSpreadStaleness to re-center. The stall cause
2491
+ // is kept so the next tick's reason names the truth.
2492
+ mirrorSpreadStall(bot, spreadResult?.stall ?? null);
2471
2493
  const spreadPlaced = Number(spreadResult?.ordersPlaced) || 0;
2472
2494
  if (spreadPlaced > 0) {
2473
2495
  bot._log(`✓ Spread correction during ${context}: ${spreadResult.ordersPlaced} order(s) placed`);
@@ -2550,17 +2572,9 @@ export function trackOutOfSpreadStaleness(bot, spreadChecked, ordersPlaced) {
2550
2572
  bot._lastSpreadStaleResyncAt = now;
2551
2573
  bot._log(`[SPREAD-STALE] Spread out of tolerance for ${staleMin}min despite corrections; ` +
2552
2574
  `requesting structural re-center`, 'warn');
2553
- try {
2554
- const res = bot.manager.requestStructuralGridResync('spread-stale-persistent', {
2555
- reason: `Spread out of tolerance for ${staleMin}min with no effective correction (outOfSpread=${outOfSpread})`
2556
- });
2557
- res?.catch?.((err) => {
2558
- bot.manager?.logger?.log?.(`[SPREAD-STALE] Structural re-center request failed: ${getErrorMessage(err)}`, 'error');
2559
- });
2560
- }
2561
- catch (err) {
2562
- bot.manager?.logger?.log?.(`[SPREAD-STALE] Structural re-center request failed: ${getErrorMessage(err)}`, 'error');
2563
- }
2575
+ fireStructuralResync(bot, 'spread-stale-persistent', {
2576
+ reason: `Spread out of tolerance for ${staleMin}min with no effective correction (outOfSpread=${outOfSpread})`
2577
+ }, '[SPREAD-STALE] Structural re-center request failed');
2564
2578
  return { staleMs, escalated: true };
2565
2579
  }
2566
2580
  }
@@ -3261,6 +3275,7 @@ export default {
3261
3275
  stopBotsConfigPollInterval,
3262
3276
  executeMaintenanceLogic,
3263
3277
  getTargetedSyncReason,
3278
+ mirrorSpreadStall,
3264
3279
  countLiveReserveOrders,
3265
3280
  maybeRunTargetedDriftReconciliation,
3266
3281
  cancelDustOrders,
@@ -1,4 +1,3 @@
1
- /** Startup runtime - bot initialization, grid placement, and startup sequence */
2
1
  import type { BotLike } from './types.js';
3
2
  /**
4
3
  * Initialize the startup state: account orders, manager, persisted data.
@@ -1,6 +1,5 @@
1
1
  /** Startup runtime - bot initialization, grid placement, and startup sequence */
2
- import { createRequire } from 'node:module';
3
- const require = createRequire(import.meta.url);
2
+ import { lazyShim } from './lazy_shim.js';
4
3
  import { path } from './path_api.js';
5
4
  import * as chainOrders from './chain_orders.js';
6
5
  import { readOpenOrdersGuarded } from './chain_orders.js';
@@ -16,19 +15,19 @@ import { getErrorMessage } from './utils/errors.js';
16
15
  import { processSweepOrphanFill } from './dexbot_fill_runtime.js';
17
16
  import { ON_MISSING_GENESIS, recordMissingGenesisFault, resolvePersistedGenesis } from './order/genesis_policy.js';
18
17
  const { OrderManager, grid: Grid } = orderModule;
19
- function initializeFeeCache(...args) { return require('./order/utils/system').initializeFeeCache(...args); }
20
- function parseJsonWithComments(...args) { return require('./order/utils/system').parseJsonWithComments(...args); }
21
- function withBlockchainRetry(...args) { return require('./order/utils/system').withBlockchainRetry(...args); }
22
- function buildFillKey(...args) { return require('./order/utils/order').buildFillKey(...args); }
23
- function correctAllPriceMismatches(...args) { return require('./order/utils/order').correctAllPriceMismatches(...args); }
24
- function parseChainOrder(...args) { return require('./order/utils/order').parseChainOrder(...args); }
25
- function restoreGapEvacStreaks(...args) { return require('./order/utils/system').restoreGapEvacStreaks(...args); }
26
- function applyPersistedPendingCrawls(...args) { return require('./order/utils/system').applyPersistedPendingCrawls(...args); }
27
- function startupSleep(...args) { return require('./order/utils/system').sleep(...args); }
18
+ const initializeFeeCache = lazyShim('./order/utils/system', 'initializeFeeCache');
19
+ const parseJsonWithComments = lazyShim('./order/utils/system', 'parseJsonWithComments');
20
+ const withBlockchainRetry = lazyShim('./order/utils/system', 'withBlockchainRetry');
21
+ const buildFillKey = lazyShim('./order/utils/order', 'buildFillKey');
22
+ const correctAllPriceMismatches = lazyShim('./order/utils/order', 'correctAllPriceMismatches');
23
+ const parseChainOrder = lazyShim('./order/utils/order', 'parseChainOrder');
24
+ const restoreGapEvacStreaks = lazyShim('./order/utils/system', 'restoreGapEvacStreaks');
25
+ const applyPersistedPendingCrawls = lazyShim('./order/utils/system', 'applyPersistedPendingCrawls');
26
+ const startupSleep = lazyShim('./order/utils/system', 'sleep');
28
27
  const storage = getStorage();
29
- function attemptResumePersistedGridByPriceMatch(...args) { return require('./order/grid_reconcile').attemptResumePersistedGridByPriceMatch(...args); }
30
- function decideStartupGridAction(...args) { return require('./order/grid_reconcile').decideStartupGridAction(...args); }
31
- function reconcileGridOrders(...args) { return require('./order/grid_reconcile').reconcileGridOrders(...args); }
28
+ const attemptResumePersistedGridByPriceMatch = lazyShim('./order/grid_reconcile', 'attemptResumePersistedGridByPriceMatch');
29
+ const decideStartupGridAction = lazyShim('./order/grid_reconcile', 'decideStartupGridAction');
30
+ const reconcileGridOrders = lazyShim('./order/grid_reconcile', 'reconcileGridOrders');
32
31
  function botRetryLogger(bot) {
33
32
  return { log: (msg) => bot._log(msg) };
34
33
  }
@@ -10,7 +10,7 @@ declare const SETTINGS_FILE: string;
10
10
  * The on-disk general settings document. Open-ended (dynamic top-level
11
11
  * sections) but `NODES` is typed because several callers read it directly.
12
12
  */
13
- export interface GeneralSettingsDocument {
13
+ interface GeneralSettingsDocument {
14
14
  NODES?: {
15
15
  enabled?: boolean;
16
16
  list?: string[];
@@ -68,6 +68,18 @@ let cleanupHandlers = [];
68
68
  let shutdownInProgress = false;
69
69
  const shutdownLogger = new Logger('Shutdown');
70
70
  const exitWipeCallbacks = [];
71
+ /**
72
+ * Shared registration guard for the cleanup and exit-wipe lists. Both hold
73
+ * `{ name, handler }` records and reject non-function handlers, so the
74
+ * validation and push live in one place.
75
+ * @private
76
+ */
77
+ function registerHandler(list, name, handler, label) {
78
+ if (typeof handler !== 'function') {
79
+ throw new Error(`${label} for '${name}' must be a function`);
80
+ }
81
+ list.push({ name, handler });
82
+ }
71
83
  /**
72
84
  * Register a synchronous wipe callback that runs AFTER all LIFO cleanup
73
85
  * handlers have completed, immediately before process exit. Unlike regular
@@ -79,10 +91,7 @@ const exitWipeCallbacks = [];
79
91
  * @param {Function} wipeFn - Synchronous function to execute last
80
92
  */
81
93
  function registerExitWipe(name, wipeFn) {
82
- if (typeof wipeFn !== 'function') {
83
- throw new Error(`Exit wipe callback for '${name}' must be a function`);
84
- }
85
- exitWipeCallbacks.push({ name, wipeFn });
94
+ registerHandler(exitWipeCallbacks, name, wipeFn, 'Exit wipe callback');
86
95
  }
87
96
  /**
88
97
  * Register a cleanup function to be called on graceful shutdown
@@ -91,10 +100,7 @@ function registerExitWipe(name, wipeFn) {
91
100
  * @param {Function} handler - Async or sync function to call on shutdown
92
101
  */
93
102
  function registerCleanup(name, handler) {
94
- if (typeof handler !== 'function') {
95
- throw new Error(`Cleanup handler for '${name}' must be a function`);
96
- }
97
- cleanupHandlers.push({ name, handler });
103
+ registerHandler(cleanupHandlers, name, handler, 'Cleanup handler');
98
104
  }
99
105
  /**
100
106
  * Remove a previously registered cleanup function.
@@ -155,9 +161,9 @@ async function executeCleanup() {
155
161
  }
156
162
  }
157
163
  for (let i = 0; i < exitWipeCallbacks.length; i++) {
158
- const { name, wipeFn } = exitWipeCallbacks[i];
164
+ const { name, handler } = exitWipeCallbacks[i];
159
165
  try {
160
- wipeFn();
166
+ handler();
161
167
  shutdownLogger.info(`✓ ${name} (exit wipe)`);
162
168
  }
163
169
  catch (err) {
@@ -186,7 +192,7 @@ function setupGracefulShutdown() {
186
192
  runtime.onSignal('exit', () => {
187
193
  for (let i = 0; i < exitWipeCallbacks.length; i++) {
188
194
  try {
189
- exitWipeCallbacks[i].wipeFn();
195
+ exitWipeCallbacks[i].handler();
190
196
  }
191
197
  catch (_) { }
192
198
  }
@@ -42,7 +42,6 @@ function buildDaemonBroadcastOptions(signingKey, extraOptions, sessionIdOverride
42
42
  requestType: 'broadcast',
43
43
  batchId: signingKey.batchId || null,
44
44
  ...(extraOptions.nodeUrl ? { nodeUrl: extraOptions.nodeUrl } : {}),
45
- ...(extraOptions.fallbackNodes ? { fallbackNodes: extraOptions.fallbackNodes } : {}),
46
45
  ...(typeof extraOptions.onNodeFailed === 'function' ? { onNodeFailed: extraOptions.onNodeFailed } : {}),
47
46
  };
48
47
  }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Build a lazy pass-through to a named export. The require runs on each call
3
+ * (Node caches modules), which keeps heavy or circular targets out of the
4
+ * static import graph without a hand-written wrapper per function. The
5
+ * returned function keeps the previous `(...args: unknown[]) => any` shape.
6
+ *
7
+ * Lives directly under modules/ so `require(modulePath)` resolves relative
8
+ * paths identically to the runtime modules that call it.
9
+ */
10
+ export declare function lazyShim(modulePath: string, exportName: string): (...args: unknown[]) => any;
11
+ //# sourceMappingURL=lazy_shim.d.ts.map
@@ -0,0 +1,16 @@
1
+ /** Lazy named-export pass-through shared by the Node-only runtime modules. */
2
+ import { createRequire } from 'node:module';
3
+ const require = createRequire(import.meta.url);
4
+ /**
5
+ * Build a lazy pass-through to a named export. The require runs on each call
6
+ * (Node caches modules), which keeps heavy or circular targets out of the
7
+ * static import graph without a hand-written wrapper per function. The
8
+ * returned function keeps the previous `(...args: unknown[]) => any` shape.
9
+ *
10
+ * Lives directly under modules/ so `require(modulePath)` resolves relative
11
+ * paths identically to the runtime modules that call it.
12
+ */
13
+ export function lazyShim(modulePath, exportName) {
14
+ return (...args) => require(modulePath)[exportName](...args);
15
+ }
16
+ //# sourceMappingURL=lazy_shim.js.map
@@ -13,7 +13,7 @@
13
13
  * unit-tested without constructing the whole native client or a live
14
14
  * NodeManager. Callers own the side effects.
15
15
  */
16
- export interface ConnectedNodePolicyInput {
16
+ interface ConnectedNodePolicyInput {
17
17
  /** `nodeConfig.healthCheck.enabled !== false`. */
18
18
  healthCheckEnabled: boolean;
19
19
  /** A restart/failover is already in progress; do not start another. */
@@ -25,7 +25,7 @@ export interface ConnectedNodePolicyInput {
25
25
  /** `nodeManager.getHealthyNodes`. */
26
26
  getHealthyNodes: () => string[];
27
27
  }
28
- export type ConnectedNodePolicyAction = {
28
+ type ConnectedNodePolicyAction = {
29
29
  action: 'switch';
30
30
  nodes: string[];
31
31
  reason: 'connected-on-blacklisted-node';
@@ -49,4 +49,5 @@ export type ConnectedNodePolicyAction = {
49
49
  * @returns {ConnectedNodePolicyAction}
50
50
  */
51
51
  export declare function resolveConnectedNodeAction(input: ConnectedNodePolicyInput): ConnectedNodePolicyAction;
52
+ export {};
52
53
  //# sourceMappingURL=node_connect_policy.d.ts.map
@@ -21,12 +21,12 @@
21
21
  * already-blacklisted node, and restarts counting from 0 when a previous
22
22
  * blacklist's cooldown expired.
23
23
  */
24
- export interface FailureLedgerEntry {
24
+ interface FailureLedgerEntry {
25
25
  failureCount: number;
26
26
  blacklistedUntil: number;
27
27
  lastReportedAt: number;
28
28
  }
29
- export interface FailureLedgerOptions {
29
+ interface FailureLedgerOptions {
30
30
  /** Failure count that triggers a blacklist. */
31
31
  threshold: number;
32
32
  /** Blacklist duration once the threshold is reached. */
@@ -40,14 +40,14 @@ export interface FailureLedgerOptions {
40
40
  /** Skip counting while the node is currently blacklisted (daemon). */
41
41
  skipWhileBlacklisted?: boolean;
42
42
  }
43
- export type FailureRecordOutcome = 'counted' | 'blacklisted' | 'rate-limited' | 'skipped-blacklisted';
44
- export interface FailureRecordResult {
43
+ type FailureRecordOutcome = 'counted' | 'blacklisted' | 'rate-limited' | 'skipped-blacklisted';
44
+ interface FailureRecordResult {
45
45
  outcome: FailureRecordOutcome;
46
46
  /** The count as recorded (or the existing count for skipped outcomes). */
47
47
  failureCount: number;
48
48
  threshold: number;
49
49
  }
50
- export interface FailureLedger {
50
+ interface FailureLedger {
51
51
  isBlacklisted(key: string): boolean;
52
52
  recordFailure(key: string, now?: number): FailureRecordResult;
53
53
  /** Clear a single entry (recovery: health-check success, resetNode). */
@@ -58,4 +58,5 @@ export interface FailureLedger {
58
58
  clear(): void;
59
59
  }
60
60
  export declare function createFailureLedger(options: FailureLedgerOptions): FailureLedger;
61
+ export {};
61
62
  //# sourceMappingURL=node_failure_ledger.d.ts.map
@@ -38,10 +38,11 @@
38
38
  * SECTION 4: RATIO/METRIC FORMATTING (1 function)
39
39
  * 12. formatMetric2(value) - Format to 2 decimals (timing, performance)
40
40
  *
41
- * SECTION 5: HELPER UTILITIES (3 functions)
41
+ * SECTION 5: HELPER UTILITIES (4 functions)
42
42
  * 13. isValidNumber(value) - Check if value is defined and finite
43
43
  * 14. toFiniteNumber(value, defaultValue) - Convert to finite number with fallback
44
- * 15. safeFormat(value, decimals, fallback) - Safely format with fallback
44
+ * 15. positiveOrNull(value) - Convert to a strictly-positive number, else null
45
+ * 16. safeFormat(value, decimals, fallback) - Safely format with fallback
45
46
  *
46
47
  * ===============================================================================
47
48
  */
@@ -156,6 +157,14 @@ declare function isValidNumber(value: unknown): boolean;
156
157
  */
157
158
  declare function toFiniteNumber(value: unknown, defaultValue?: number): number;
158
159
  declare function toFiniteNumber(value: unknown, defaultValue: number | null): number | null;
160
+ /**
161
+ * Convert a value to a strictly-positive finite number, else `null`.
162
+ *
163
+ * Single home for the `positiveOrNull` guard previously duplicated in
164
+ * cr_planner and credit_pricing. Zero, negatives, non-finite values and
165
+ * non-numeric strings all yield `null`.
166
+ */
167
+ declare function positiveOrNull(value: unknown): number | null;
159
168
  /**
160
169
  * Safely format a numeric value with specified decimals and fallback.
161
170
  *
@@ -165,5 +174,5 @@ declare function toFiniteNumber(value: unknown, defaultValue: number | null): nu
165
174
  * @returns {string} Formatted value or fallback string
166
175
  */
167
176
  declare function safeFormat(value: unknown, decimals: number, fallback?: string): string;
168
- export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, safeFormat };
177
+ export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, positiveOrNull, safeFormat };
169
178
  //# sourceMappingURL=format.d.ts.map
@@ -38,10 +38,11 @@
38
38
  * SECTION 4: RATIO/METRIC FORMATTING (1 function)
39
39
  * 12. formatMetric2(value) - Format to 2 decimals (timing, performance)
40
40
  *
41
- * SECTION 5: HELPER UTILITIES (3 functions)
41
+ * SECTION 5: HELPER UTILITIES (4 functions)
42
42
  * 13. isValidNumber(value) - Check if value is defined and finite
43
43
  * 14. toFiniteNumber(value, defaultValue) - Convert to finite number with fallback
44
- * 15. safeFormat(value, decimals, fallback) - Safely format with fallback
44
+ * 15. positiveOrNull(value) - Convert to a strictly-positive number, else null
45
+ * 16. safeFormat(value, decimals, fallback) - Safely format with fallback
45
46
  *
46
47
  * ===============================================================================
47
48
  */
@@ -246,6 +247,17 @@ function toFiniteNumber(value, defaultValue = 0) {
246
247
  const num = Number(value);
247
248
  return Number.isFinite(num) ? num : defaultValue;
248
249
  }
250
+ /**
251
+ * Convert a value to a strictly-positive finite number, else `null`.
252
+ *
253
+ * Single home for the `positiveOrNull` guard previously duplicated in
254
+ * cr_planner and credit_pricing. Zero, negatives, non-finite values and
255
+ * non-numeric strings all yield `null`.
256
+ */
257
+ function positiveOrNull(value) {
258
+ const num = Number(value);
259
+ return Number.isFinite(num) && num > 0 ? num : null;
260
+ }
249
261
  /**
250
262
  * Safely format a numeric value with specified decimals and fallback.
251
263
  *
@@ -268,5 +280,5 @@ function safeFormat(value, decimals, fallback = 'N/A') {
268
280
  // ===============================================================================
269
281
  // EXPORTS
270
282
  // ===============================================================================
271
- export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, safeFormat };
283
+ export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, positiveOrNull, safeFormat };
272
284
  //# sourceMappingURL=format.js.map
@@ -45,12 +45,11 @@ export declare const MISSING_GENESIS_REASON: {
45
45
  /** T4: the migration ladder build threw. */
46
46
  readonly MIGRATION_FAILED: "migration_failed";
47
47
  };
48
- export type MissingGenesisReason = (typeof MISSING_GENESIS_REASON)[keyof typeof MISSING_GENESIS_REASON];
49
48
  export declare const ON_MISSING_GENESIS: {
50
49
  readonly REBUILD: "rebuild";
51
50
  readonly HALT: "halt";
52
51
  };
53
- export type OnMissingGenesisPolicy = (typeof ON_MISSING_GENESIS)[keyof typeof ON_MISSING_GENESIS];
52
+ type OnMissingGenesisPolicy = (typeof ON_MISSING_GENESIS)[keyof typeof ON_MISSING_GENESIS];
54
53
  /**
55
54
  * Thrown by `loadGrid` (and the startup gate) when a snapshot carries orders
56
55
  * but no usable ladder. Carries the policy so each caller can route the same
@@ -105,7 +104,7 @@ export declare function buildGenesisFromLiveRail(config: GridConfig | null | und
105
104
  reason: string;
106
105
  detail: string;
107
106
  };
108
- export type GenesisResolution = {
107
+ type GenesisResolution = {
109
108
  ok: true;
110
109
  genesis: GridGenesis | null;
111
110
  source: 'persisted' | 'in_memory' | 'migration';
@@ -162,4 +161,5 @@ export declare function recordMissingGenesisFault(manager: OrderManagerLike, fau
162
161
  detail: string;
163
162
  mismatchRatio: number | null;
164
163
  }): MissingGenesisError;
164
+ export {};
165
165
  //# sourceMappingURL=genesis_policy.d.ts.map
@@ -202,9 +202,12 @@ export function resolvePersistedGenesis({ config, grid, genesisInput = null, man
202
202
  }
203
203
  const built = buildGenesisFromLiveRail(config);
204
204
  if (!built.ok) {
205
- emit(`[GENESIS] Cannot migrate the persisted grid: ${built.detail} — ` +
205
+ // strictNullChecks:false (tests build) does not discriminate this union,
206
+ // so name the failure shape explicitly.
207
+ const failure = built;
208
+ emit(`[GENESIS] Cannot migrate the persisted grid: ${failure.detail} — ` +
206
209
  `no ladder available, refusing to load the snapshot without one`, 'error');
207
- return { ok: false, reason: built.reason, detail: built.detail, mismatchRatio: null };
210
+ return { ok: false, reason: failure.reason, detail: failure.detail, mismatchRatio: null };
208
211
  }
209
212
  // Cross-check the derived rail against the persisted slots. A user who
210
213
  // edited startPrice/min/max/increment across restarts gets a rail the live
@@ -93,6 +93,8 @@ interface SpreadCorrection {
93
93
  partialOrder: ManagedOrder;
94
94
  newSize: number;
95
95
  }>;
96
+ plannedCount?: number;
97
+ stallHint?: 'unfunded' | 'no-candidates';
96
98
  boundaryIdx?: number;
97
99
  origin?: string;
98
100
  [key: string]: unknown;
@@ -109,7 +111,7 @@ export declare function resolveRmsThresholdPct(manager: OrderManagerLike | null
109
111
  import { calculateGapSlots as _mathGapSlots } from './utils/math.js';
110
112
  import * as MathUtils from './utils/math.js';
111
113
  import { WorkingGrid } from './working_grid.js';
112
- import type { OrderManagerLike, ManagedOrder, GridConfig, OrderType, OrderState, CowAction } from '../types.js';
114
+ import type { OrderManagerLike, ManagedOrder, GridConfig, OrderType, OrderState, CowAction, SpreadCorrectionStall } from '../types.js';
113
115
  import type { GridGenesis } from './utils/math.js';
114
116
  declare const calculateGapSlots: typeof _mathGapSlots;
115
117
  export { calculateGapSlots };
@@ -475,7 +477,7 @@ export declare function checkSpreadCondition(manager: OrderManagerLike, _BitShar
475
477
  }>) | null): Promise<{
476
478
  ordersPlaced: number;
477
479
  partialsMoved: number;
478
- fundsExhausted?: boolean;
480
+ stall?: SpreadCorrectionStall;
479
481
  }>;
480
482
  /**
481
483
  * Grid health check for structural violations.