dexbot 1.6.18 → 1.7.1

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 (146) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +24 -18
  3. package/analysis/README.md +117 -5
  4. package/claw/package.json +1 -1
  5. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  7. package/dist/analysis/account_resolver.js +5 -6
  8. package/dist/analysis/analyze_dynamic_weight.js +2 -1
  9. package/dist/analysis/analyze_kalman.js +3 -2
  10. package/dist/analysis/analyze_liquidity.d.ts +17 -0
  11. package/dist/analysis/analyze_liquidity.js +336 -0
  12. package/dist/analysis/analyze_regime.js +3 -2
  13. package/dist/analysis/analyze_regime_windows.js +3 -2
  14. package/dist/analysis/analyze_volatility.js +3 -2
  15. package/dist/analysis/bot_key_utils.d.ts +44 -1
  16. package/dist/analysis/bot_key_utils.js +76 -7
  17. package/dist/analysis/fills_cache.js +2 -1
  18. package/dist/analysis/grid_correction_check.d.ts +1 -19
  19. package/dist/analysis/grid_correction_check.js +12 -30
  20. package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
  21. package/dist/analysis/liquidity/liquidity_chain.js +178 -0
  22. package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
  23. package/dist/analysis/liquidity/liquidity_chart_generator.js +693 -0
  24. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +166 -0
  25. package/dist/analysis/liquidity/liquidity_depth_model.js +258 -0
  26. package/dist/analysis/liquidity/liquidity_view.d.ts +53 -0
  27. package/dist/analysis/liquidity/liquidity_view.js +66 -0
  28. package/dist/analysis/resolve_bot_accounts.js +7 -6
  29. package/dist/analysis/trade_profitability.js +4 -2
  30. package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
  31. package/dist/credential-daemon.js +13 -2
  32. package/dist/dexbot.js +77 -172
  33. package/dist/modules/account_bots.d.ts +11 -1
  34. package/dist/modules/account_orders.d.ts +12 -0
  35. package/dist/modules/account_orders.js +30 -0
  36. package/dist/modules/asset_lookup.d.ts +25 -0
  37. package/dist/modules/asset_lookup.js +75 -0
  38. package/dist/modules/bitshares-native/transport.js +24 -6
  39. package/dist/modules/bitshares_client.d.ts +24 -6
  40. package/dist/modules/bitshares_client.js +44 -7
  41. package/dist/modules/bot_settings.d.ts +2 -0
  42. package/dist/modules/chain_scan.d.ts +64 -0
  43. package/dist/modules/chain_scan.js +80 -0
  44. package/dist/modules/cli_colors.d.ts +5 -0
  45. package/dist/modules/cli_colors.js +7 -0
  46. package/dist/modules/cli_progress.d.ts +51 -0
  47. package/dist/modules/cli_progress.js +113 -0
  48. package/dist/modules/constants.d.ts +26 -3
  49. package/dist/modules/constants.js +63 -8
  50. package/dist/modules/dexbot_class.d.ts +1 -6
  51. package/dist/modules/dexbot_class.js +14 -0
  52. package/dist/modules/dexbot_cow_runtime.d.ts +97 -7
  53. package/dist/modules/dexbot_cow_runtime.js +634 -136
  54. package/dist/modules/dexbot_fill_runtime.js +132 -23
  55. package/dist/modules/dexbot_maintenance_runtime.js +242 -74
  56. package/dist/modules/dexbot_startup_runtime.js +32 -20
  57. package/dist/modules/dexbot_state_recovery.d.ts +33 -1
  58. package/dist/modules/dexbot_state_recovery.js +167 -5
  59. package/dist/modules/launcher/runtime_entry.d.ts +21 -1
  60. package/dist/modules/launcher/runtime_entry.js +36 -1
  61. package/dist/modules/liquidity_pool_ref.d.ts +32 -0
  62. package/dist/modules/liquidity_pool_ref.js +116 -0
  63. package/dist/modules/node_connect_policy.d.ts +8 -1
  64. package/dist/modules/node_connect_policy.js +18 -2
  65. package/dist/modules/node_flap_score.d.ts +87 -0
  66. package/dist/modules/node_flap_score.js +124 -0
  67. package/dist/modules/node_health_cache.d.ts +40 -3
  68. package/dist/modules/node_health_cache.js +66 -20
  69. package/dist/modules/node_manager.d.ts +101 -19
  70. package/dist/modules/node_manager.js +255 -65
  71. package/dist/modules/order/accounting.js +56 -7
  72. package/dist/modules/order/format.d.ts +24 -10
  73. package/dist/modules/order/format.js +30 -10
  74. package/dist/modules/order/grid.js +91 -13
  75. package/dist/modules/order/grid_reconcile.d.ts +5 -1
  76. package/dist/modules/order/grid_reconcile.js +333 -189
  77. package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
  78. package/dist/modules/order/grid_reconcile_internal.js +298 -100
  79. package/dist/modules/order/index.d.ts +19 -1
  80. package/dist/modules/order/lifecycle.d.ts +353 -0
  81. package/dist/modules/order/lifecycle.js +1109 -0
  82. package/dist/modules/order/manager.d.ts +273 -5
  83. package/dist/modules/order/manager.js +654 -48
  84. package/dist/modules/order/placement_lock.d.ts +102 -0
  85. package/dist/modules/order/placement_lock.js +222 -0
  86. package/dist/modules/order/strategy.js +13 -1
  87. package/dist/modules/order/sync_engine.d.ts +33 -1
  88. package/dist/modules/order/sync_engine.js +241 -73
  89. package/dist/modules/order/utils/math.d.ts +39 -1
  90. package/dist/modules/order/utils/math.js +83 -1
  91. package/dist/modules/order/utils/order.d.ts +181 -5
  92. package/dist/modules/order/utils/order.js +455 -9
  93. package/dist/modules/order/utils/system.d.ts +81 -1
  94. package/dist/modules/order/utils/system.js +331 -44
  95. package/dist/modules/order/utils/validate.d.ts +7 -1
  96. package/dist/modules/order/utils/validate.js +80 -3
  97. package/dist/modules/outcome.d.ts +54 -0
  98. package/dist/modules/outcome.js +51 -0
  99. package/dist/modules/settings_merge.d.ts +4 -0
  100. package/dist/modules/settings_merge.js +9 -0
  101. package/dist/modules/timing_policy.d.ts +82 -0
  102. package/dist/modules/timing_policy.js +244 -0
  103. package/dist/modules/types.d.ts +137 -0
  104. package/dist/modules/utils/asset_symbols.d.ts +13 -2
  105. package/dist/modules/utils/asset_symbols.js +21 -2
  106. package/dist/scripts/analysis_runner.d.ts +10 -0
  107. package/dist/scripts/analysis_runner.js +33 -0
  108. package/dist/scripts/analyze-credit.js +54 -17
  109. package/dist/scripts/analyze-orders.d.ts +4 -2
  110. package/dist/scripts/analyze-orders.js +115 -35
  111. package/dist/scripts/asset.d.ts +26 -0
  112. package/dist/scripts/asset.js +165 -0
  113. package/dist/scripts/bts_distribution.d.ts +1 -0
  114. package/dist/scripts/bts_distribution.js +194 -142
  115. package/dist/scripts/chart_command.d.ts +1 -1
  116. package/dist/scripts/chart_command.js +60 -86
  117. package/dist/scripts/chart_targets.d.ts +18 -0
  118. package/dist/scripts/chart_targets.js +48 -0
  119. package/dist/scripts/dw.js +1 -1
  120. package/dist/scripts/liquid.d.ts +24 -0
  121. package/dist/scripts/liquid.js +134 -0
  122. package/dist/scripts/rich_list.js +12 -16
  123. package/dist/scripts/test-credit-renewal.js +12 -5
  124. package/dist/scripts/token_distribution.d.ts +2 -0
  125. package/dist/scripts/token_distribution.js +132 -108
  126. package/dist/scripts/tv.js +1 -1
  127. package/dist/scripts/verify-browser-bundle.js +18 -0
  128. package/docs/COW_INVARIANTS.md +69 -10
  129. package/docs/DEXBOT_COMPARISON.md +6 -6
  130. package/docs/EVOLUTION.md +10 -8
  131. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  132. package/docs/GRID_PRICE_INVARIANT.md +5 -2
  133. package/docs/GRID_RECONCILE.md +36 -11
  134. package/docs/LOGGING.md +50 -4
  135. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +177 -27
  136. package/docs/README.md +23 -2
  137. package/docs/WORKFLOW.md +12 -4
  138. package/docs/architecture.md +42 -5
  139. package/docs/developer_guide.md +25 -8
  140. package/modules/README.md +8 -1
  141. package/package.json +3 -1
  142. package/scripts/README.md +39 -7
  143. package/scripts/pdev.sh +14 -1
  144. package/scripts/pmain.sh +23 -8
  145. package/scripts/ptest.sh +7 -0
  146. package/tests/README.md +30 -1
@@ -10,12 +10,12 @@
10
10
  *
11
11
  * Asset Amounts: 8 decimals - blockchain native precision
12
12
  * Prices: 6-8 decimals - price precision varies by pair
13
- * Percentages: 1-4 decimals - display precision
13
+ * Percentages: 0-2 decimals - display precision (formatPercentLabel)
14
14
  * Ratios/Metrics: 2-5 decimals - context dependent
15
15
  * Time/Performance (ms, %): 1-2 decimals - readable metrics
16
16
  *
17
17
  * ===============================================================================
18
- * TABLE OF CONTENTS (17 exported functions)
18
+ * TABLE OF CONTENTS (18 exported functions)
19
19
  * ===============================================================================
20
20
  *
21
21
  * SECTION 1: ASSET FORMATTING (4 functions)
@@ -31,20 +31,22 @@
31
31
  * 8. formatCurrency(value, digits) - Grouped thousands with SI micro-suffixes
32
32
  * 9. formatFundsValue(value) - Compact K/M, 4 significant figures (keeps trailing zeros)
33
33
  *
34
- * SECTION 3: PERCENTAGE FORMATTING (2 functions)
34
+ * SECTION 3: PERCENTAGE FORMATTING (3 functions)
35
35
  * 10. formatPercent2(value) - Format to 2 decimals (spread %, ratios)
36
36
  * 11. formatPercent(value, decimals) - Format with custom decimal places
37
+ * 12. formatPercentLabel(value) - Percentage with unit: 2 decimals below 100%,
38
+ * 1 from 100%, 0 from 1000% (fixed-point, never SI-suffixed)
37
39
  *
38
40
  * SECTION 4: RATIO/METRIC FORMATTING (1 function)
39
- * 12. formatMetric2(value) - Format to 2 decimals (timing, performance)
41
+ * 13. formatMetric2(value) - Format to 2 decimals (timing, performance)
40
42
  *
41
43
  * SECTION 5: HELPER UTILITIES (5 functions)
42
- * 13. isValidNumber(value) - Check if value is defined and finite
43
- * 14. toFiniteNumber(value, defaultValue) - Convert to finite number with fallback
44
- * 15. toKnownNumber(value, absentValue) - Convert to finite number, treating an
44
+ * 14. isValidNumber(value) - Check if value is defined and finite
45
+ * 15. toFiniteNumber(value, defaultValue) - Convert to finite number with fallback
46
+ * 16. toKnownNumber(value, absentValue) - Convert to finite number, treating an
45
47
  * explicitly absent value (null/undefined/empty) as the absent sentinel
46
- * 16. positiveOrNull(value) - Convert to a strictly-positive number, else null
47
- * 17. safeFormat(value, decimals, fallback) - Safely format with fallback
48
+ * 17. positiveOrNull(value) - Convert to a strictly-positive number, else null
49
+ * 18. safeFormat(value, decimals, fallback) - Safely format with fallback
48
50
  *
49
51
  * ===============================================================================
50
52
  */
@@ -138,6 +140,18 @@ declare function formatFundsValue(value: number): string;
138
140
  */
139
141
  declare function formatPercent2(value: number): string;
140
142
  declare function formatPercent(value: number, decimals?: number): string;
143
+ /**
144
+ * Percentage including its unit, at display precision.
145
+ *
146
+ * 2 decimals below 100% ("2.27%", "0.40%", "18.18%"), 1 from 100% ("100.0%")
147
+ * and none from 1000% ("1235%"), so a percentage never carries more than four
148
+ * significant digits or a noisy trailing digit on a spread. Fixed-point, so the
149
+ * milli/micro suffixes `formatCurrency` produces for small values ("0.05" ->
150
+ * "50m") can never leak into a percentage.
151
+ *
152
+ * Dependency-free (Math/Number only) so chart exporters can embed it verbatim.
153
+ */
154
+ declare function formatPercentLabel(value: number | null | undefined): string;
141
155
  /**
142
156
  * Format metric to 2 decimal places
143
157
  *
@@ -190,5 +204,5 @@ declare function toKnownNumber(value: unknown): number;
190
204
  * @returns {string} Formatted value or fallback string
191
205
  */
192
206
  declare function safeFormat(value: unknown, decimals: number, fallback?: string): string;
193
- export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, toKnownNumber, positiveOrNull, safeFormat };
207
+ export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatPercentLabel, formatMetric2, isValidNumber, toFiniteNumber, toKnownNumber, positiveOrNull, safeFormat };
194
208
  //# sourceMappingURL=format.d.ts.map
@@ -10,12 +10,12 @@
10
10
  *
11
11
  * Asset Amounts: 8 decimals - blockchain native precision
12
12
  * Prices: 6-8 decimals - price precision varies by pair
13
- * Percentages: 1-4 decimals - display precision
13
+ * Percentages: 0-2 decimals - display precision (formatPercentLabel)
14
14
  * Ratios/Metrics: 2-5 decimals - context dependent
15
15
  * Time/Performance (ms, %): 1-2 decimals - readable metrics
16
16
  *
17
17
  * ===============================================================================
18
- * TABLE OF CONTENTS (17 exported functions)
18
+ * TABLE OF CONTENTS (18 exported functions)
19
19
  * ===============================================================================
20
20
  *
21
21
  * SECTION 1: ASSET FORMATTING (4 functions)
@@ -31,20 +31,22 @@
31
31
  * 8. formatCurrency(value, digits) - Grouped thousands with SI micro-suffixes
32
32
  * 9. formatFundsValue(value) - Compact K/M, 4 significant figures (keeps trailing zeros)
33
33
  *
34
- * SECTION 3: PERCENTAGE FORMATTING (2 functions)
34
+ * SECTION 3: PERCENTAGE FORMATTING (3 functions)
35
35
  * 10. formatPercent2(value) - Format to 2 decimals (spread %, ratios)
36
36
  * 11. formatPercent(value, decimals) - Format with custom decimal places
37
+ * 12. formatPercentLabel(value) - Percentage with unit: 2 decimals below 100%,
38
+ * 1 from 100%, 0 from 1000% (fixed-point, never SI-suffixed)
37
39
  *
38
40
  * SECTION 4: RATIO/METRIC FORMATTING (1 function)
39
- * 12. formatMetric2(value) - Format to 2 decimals (timing, performance)
41
+ * 13. formatMetric2(value) - Format to 2 decimals (timing, performance)
40
42
  *
41
43
  * SECTION 5: HELPER UTILITIES (5 functions)
42
- * 13. isValidNumber(value) - Check if value is defined and finite
43
- * 14. toFiniteNumber(value, defaultValue) - Convert to finite number with fallback
44
- * 15. toKnownNumber(value, absentValue) - Convert to finite number, treating an
44
+ * 14. isValidNumber(value) - Check if value is defined and finite
45
+ * 15. toFiniteNumber(value, defaultValue) - Convert to finite number with fallback
46
+ * 16. toKnownNumber(value, absentValue) - Convert to finite number, treating an
45
47
  * explicitly absent value (null/undefined/empty) as the absent sentinel
46
- * 16. positiveOrNull(value) - Convert to a strictly-positive number, else null
47
- * 17. safeFormat(value, decimals, fallback) - Safely format with fallback
48
+ * 17. positiveOrNull(value) - Convert to a strictly-positive number, else null
49
+ * 18. safeFormat(value, decimals, fallback) - Safely format with fallback
48
50
  *
49
51
  * ===============================================================================
50
52
  */
@@ -222,6 +224,24 @@ function formatPercent2(value) {
222
224
  function formatPercent(value, decimals = 2) {
223
225
  return safeFormat(value, decimals);
224
226
  }
227
+ /**
228
+ * Percentage including its unit, at display precision.
229
+ *
230
+ * 2 decimals below 100% ("2.27%", "0.40%", "18.18%"), 1 from 100% ("100.0%")
231
+ * and none from 1000% ("1235%"), so a percentage never carries more than four
232
+ * significant digits or a noisy trailing digit on a spread. Fixed-point, so the
233
+ * milli/micro suffixes `formatCurrency` produces for small values ("0.05" ->
234
+ * "50m") can never leak into a percentage.
235
+ *
236
+ * Dependency-free (Math/Number only) so chart exporters can embed it verbatim.
237
+ */
238
+ function formatPercentLabel(value) {
239
+ if (typeof value !== 'number' || !Number.isFinite(value))
240
+ return 'N/A';
241
+ const abs = Math.abs(value);
242
+ const decimals = abs >= 1000 ? 0 : abs >= 100 ? 1 : 2;
243
+ return `${value.toFixed(decimals)}%`;
244
+ }
225
245
  // ===============================================================================
226
246
  // SECTION 4: RATIO/METRIC FORMATTING
227
247
  // ===============================================================================
@@ -300,5 +320,5 @@ function safeFormat(value, decimals, fallback = 'N/A') {
300
320
  // ===============================================================================
301
321
  // EXPORTS
302
322
  // ===============================================================================
303
- export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, toKnownNumber, positiveOrNull, safeFormat };
323
+ export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatPercentLabel, formatMetric2, isValidNumber, toFiniteNumber, toKnownNumber, positiveOrNull, safeFormat };
304
324
  //# sourceMappingURL=format.js.map
@@ -420,7 +420,7 @@ function _snapshotFundState(manager) {
420
420
  import { floatToBlockchainInt, getPrecisionByOrderType, getPrecisionsForManager, calculateOrderCreationFees, calculateOrderSizes, calculateRotationOrderSizes, calculateAvailableFundsValue, calculateGridSideDivergenceMetric, getPrecisionSlack, getMinOrderSize, getSingleDustThreshold, getGridBestPrices, calculateSpreadFromOrders, allocateFundsByWeights, calculateGapSlots as _mathGapSlots, pricesOnSameLevel, sameGridLevel, getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, validatePersistedBoundary, isTransientInBandRejection, adjustBudgetForBtsFees, clamp, derivePriceLevels, buildGenesisFromPriceLevels, assertSlotPriceInvariant, priceForSlot, hashPriceLevels, } from './utils/math.js';
421
421
  import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, resolveEdgeCount, edgeOrderIdSet, resolveLiveEdgeAnchorPrice, liveWindowIdSet, getOrderTypeFromUpdatedFlags } from './utils/order.js';
422
422
  import { parseSlotIndex } from './utils/slot.js';
423
- import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot, rearmLastFillPivotFromMarketFill, evaluateSpreadCorrectionReadiness, maybeRefreshLiveMarketPrice, resolveLastFillGuardReference, isLastFillGuardBlocked } from './utils/system.js';
423
+ import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot, rearmLastFillPivotFromMarketFill, evaluateSpreadCorrectionReadiness, maybeRefreshLiveMarketPrice, resolveLastFillGuardReference, isLastFillPlacementBlocked } from './utils/system.js';
424
424
  import * as MathUtils from './utils/math.js';
425
425
  import { derivePriceWithPoolRef, resolveStartPriceMode } from './utils/withPoolRef.js';
426
426
  import { getWhitelistFlags } from '../market_adapter_whitelist.js';
@@ -908,6 +908,21 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
908
908
  }
909
909
  // RC-2: Use logic helper
910
910
  _clearOrderCachesLogic(manager);
911
+ // Restart durability: merge the pass-1 "size already applied"
912
+ // markers persisted with this snapshot (live markers win on
913
+ // conflict), so a fill replayed after a crash is not subtracted a
914
+ // second time.
915
+ try {
916
+ const restoreMarkers = manager.restoreChainSizeAppliedFills;
917
+ const acct = manager.accountOrders;
918
+ const persistedMarkers = typeof acct?.loadChainSizeAppliedFills === 'function'
919
+ ? acct.loadChainSizeAppliedFills()
920
+ : null;
921
+ if (typeof restoreMarkers === 'function' && persistedMarkers) {
922
+ restoreMarkers.call(manager, persistedMarkers);
923
+ }
924
+ }
925
+ catch { /* marker restore is best-effort; normal accounting still applies */ }
911
926
  // resetFunds under _fundLock only — no persistGrid needed (grid already
912
927
  // on disk). For the resync variant see recalculateGrid (grid.ts:~1037)
913
928
  // which snapshots fund values under lock and persists outside.
@@ -929,6 +944,14 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
929
944
  // center boundary from slot prices, falling back to "no boundary"
930
945
  // (callers sync against chain right after load either way).
931
946
  const loadGapSlots = calculateGapSlots(manager.config?.incrementPercent, manager.config?.targetSpreadPercent, manager.config?.gridLimits);
947
+ // Publish the geometry BEFORE restoring the boundary. The restore
948
+ // path (and anything it calls: last-fill pivot snapping, the
949
+ // [BOUNDARY] restore debug line) reads manager._gapSlots, and
950
+ // leaving it unset until the re-type pass below made every restart
951
+ // report `gapSlots=0 sellStart=boundary+1` — i.e. "the spread band
952
+ // is gone" on a perfectly healthy 4-slot band. Same value as the
953
+ // assignment in the re-type block, which now only reads it.
954
+ manager._gapSlots = loadGapSlots;
932
955
  let restoredBoundary = typeof boundaryIdx === 'number' ? boundaryIdx : null;
933
956
  if (restoredBoundary !== null) {
934
957
  const check = validatePersistedBoundary(restoredBoundary, grid, loadGapSlots);
@@ -1018,7 +1041,6 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
1018
1041
  // slot-N is the canonical identity.
1019
1042
  if (restoredBoundary !== null) {
1020
1043
  const gapSlots = loadGapSlots;
1021
- manager._gapSlots = gapSlots;
1022
1044
  const buyEndIdx = restoredBoundary;
1023
1045
  const sellStartIdx = getSellStartIdx(restoredBoundary, gapSlots);
1024
1046
  let reassignCount = 0;
@@ -1166,6 +1188,7 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
1166
1188
  });
1167
1189
  manager.initialSpreadCount = spreadCount;
1168
1190
  manager.currentSpreadCount = spreadCount;
1191
+ manager._spreadCountKnown = true;
1169
1192
  }
1170
1193
  finally {
1171
1194
  await manager.resumeFundRecalc();
@@ -1573,6 +1596,10 @@ export async function initializeGrid(manager) {
1573
1596
  // RC-2: Wrap atomic changes in grid lock
1574
1597
  await manager._gridLock.acquire(async () => {
1575
1598
  _clearOrderCachesLogic(manager);
1599
+ // Regeneration replaces every chain order id: pass-1 size markers
1600
+ // keyed by the old ids are no longer evidence (unlike a snapshot
1601
+ // RELOAD, which restores/merges the persisted markers).
1602
+ manager._chainSizeAppliedFills = new Map();
1576
1603
  await manager._fundLock.acquire(async () => {
1577
1604
  await manager.resetFunds();
1578
1605
  });
@@ -1596,6 +1623,7 @@ export async function initializeGrid(manager) {
1596
1623
  // should not assume the two paths agree.
1597
1624
  manager.initialSpreadCount = initialSpreadCount.buy + initialSpreadCount.sell;
1598
1625
  manager.currentSpreadCount = manager.initialSpreadCount;
1626
+ manager._spreadCountKnown = true;
1599
1627
  });
1600
1628
  // FIX: Use consistent optional chaining pattern for all logger calls
1601
1629
  manager.logger?.log?.(`Initialized grid with ${orders.length} orders.`, 'info');
@@ -1616,6 +1644,9 @@ export async function recalculateGrid(manager, opts) {
1616
1644
  const { readOpenOrdersFn, chainOrders, account, privateKey } = opts;
1617
1645
  // Suppress invariant warnings during full resync
1618
1646
  manager.startBootstrap();
1647
+ // A rebuild owns placement until the reconcile completes: fill-driven
1648
+ // COW rebalances defer instead of re-planning against the fresh master.
1649
+ manager.beginStructuralRebuild?.('recalculateGrid');
1619
1650
  // Total timeout across all steps — prevents indefinite hang even if
1620
1651
  // an individual withBlockchainRetry step pins the event loop.
1621
1652
  const totalTimeoutMs = PIPELINE_TIMING.TIMEOUT_MS * 2; // 10 min
@@ -1668,6 +1699,16 @@ export async function recalculateGrid(manager, opts) {
1668
1699
  if (_resyncAborted)
1669
1700
  return;
1670
1701
  const { reconcileGridOrders } = require('./grid_reconcile');
1702
+ // NOTE: do NOT re-adopt the chain snapshot by ladder index here.
1703
+ // After a rebuild every slot price moved, so a price-agnostic
1704
+ // ladder adoption would park each old order on a slot whose new
1705
+ // price differs from the order's actual chain price. The
1706
+ // reconcile marks that slot as matched and would leave the stale
1707
+ // price in place for a later correction cycle. The rebuild is
1708
+ // bracketed by beginStructuralRebuild(), so no concurrent COW
1709
+ // can create against the fresh master; reconcileGridOrders owns
1710
+ // update-first placement and re-prices the live orders onto the
1711
+ // new slots from the chain snapshot directly.
1671
1712
  // #5: Reconcile grid orders.
1672
1713
  // No per-attempt wall-clock race around the whole reconcile.
1673
1714
  // Phase 2 performs many sequential broadcasts (creates ~3s each)
@@ -1681,7 +1722,7 @@ export async function recalculateGrid(manager, opts) {
1681
1722
  // failover standard via withBlockchainRetry, and the 10-min
1682
1723
  // totalTimeoutMs safety net below bounds the whole resync.
1683
1724
  try {
1684
- await reconcileGridOrders({ manager, config: manager.config, account, privateKey, chainOrders, chainOpenOrders });
1725
+ await reconcileGridOrders({ manager, config: manager.config, account, privateKey, chainOrders, chainOpenOrders, options: { allowDuringRebuild: true } });
1685
1726
  }
1686
1727
  catch (err) {
1687
1728
  manager.logger?.log?.(`Error during startup order reconciliation: ${getErrorMessage(err)}`, 'error');
@@ -1705,6 +1746,7 @@ export async function recalculateGrid(manager, opts) {
1705
1746
  }
1706
1747
  finally {
1707
1748
  manager.finishBootstrap();
1749
+ manager.endStructuralRebuild?.();
1708
1750
  }
1709
1751
  })();
1710
1752
  // Swallow late rejection if timeout wins the race
@@ -3126,10 +3168,16 @@ function resolveMinSpreadOrdersReserve(manager) {
3126
3168
  const raw = Number(manager?.config?.gridLimits?.MIN_SPREAD_ORDERS ?? GRID_LIMITS.MIN_SPREAD_ORDERS);
3127
3169
  return (Number.isFinite(raw) && raw >= 0) ? Math.floor(raw) : GRID_LIMITS.MIN_SPREAD_ORDERS;
3128
3170
  }
3129
- // Collect contiguous empty gap-band slots adjacent to a rail edge for boundary
3130
- // promotion. BUY walks upward from the boundary into the gap, SELL walks
3131
- // downward from the sell start; both stop at the first unavailable slot.
3132
- // Mirrors are collapsed into one directional walk (step +/- 1).
3171
+ // Collect gap-band slots adjacent to a rail edge for boundary promotion.
3172
+ // BUY walks upward from the boundary into the gap, SELL walks downward from
3173
+ // the sell start. An EMPTY available slot is promoted; a same-side order
3174
+ // already PLACED inside the band is ABSORBED (it becomes a legal rail member
3175
+ // once the boundary slides past it) and only advances the depth; anything
3176
+ // else (opposite-side placement, phantom, unavailable slot) stops the walk.
3177
+ // "Same-side" is the slot's stored rail type by construction: a placed
3178
+ // SPREAD slot is an ILLEGAL_SPREAD_STATE (validateOrder), so there is no
3179
+ // side-neutral placement to resolve here. Mirrors are collapsed into one
3180
+ // directional walk (step +/- 1).
3133
3181
  //
3134
3182
  // PROMOTION CAP (gap-band geometry): promotion may consume at most
3135
3183
  // bandSize − MIN_SPREAD_ORDERS slots, where bandSize = sellStartIdx −
@@ -3160,14 +3208,35 @@ function _collectPromotableBoundarySlots(allSlotsByPrice, railType, buyEndIdx, s
3160
3208
  const promotionQuota = Math.min(quota, maxPromotable, Math.max(0, maxDepth));
3161
3209
  const promoted = [];
3162
3210
  const step = isBuy ? 1 : -1;
3163
- for (let idx = isBuy ? buyEndIdx + 1 : sellStartIdx - 1; promoted.length < promotionQuota
3211
+ // Depth counts EVERY band slot the boundary slide consumes, not only the
3212
+ // new placements: a same-side order already PLACED inside the band is
3213
+ // absorbed by the slide (it becomes a legal rail member once the
3214
+ // boundary moves past it) and is not a placement target. Only empty
3215
+ // available slots are returned. Absorbing is what repairs the
3216
+ // post-crawl shape (boundary 169, sell 173 in-band, 170-172 empty):
3217
+ // step over 173, promote 172, boundary 167. Pushing the placed slot
3218
+ // would plan a CREATE over a live order (duplicate/occupied slot) and
3219
+ // abort the batch, so it only advances `depth`.
3220
+ let depth = 0;
3221
+ for (let idx = isBuy ? buyEndIdx + 1 : sellStartIdx - 1; promotionQuota > 0
3222
+ && depth < maxDepth
3223
+ && depth < maxPromotable
3164
3224
  && (isBuy
3165
3225
  ? idx <= sellStartIdx - 1 - spreadReserve
3166
3226
  : idx >= buyEndIdx + 1 + spreadReserve); idx += step) {
3167
3227
  const slot = allSlotsByPrice[idx];
3168
- if (!slot || !isSlotAvailable(slot))
3228
+ if (!slot)
3229
+ break;
3230
+ if (isOrderPlaced(slot) && slot.type === railType) {
3231
+ depth++;
3232
+ continue;
3233
+ }
3234
+ if (!isSlotAvailable(slot))
3169
3235
  break;
3170
3236
  promoted.push(slot);
3237
+ depth++;
3238
+ if (promoted.length >= promotionQuota)
3239
+ break;
3171
3240
  }
3172
3241
  return promoted;
3173
3242
  }
@@ -3235,7 +3304,14 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3235
3304
  return false;
3236
3305
  if (c?.price == null || !Number.isFinite(Number(c.price)))
3237
3306
  return false;
3238
- return isLastFillGuardBlocked(Number(c.price), railType, lastFillPivot, lastFillSide).blocked === true;
3307
+ // Judge candidates with the SAME predicate the placement guards use
3308
+ // (direction rule + same grid level). The raw-pivot direction check
3309
+ // this replaces was blind to the same-level shape — a slot level and
3310
+ // its own execution price differ by rounding (slot 1310.046339
3311
+ // filled at 1310.060435) — so it admitted candidates that the
3312
+ // broadcast guard then refused, burning a correction cycle on a
3313
+ // guaranteed refusal and under-reporting "Excluded N".
3314
+ return isLastFillPlacementBlocked(manager, Number(c.price), railType).blocked === true;
3239
3315
  };
3240
3316
  let lastFillExcluded = 0;
3241
3317
  // A slot can legitimately appear in MORE than one candidate pool (an
@@ -3500,9 +3576,11 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3500
3576
  .sort(sortCandidates)
3501
3577
  .slice(0, missingSlots);
3502
3578
  // If the funded rail is full, the spread itself may be stale: the
3503
- // nearest empty slots are still in the gap band. Promote contiguous
3504
- // empty gap slots from that rail edge so correction can repair the
3505
- // boundary and place orders in one atomic COW commit.
3579
+ // nearest empty slots are still in the gap band. Promote from that rail
3580
+ // edge so correction can repair the boundary and place orders in one
3581
+ // atomic COW commit. The walk may ABSORB a same-side order already
3582
+ // placed inside the band (it becomes a rail member once the boundary
3583
+ // slides past it); only empty slots become CREATE targets.
3506
3584
  //
3507
3585
  // Requires a KNOWN committed boundary: with a null/unknown boundary the
3508
3586
  // rail edges are fabricated (buyEndIdx=0), so promotion would place
@@ -81,12 +81,16 @@ export declare function decideStartupGridAction({ persistedGrid, chainOpenOrders
81
81
  * @param {Array<Object>} params.chainOpenOrders - On-chain open orders
82
82
  * @returns {Promise<Object|null>} Reconciliation result, or null when reconciliation completes without a summary object
83
83
  */
84
- export declare function reconcileGridOrders({ manager, config, account, privateKey, chainOrders, chainOpenOrders, }: {
84
+ export declare function reconcileGridOrders({ manager, config, account, privateKey, chainOrders, chainOpenOrders, options, }: {
85
85
  manager: OrderManagerLike;
86
86
  config: GridConfig;
87
87
  account: string;
88
88
  privateKey: string;
89
89
  chainOrders: ChainOrdersLike;
90
90
  chainOpenOrders: ChainOrder[];
91
+ options?: {
92
+ /** Rebuild callers own the rebuild and must be allowed to reconcile. */
93
+ allowDuringRebuild?: boolean;
94
+ };
91
95
  }): Promise<null>;
92
96
  //# sourceMappingURL=grid_reconcile.d.ts.map