dexbot 1.6.15 → 1.6.17

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 (130) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +4 -4
  3. package/analysis/tradingview/README.md +2 -2
  4. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  5. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
  6. package/claw/modules/chain_queries.ts +3 -3
  7. package/claw/package.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  10. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +5 -3
  11. package/dist/analysis/ama_fitting/fetch_lp_candles.js +8 -1
  12. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
  13. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
  14. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
  15. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
  16. package/dist/analysis/bot_key_utils.js +9 -7
  17. package/dist/analysis/chart_utils.d.ts +9 -2
  18. package/dist/analysis/chart_utils.js +51 -1
  19. package/dist/analysis/tradingview/grid_reset_sim.js +1 -1
  20. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
  21. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +23 -9
  22. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
  23. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +21 -2
  24. package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
  25. package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
  26. package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
  27. package/dist/dexbot.js +89 -138
  28. package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
  29. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
  30. package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
  31. package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
  32. package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
  33. package/dist/market_adapter/inputs/window_cache.js +53 -17
  34. package/dist/market_adapter/lp_chart_core.js +1 -0
  35. package/dist/market_adapter/utils/chain.js +4 -3
  36. package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
  37. package/dist/market_adapter/utils/pair_orientation.js +142 -0
  38. package/dist/modules/account_bots.d.ts +40 -3
  39. package/dist/modules/account_bots.js +77 -37
  40. package/dist/modules/account_orders.d.ts +4 -1
  41. package/dist/modules/account_orders.js +4 -1
  42. package/dist/modules/bitshares-native/resolvers.js +3 -3
  43. package/dist/modules/bitshares_client.d.ts +12 -10
  44. package/dist/modules/bitshares_client.js +12 -10
  45. package/dist/modules/bot_settings.js +3 -3
  46. package/dist/modules/chain_keys.d.ts +6 -2
  47. package/dist/modules/chain_keys.js +5 -1
  48. package/dist/modules/chain_orders.d.ts +6 -2
  49. package/dist/modules/chain_orders.js +6 -2
  50. package/dist/modules/constants.d.ts +11 -0
  51. package/dist/modules/constants.js +41 -7
  52. package/dist/modules/credit_pricing.d.ts +20 -1
  53. package/dist/modules/credit_pricing.js +23 -1
  54. package/dist/modules/credit_runtime.js +33 -16
  55. package/dist/modules/dexbot_class.d.ts +6 -2
  56. package/dist/modules/dexbot_class.js +8 -3
  57. package/dist/modules/dexbot_cow_runtime.d.ts +28 -37
  58. package/dist/modules/dexbot_cow_runtime.js +47 -66
  59. package/dist/modules/dexbot_maintenance_runtime.js +68 -10
  60. package/dist/modules/graceful_shutdown.d.ts +6 -2
  61. package/dist/modules/graceful_shutdown.js +6 -2
  62. package/dist/modules/launcher/bot_supervisor.js +4 -0
  63. package/dist/modules/launcher/credential_daemon.d.ts +14 -2
  64. package/dist/modules/launcher/credential_daemon.js +60 -26
  65. package/dist/modules/launcher/launch_modes.js +6 -3
  66. package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
  67. package/dist/modules/launcher/monolithic_runtime.js +60 -1
  68. package/dist/modules/launcher/runtime_mode.d.ts +79 -0
  69. package/dist/modules/launcher/runtime_mode.js +223 -0
  70. package/dist/modules/market_adapter_whitelist.d.ts +8 -0
  71. package/dist/modules/market_adapter_whitelist.js +8 -0
  72. package/dist/modules/order/accounting.d.ts +15 -1
  73. package/dist/modules/order/accounting.js +15 -1
  74. package/dist/modules/order/async_lock.d.ts +9 -3
  75. package/dist/modules/order/async_lock.js +9 -3
  76. package/dist/modules/order/export.d.ts +0 -5
  77. package/dist/modules/order/export.js +0 -5
  78. package/dist/modules/order/format.d.ts +6 -4
  79. package/dist/modules/order/format.js +6 -4
  80. package/dist/modules/order/grid.d.ts +36 -18
  81. package/dist/modules/order/grid.js +186 -33
  82. package/dist/modules/order/index.d.ts +16 -1
  83. package/dist/modules/order/index.js +1 -1
  84. package/dist/modules/order/logger_state.d.ts +1 -1
  85. package/dist/modules/order/logger_state.js +1 -1
  86. package/dist/modules/order/manager.d.ts +30 -7
  87. package/dist/modules/order/manager.js +108 -12
  88. package/dist/modules/order/strategy.d.ts +5 -0
  89. package/dist/modules/order/strategy.js +23 -2
  90. package/dist/modules/order/sync_engine.d.ts +26 -11
  91. package/dist/modules/order/sync_engine.js +26 -11
  92. package/dist/modules/order/utils/math.d.ts +100 -22
  93. package/dist/modules/order/utils/math.js +106 -22
  94. package/dist/modules/order/utils/order.d.ts +77 -20
  95. package/dist/modules/order/utils/order.js +125 -27
  96. package/dist/modules/order/utils/system.d.ts +107 -11
  97. package/dist/modules/order/utils/system.js +176 -11
  98. package/dist/modules/order/utils/validate.d.ts +8 -3
  99. package/dist/modules/order/utils/validate.js +10 -3
  100. package/dist/modules/types.d.ts +35 -2
  101. package/dist/modules/utils/asset_symbols.d.ts +5 -5
  102. package/dist/modules/utils/asset_symbols.js +5 -5
  103. package/dist/modules/utils/errors.d.ts +2 -1
  104. package/dist/modules/utils/errors.js +2 -1
  105. package/dist/scripts/analyze-credit.js +64 -23
  106. package/dist/scripts/bts_distribution.d.ts +66 -0
  107. package/dist/scripts/bts_distribution.js +2102 -0
  108. package/dist/scripts/rich_list.d.ts +32 -0
  109. package/dist/scripts/rich_list.js +16 -8
  110. package/dist/scripts/token_distribution.d.ts +45 -0
  111. package/dist/scripts/token_distribution.js +1870 -0
  112. package/dist/unlock.js +91 -42
  113. package/docs/BITSHARES_ONBOARDING.md +7 -0
  114. package/docs/COW_INVARIANTS.md +7 -1
  115. package/docs/DEXBOT_COMPARISON.md +5 -5
  116. package/docs/EVOLUTION.md +10 -8
  117. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -3
  118. package/docs/GRID_PRICE_INVARIANT.md +6 -0
  119. package/docs/GRID_RECALCULATION.md +18 -6
  120. package/docs/LIFECYCLE.md +8 -8
  121. package/docs/LOGGING.md +9 -0
  122. package/docs/MPA_CREDIT_USAGE.md +3 -2
  123. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +121 -4
  124. package/docs/README.md +1 -1
  125. package/docs/WORKFLOW.md +5 -5
  126. package/docs/architecture.md +98 -1
  127. package/market_adapter/README.md +10 -3
  128. package/package.json +5 -1
  129. package/scripts/README.md +85 -148
  130. package/tests/README.md +29 -0
@@ -4,56 +4,93 @@
4
4
  * Pure numeric calculations, blockchain conversions, fee math, and fund allocation.
5
5
  *
6
6
  * ===============================================================================
7
- * TABLE OF CONTENTS (44 exported functions)
7
+ * TABLE OF CONTENTS (78 exports)
8
8
  * ===============================================================================
9
9
  *
10
- * SECTION 1: PARSING & VALIDATION (6 functions)
10
+ * SECTION 1: GENESIS LADDER & RAIL GEOMETRY (28 items)
11
+ * - GridGenesis - Genesis ladder type: start price, increment, gap slots,
12
+ * price levels and their hash
13
+ * - priceLevelsForGenesis(genesis) - Extract the frozen price ladder from a genesis
14
+ * - buildGenesisFromPriceLevels(levels, config) - Build a genesis from precomputed levels
15
+ * - derivePriceLevels(startPrice, increment, minPrice, maxPrice) - Derive the
16
+ * geometric price ladder (the "rail") from a live config
17
+ * - hashPriceLevels(levels) - Deterministic hash of a price ladder
18
+ * - priceForSlot(idx, genesis) - Authoritative price for a slot index
19
+ * - slotIndexForPrice(price, genesis) - Resolve a price to its slot index
20
+ * - slotIdForPrice(price, genesis) - Resolve a price to its "slot-N" id
21
+ * - assertSlotPriceInvariant(...) - Reject a slot whose price disagrees with its index
22
+ * - priceSlotEqual(...) - Compare slot/price pairs under the genesis invariant
23
+ * - sameGridLevel(a, b) - Same ladder level, resolving each price against its genesis
24
+ * - sameGridPrice(a, b) - Same genesis-derived ladder level by precision
25
+ * - pricesOnSameLevel(a, b, ...) - Same order-book price LEVEL under precision
26
+ * - isChainPriceOutOfGrid(price, genesis, ...) - Whether a chain price is off the rail
27
+ * - getBtsSide(assets) - Which side of the pair holds BTS
28
+ * - getSellStartIdx(boundaryIdx, gapSlots) - Sell start index from boundary + gap
29
+ * - calculateGapSlots(incrementPercent, targetSpreadPercent) - Gap-slot count
30
+ * - resolveGapSlots(manager) - Configured gap-slot count for a manager
31
+ * - resolveGapBand(manager) - Gap-band geometry { start, end, gapSlots }
32
+ * - countGapBandSpread(manager) - Count SPREAD slots strictly inside the gap band
33
+ * - isSlotInRail(...) - Geometric rail-membership test for a slot
34
+ * - isSlotIndexInGapBand(idx, ...) - Whether a slot index sits inside the gap band
35
+ * - isEvacuationRotationAllowed(...) - Whether a gap-evacuation rotation is geometrically valid
36
+ * - isEvacuationSizeStillValid(...) - Re-proof a stamped evacuation size against live geometry
37
+ * - validateBoundaryCommit(...) - Validate a proposed boundary commit against geometry
38
+ * - validatePersistedBoundary(...) - Validate a boundary restored from disk
39
+ * - isTransientInBandRejection(reason) - Whether a persisted-boundary rejection is transient
40
+ * - BOUNDARY_REJECT_PLACED_IN_BAND - Rejection reason: target slot holds an in-band order
41
+ *
42
+ * SECTION 2: PARSING & VALIDATION (10 functions)
11
43
  * - isExplicitZeroAllocation(value) - Check if value is explicitly zero
12
44
  * - isPercentageString(v) - Check if value is percentage string
45
+ * - isPositiveNumber(value) - Check if value is a positive number
46
+ * - isPositiveNumberOrPercent(value) - Positive number or positive percentage string
47
+ * - isPositiveInt(value) - Check if value is a positive integer
13
48
  * - parsePercentageString(v) - Parse percentage string to decimal
49
+ * - toDecimal(value) - Convert number/percentage/numeric string to a decimal
14
50
  * - parseRelativeMultiplier(value) - Parse "3x" multiplier syntax to number
15
51
  * - resolveRelativePrice(value, startPrice, mode) - Resolve relative price values
16
52
  * - validateGridPriceBounds(min, max, center) - Reject bounds not bracketing center
17
53
  *
18
- * SECTION 2: FUND CALCULATIONS (4 functions)
54
+ * SECTION 3: FUND CALCULATIONS (8 functions)
19
55
  * - computeChainFundTotals(accountTotals, committedChain) - Compute total funds
20
56
  * - calculateAvailableFundsValue(side, accountTotals, funds, ...) - Calculate available funds
57
+ * - adjustBudgetForBtsFees(budget, btsFeeData, ...) - Reserve BTS fees from a side budget
58
+ * - getGridBestPrices(manager) - Best (highest) buy and best (lowest) sell price
21
59
  * - calculateSpreadFromOrders(activeBuys, activeSells) - Calculate spread percentage
22
60
  * - resolveConfigValue(value, total) - Resolve percentage or absolute config value
61
+ * - resolveConfigValueWithRegistry(value, total, registry) - Config value incl. shared-account funds
62
+ * - hasValidAccountTotals(accountTotals, checkFree) - Validate account totals structure
23
63
  *
24
- * SECTION 3: BLOCKCHAIN CONVERSIONS (5 functions)
64
+ * SECTION 4: BLOCKCHAIN CONVERSIONS (6 functions)
25
65
  * - blockchainToFloat(intValue, precision) - Convert blockchain int to float
26
66
  * - floatToBlockchainInt(floatValue, precision) - Convert float to blockchain int
67
+ * - floorToBlockchainInt(floatValue, precision) - Convert float to int by flooring
27
68
  * - quantizeFloat(value, precision) - Round float to blockchain precision
28
69
  * - normalizeInt(value, precision) - Normalize int within precision bounds
29
- * - hasValidAccountTotals(accountTotals, checkFree) - Validate account totals structure
70
+ * - quantumForPrecision(precision) - Smallest representable unit for a precision
30
71
  *
31
- * SECTION 4: PRECISION & FORMATTING UTILITIES (8 functions)
32
- * - roundTo(value, factor) - Round to a factor
33
- * - fixedTo(value, decimals) - Format to fixed decimal string
34
- * - roundToDecimals(value, decimals) - Round to N decimal places
72
+ * SECTION 5: PRECISION UTILITIES (4 functions)
35
73
  * - getPrecision(assets, orderType) - Get precision for order type
36
74
  * - getPrecisionByOrderType(assets, orderType) - Alias for getPrecision
37
- * - getPrecisionForSide(assets, side) - Get precision by side (buy/sell)
38
75
  * - getPrecisionsForManager(manager) - Get both asset precisions
39
76
  * - getPrecisionSlack(precision) - Calculate tolerance for precision
40
77
  *
41
- * SECTION 5: ORDER SIZE VALIDATION (7 functions)
78
+ * SECTION 6: ORDER SIZE VALIDATION (8 functions)
42
79
  * - calculatePriceTolerance(price, size, type, assets) - Calculate price match tolerance
80
+ * - findCrossedOrder(...) - Find an opposite-side order a placement would CROSS
43
81
  * - validateOrderAmountsWithinLimits(amountToSell, minToReceive) - Validate order limits
44
- * - getMinOrderSize(assets, type) - Get minimum order size for type
82
+ * - getMinOrderSize(orderType, assets, factor) - Get minimum order size
45
83
  * - getDustThresholdFactor() - Get dust threshold multiplier
46
84
  * - getSingleDustThreshold(idealSize, dustThresholdPercent) - Get single dust threshold
47
85
  * - getDoubleDustThreshold(idealSize, dustThresholdPercent) - Get double dust threshold
48
- * - getMinOrderSize(orderType, assets, factor) - Get minimum order size
49
86
  * - validateOrderSize(manager, size, type, context) - Validate order size against minimums
50
87
  *
51
- * SECTION 6: FEE CALCULATIONS (2 functions + 2 internal)
88
+ * SECTION 7: FEE CALCULATIONS (3 functions)
52
89
  * - getAssetFees(assetSymbol, assetAmount, isMaker) - Get fee info for asset
90
+ * - getAssetFeesSafe(assetSymbol, assetAmount, isMaker) - Fee info without throwing
53
91
  * - _setFeeCache(cache) - Set internal fee cache (internal)
54
- * - _getFeeCache() - Get internal fee cache (internal)
55
92
  *
56
- * SECTION 7: FUND ALLOCATION (6 functions)
93
+ * SECTION 8: FUND ALLOCATION (6 functions)
57
94
  * - allocateFundsByWeights(available, targetCount) - Allocate funds by weight
58
95
  * - cloneWeightDistribution(weightDistribution, base) - Clone weight distribution safely
59
96
  * - calculateOrderSizes(manager, orderType) - Calculate order sizes for placement
@@ -61,13 +98,14 @@
61
98
  * - calculateGridSideDivergenceMetric(manager, orderType, threshold) - Calculate divergence
62
99
  * - clamp(value, min, max) - Clamp a value between min and max bounds
63
100
  *
64
- * SECTION 8: FEE DEDUCTION (3 functions)
101
+ * SECTION 9: FEE DEDUCTION (2 functions)
65
102
  * - calculateOrderCreationFees(count, btsFeeData) - Calculate total creation fees
66
- * - deductOrderFeesFromFunds(available, count, btsFeeData, btsSide) - Deduct fees from funds
67
103
  * - calculateSwapInAmount(targetReceive, poolReserveOut, poolReserveIn) - AMM swap math
68
104
  *
69
- * SECTION 9: GRID UTILITIES (1 function)
70
- * - calculateGapSlots(incrementPercent, targetSpreadPercent) - Calculate gap slots count
105
+ * SECTION 10: FORMATTING (3 functions)
106
+ * - roundTo(value, factor) - Round to a factor
107
+ * - fixedTo(value, decimals) - Format to fixed decimal string
108
+ * - roundToDecimals(value, decimals) - Round to N decimal places
71
109
  *
72
110
  * ===============================================================================
73
111
  */
@@ -420,6 +458,52 @@ function getAssetFeesSafe(assetSymbol, assetAmount = null, isMaker = true) {
420
458
  return null;
421
459
  }
422
460
  }
461
+ /**
462
+ * Fund budget for placing a KNOWN set of pending slots (spread correction).
463
+ *
464
+ * `calculateAvailableFundsValue` computes `chainFree - virtual - fees`, where
465
+ * `virtual` is the projection of the side's not-yet-placed (VIRTUAL) slots.
466
+ * That is the right number for "how much room is left beyond the projected
467
+ * rail", but it is CIRCULAR when the caller is funding exactly those projected
468
+ * slots: if the projection is larger than the account holds free (a rail sized
469
+ * from a bigger balance, from inventory locked in resting orders, or from
470
+ * optimistic proceeds), `available` reads 0 while the chain clearly holds free
471
+ * funds, and the projection can never shrink because nothing gets placed.
472
+ * Live symptom: `planned 3, placing 0` every cycle for 84 minutes
473
+ * (`free 454560.80` vs `virtual 456046.21`).
474
+ *
475
+ * So for a known candidate set, re-derive the budget from chain truth: add the
476
+ * projection back, but never more than the candidates themselves need and never
477
+ * more than the chain actually holds free. The chain remains the final arbiter
478
+ * (an over-commit is rejected at broadcast), and the fee reservation stays
479
+ * inside `availableFund` for every healthy cycle.
480
+ *
481
+ * Only an OVERSUBSCRIPTION (projection > chain free) triggers the fallback. A
482
+ * zero caused by the fee reservation or by a genuinely empty balance is a real
483
+ * constraint: the projection fits, so honour it (and its fees) and place
484
+ * nothing.
485
+ *
486
+ * @param {{availableFund?: number, virtualIntent?: number, chainFree?: number, candidateIdeals?: number}} args
487
+ * @returns {{budget: number, oversubscribed: number, eroded: boolean}} budget to
488
+ * place with; projection excess over chain free (0 = healthy); whether the
489
+ * chain-truth re-derivation was needed
490
+ */
491
+ function deriveChainTruthFundBudget(args) {
492
+ const available = Math.max(0, toFiniteNumber(args?.availableFund, 0));
493
+ const virtual = Math.max(0, toFiniteNumber(args?.virtualIntent, 0));
494
+ const chainFree = Math.max(0, toFiniteNumber(args?.chainFree, 0));
495
+ const ideals = Math.max(0, toFiniteNumber(args?.candidateIdeals, 0));
496
+ const oversubscribed = Math.max(0, virtual - chainFree);
497
+ // `oversubscribed <= 0` means the projection FITS in the free balance, so a
498
+ // zero `available` is a real constraint (fees/reservation), not the circular
499
+ // case — never re-derive past it.
500
+ if (available > 0 || oversubscribed <= 0 || ideals <= 0 || chainFree <= 0) {
501
+ return { budget: available, oversubscribed, eroded: false };
502
+ }
503
+ // Oversubscribed: fund the candidates from what the chain really holds.
504
+ const budget = Math.min(chainFree, Math.min(virtual, ideals));
505
+ return { budget, oversubscribed, eroded: budget > 0 };
506
+ }
423
507
  /**
424
508
  * Calculate available funds for a specific side (buy or sell).
425
509
  * Deducts virtual reservations, BTS fees owed, and BTS fee reservation from chain-free balance.
@@ -1378,7 +1462,7 @@ function calculateSwapInAmount(targetReceive, poolReserveOut, poolReserveIn) {
1378
1462
  *
1379
1463
  * @param {number} incrementPercent - Grid increment percentage
1380
1464
  * @param {number} targetSpreadPercent - Target spread percentage
1381
- * @param {Object} GRID_LIMITS - Grid limits constants (optional, uses defaults)
1465
+ * @param {Object} [gridLimits] - Grid limits constants (optional, uses defaults)
1382
1466
  * @returns {number} Number of gap slots
1383
1467
  */
1384
1468
  function calculateGapSlots(incrementPercent, targetSpreadPercent, gridLimits = {}) {
@@ -2064,7 +2148,7 @@ function buildGenesisFromPriceLevels(startPrice, incrementPercent, gapSlots, pri
2064
2148
  createdAt: Date.now()
2065
2149
  };
2066
2150
  }
2067
- export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
2151
+ export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
2068
2152
  /**
2069
2153
  * Round a value to a given factor.
2070
2154
  * @param {number} value - Value to round
@@ -5,68 +5,112 @@
5
5
  * Includes grid indexing, order comparison, delta building, and strategy calculations.
6
6
  *
7
7
  * ===============================================================================
8
- * TABLE OF CONTENTS (35 exported functions)
8
+ * TABLE OF CONTENTS (76 exported functions)
9
9
  * ===============================================================================
10
10
  *
11
- * SECTION 1: CHAIN ORDER MATCHING & RECONCILIATION (5 functions)
11
+ * SECTION 1: CHAIN ORDER MATCHING & RECONCILIATION (7 functions)
12
12
  * - parseChainOrder(chainOrder, assets) - Parse blockchain order to grid format
13
13
  * - applyChainSizeToGridOrder(manager, gridOrder, chainSize) - Apply chain size to grid
14
14
  * - correctOrderPriceOnChain(manager, correctionInfo, ...) - Correct order price on chain
15
15
  * - correctAllPriceMismatches(manager, accountName, ...) - Correct all price mismatches
16
- *
17
- * SECTION 2: ORDER CONSTRUCTION (3 functions)
16
+ * - _validatePriceCorrectionEntry(...) - Drain-time staleness check for a queued correction
17
+ * - _stampCorrectionProvenance(...) - Stamp queue provenance on a correction entry
18
+ * - findLiveOrderOwnerByChainId(...) - Find the live grid slot that owns a chain order
19
+ *
20
+ * SECTION 2: CROSSING-PLACEMENT GUARDS (8 functions)
21
+ * - chainOrderMatchesSlot(...) - Exact chain-order/grid-slot match
22
+ * - chainOrderMatchesSlotWithTolerance(...) - Match within price tolerance
23
+ * - crossingCandidateChainId(order) - Chain id of a crossing-check candidate
24
+ * - isCrossingCheckCandidate(order) - Predicate for crossing-placement guards
25
+ * - buildCrossingCheckCandidates(...) - Candidate set for crossing-placement checks
26
+ * - chainOrderUnchangedFromCache(...) - Chain order still matches cached pre-update state
27
+ * - detectCrossedBookPlan(...) - Pre-broadcast crossed-book assert
28
+ * - collectKnownOnChainOrderIds(...) - On-chain ids master must converge against
29
+ *
30
+ * SECTION 3: ORDER CONSTRUCTION (5 functions)
18
31
  * - buildCreateOrderArgs(order, assetA, assetB) - Build create order arguments
19
32
  * - getOrderTypeFromUpdatedFlags(buyUpdated, sellUpdated) - Get type from update flags
20
33
  * - resolveConfiguredPriceBound(value, fallback, startPrice, mode) - Resolve price bounds
21
34
  * - buildFillKey(fillOrParts) - Build a stable fill dedupe key
22
35
  * - buildCreateOpFingerprint(params) - Build fingerprint for create operations
23
36
  *
24
- * SECTION 3: STATE TRANSITIONS (2 functions)
37
+ * SECTION 4: STATE TRANSITIONS & PLACEHOLDERS (6 functions)
25
38
  * - virtualizeOrder(order) - Convert order to VIRTUAL state
26
39
  * - convertToSpreadPlaceholder(order) - Convert order to SPREAD placeholder
27
- *
28
- * SECTION 4: FILTERING & COUNTING (5 functions)
40
+ * - toRailHolePlaceholder(order) - Convert to a rail-typed hole placeholder
41
+ * - geometryTypeForSlotIndex(...) - BUY/SELL type for a slot index
42
+ * - resolveSpreadOrderSide(order) - Resolve the real side of a SPREAD slot
43
+ * - resolveOnChainRetypeType(...) - Type to keep when a live-order slot would retype
44
+ *
45
+ * SECTION 5: GAP EVACUATION (3 functions)
46
+ * - detectGapEvacuationCandidates(...) - Detect gap-evacuation candidates by geometry
47
+ * - updateGapEvacuationStreaks(...) - Tick per-slot gap-evacuation streak counter
48
+ * - collectRefillSlotIds(...) - Refill-slot wire for the COW boundary hold
49
+ *
50
+ * SECTION 6: FILTERING & DRIFT DIAGNOSTICS (12 functions)
51
+ * - parseSlotIndex(id) - Parse "slot-N" to its rail index
29
52
  * - filterOrdersByType(orders, orderType) - Filter orders by type
30
-
31
53
  * - buildOutsideInPairGroups(items, accessors) - Outside->center pair grouping
32
54
  * - extractBatchOperationResults(result) - Extract operation_results from chain batch result
33
55
  * - formatUnmatchedChainOrder(order) - Format structural drift diagnostics
34
- *
35
- * SECTION 5: STATE PREDICATES (7 functions)
56
+ * - isNonBlockingUnmatchedOrder(...) - Deliberate hold that must not read as drift
57
+ * - isStrandedHoldOrder(...) - Stranded hold detection
58
+ * - isOrderGoneErrorMessage(err) - Detect "chain order does not exist"
59
+ * - recordDuplicateOrphanDetection(orderId) - Record a duplicate-orphan detection
60
+ * - clearDuplicateOrphanDetection(orderId) - Clear the detection counter
61
+ * - duplicateOrphanLogInfo(...) - Log level + re-detection info for duplicate orphans
62
+ * - _filterUnmatchedChainOrders(...) - Drop a satisfied id from the unmatched list
63
+ *
64
+ * SECTION 7: STATE PREDICATES (8 functions)
36
65
  * - isOrderOnChain(order) - Check if order is ACTIVE or PARTIAL
37
66
  * - isOrderVirtual(order) - Check if order is VIRTUAL
38
67
  * - hasOnChainId(order) - Check if order has blockchain orderId
39
68
  * - isOrderPlaced(order) - Check if order is placed on chain
40
69
  * - isPhantomOrder(order) - Check if order is phantom (ACTIVE without orderId)
41
70
  * - isSlotAvailable(order) - Check if slot is available for placement
71
+ * - isEmptyGridSlot(order) - Empty reusable placeholder test
42
72
  * - isOrderHealthy(order, context) - Comprehensive order health check
43
73
  *
44
- * SECTION 6: SIZE VALIDATION (2 functions)
74
+ * SECTION 8: SIZE VALIDATION (2 functions)
45
75
  * - checkSizeThreshold(size, threshold) - Check if size exceeds threshold
46
76
  * - checkSizesBeforeMinimum(sizes, minSize) - Check sizes against minimum
47
77
  *
48
- * SECTION 7: GRID BOUNDARY & ROLES (3 functions)
78
+ * SECTION 9: GRID BOUNDARY & ROLES (5 functions)
49
79
  * - calculateIdealBoundary(allSlots, startPrice, gapSlots) - Calculate ideal boundary
50
80
  * - assignGridRoles(allSlots, boundaryIdx, gapSlots, ...) - Assign BUY/SELL roles
51
81
  * - shouldFlagOutOfSpread(order, startPrice, configSpread) - Check if order is out of spread
82
+ * - deriveTargetBoundary(...) - Target boundary for a rebalance plan
83
+ * - isShiftEligibleFill(...) - Whether a fill may drive boundary shift/rotation
52
84
  *
53
- * SECTION 8: GRID INDEXING (2 functions)
85
+ * SECTION 10: GRID INDEXING (2 functions)
54
86
  * - buildIndexes(grid) - Build complete index set from grid
55
87
  * - validateIndexes(grid, indexes) - Validate index consistency
56
88
  *
57
- * SECTION 9: ORDER COMPARISON & DELTA (3 functions)
89
+ * SECTION 11: ORDER COMPARISON & DELTA (2 functions)
58
90
  * - ordersEqual(a, b) - Compare two orders for equality
59
91
  * - buildDelta(masterGrid, workingGrid) - Build delta actions between grids
60
- * - getOrderSize(order) - Extract order size with fallback
61
92
  *
62
- * SECTION 10: STRATEGY CALCULATIONS (7 functions)
93
+ * SECTION 12: STRATEGY / EDGE / BUDGET (11 functions)
63
94
  * - resolveEdgeCount(config, side) - Clamped per-side edge count (>=0 int, 0 disables)
64
95
  * - resolveEdgeOrders(config) - Total edge orders buy+sell (fee/count totals)
65
- * - resolveLiveEdgeAnchorPrice(manager, side) - Live-grid edge anchor (genesis ladder extreme; null when no usable ladder)
96
+ * - selectEdgeSlots(sortedAsc, count, excludeIds, edge, anchorPrice?) - Shared position picker (both edges anchor toward their bound)
97
+ * - getCoreOrdersTotal(config) - Total target order count across both sides
98
+ * - getSideBudget(...) - Side budget after BTS fee deduction
99
+ * - calculateBudgetedSizes(...) - Sizes for all slots on a side using weighted distribution
100
+ * - edgeOrderIdSet(allSlots, config, orderType, anchorPrice?, excludeIds?) - Edge order id set (config count; shares the picker ordering; excludeIds carries the window exclusion)
101
+ * - liveWindowIdSet(...) - Window member ids for one side from the live manager
66
102
  * - resolveEdgeAnchorPrice(config, side) - Config-bound anchor fallback (buy→minPrice, sell→maxPrice; null when unresolvable)
103
+ * - resolveLiveEdgeAnchorPrice(manager, side) - Live-grid edge anchor (genesis ladder extreme; null when no usable ladder)
67
104
  * - compareEdge(a, b, edge, anchorPrice) - Shared anchored edge comparator (single ordering source)
68
- * - edgeOrderIdSet(allSlots, config, orderType, anchorPrice?, excludeIds?) - Edge order id set (config count; shares the picker ordering; excludeIds carries the window exclusion)
69
- * - selectEdgeSlots(sortedAsc, count, excludeIds, edge, anchorPrice?) - Shared position picker (both edges anchor toward their bound)
105
+ *
106
+ * SECTION 13: GRID PRICE INVARIANT (2 functions)
107
+ * - checkGridPriceInvariant(...) - The price emitted for a slot must equal its genesis price
108
+ * - reportGridPriceInvariant(...) - Report one GRID-PRICE-INVARIANT check
109
+ *
110
+ * SECTION 14: PERSISTED CRAWL & PLACEMENT GRACE (3 functions)
111
+ * - consumePendingFillCrawls(...) - Apply recorded-but-uncommitted fill crawls to the boundary
112
+ * - recordOrderPlacement(...) - Record a fresh on-chain placement timestamp
113
+ * - isFreshlyPlacedOrder(...) - Chain order placed within the surplus-cancel grace
70
114
  *
71
115
  * ===============================================================================
72
116
  */
@@ -732,7 +776,7 @@ declare function isOrderOnChain(order: SlotLike | null | undefined): boolean;
732
776
  * @param {Object} slot - The slot being retyped
733
777
  * @param {number} idx - Slot index
734
778
  * @param {number} buyEndIdx - Boundary index (last BUY slot)
735
- * @param {Object} ORDER_TYPES - ORDER_TYPES constants
779
+ * @param {Object} orderTypes - ORDER_TYPES constants
736
780
  * @returns {string} Type to keep for the on-chain slot
737
781
  */
738
782
  declare function resolveOnChainRetypeType(slot: SlotLike, idx: number, buyEndIdx: number, orderTypes: {
@@ -995,6 +1039,17 @@ declare function buildDelta(masterGrid: Map<string, ManagedOrder>, workingGrid:
995
1039
  priceRelativeTolerance?: number;
996
1040
  };
997
1041
  }): DeltaAction[];
1042
+ /**
1043
+ * A pending-crawl ledger entry as consumed by a derivation.
1044
+ * `ts` is carried so the commit clears exactly the records the derivation
1045
+ * folded — never a newer record for the same slot (recording happens at fill
1046
+ * intake, so a slot can be re-recorded between derivation and commit).
1047
+ */
1048
+ type CrawlEntry = {
1049
+ slotId: string;
1050
+ side: string;
1051
+ ts?: number;
1052
+ };
998
1053
  /**
999
1054
  * Check whether a fill is eligible to drive boundary shift / rotation.
1000
1055
  * Partials only count when they are delayed-rotation triggers.
@@ -1031,6 +1086,7 @@ declare function deriveTargetBoundary(fills: Array<{
1031
1086
  } | null): {
1032
1087
  boundaryIdx: number | null;
1033
1088
  remainingBudget: number;
1089
+ consumedCrawlIds: CrawlEntry[];
1034
1090
  };
1035
1091
  /**
1036
1092
  * Apply recorded-but-uncommitted fill crawls to the committed boundary.
@@ -1359,5 +1415,6 @@ declare function collectKnownOnChainOrderIds(mgr: OrderManagerLike, placedResult
1359
1415
  all: string[];
1360
1416
  };
1361
1417
  export { parseChainOrder, applyChainSizeToGridOrder, buildFillKey, correctOrderPriceOnChain, correctAllPriceMismatches, _validatePriceCorrectionEntry, _stampCorrectionProvenance, findLiveOrderOwnerByChainId, buildCreateOrderArgs, getOrderTypeFromUpdatedFlags, resolveConfiguredPriceBound, virtualizeOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, detectGapEvacuationCandidates, updateGapEvacuationStreaks, resolveSpreadOrderSide, chainOrderMatchesSlot, chainOrderMatchesSlotWithTolerance, crossingCandidateChainId, isCrossingCheckCandidate, buildCrossingCheckCandidates, parseSlotIndex, filterOrdersByType, buildOutsideInPairGroups, extractBatchOperationResults, formatUnmatchedChainOrder, isNonBlockingUnmatchedOrder, isStrandedHoldOrder, isOrderOnChain, isOrderVirtual, hasOnChainId, isOrderPlaced, isPhantomOrder, isSlotAvailable, isEmptyGridSlot, isOrderHealthy, checkSizeThreshold, checkSizesBeforeMinimum, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, shouldFlagOutOfSpread, buildIndexes, validateIndexes, ordersEqual, buildDelta, deriveTargetBoundary, isShiftEligibleFill, resolveEdgeCount, resolveEdgeOrders, selectEdgeSlots, getCoreOrdersTotal, getSideBudget, calculateBudgetedSizes, buildCreateOpFingerprint, isOrderGoneErrorMessage, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
1418
+ export type { CrawlEntry };
1362
1419
  export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
1363
1420
  //# sourceMappingURL=order.d.ts.map
@@ -5,68 +5,112 @@
5
5
  * Includes grid indexing, order comparison, delta building, and strategy calculations.
6
6
  *
7
7
  * ===============================================================================
8
- * TABLE OF CONTENTS (35 exported functions)
8
+ * TABLE OF CONTENTS (76 exported functions)
9
9
  * ===============================================================================
10
10
  *
11
- * SECTION 1: CHAIN ORDER MATCHING & RECONCILIATION (5 functions)
11
+ * SECTION 1: CHAIN ORDER MATCHING & RECONCILIATION (7 functions)
12
12
  * - parseChainOrder(chainOrder, assets) - Parse blockchain order to grid format
13
13
  * - applyChainSizeToGridOrder(manager, gridOrder, chainSize) - Apply chain size to grid
14
14
  * - correctOrderPriceOnChain(manager, correctionInfo, ...) - Correct order price on chain
15
15
  * - correctAllPriceMismatches(manager, accountName, ...) - Correct all price mismatches
16
- *
17
- * SECTION 2: ORDER CONSTRUCTION (3 functions)
16
+ * - _validatePriceCorrectionEntry(...) - Drain-time staleness check for a queued correction
17
+ * - _stampCorrectionProvenance(...) - Stamp queue provenance on a correction entry
18
+ * - findLiveOrderOwnerByChainId(...) - Find the live grid slot that owns a chain order
19
+ *
20
+ * SECTION 2: CROSSING-PLACEMENT GUARDS (8 functions)
21
+ * - chainOrderMatchesSlot(...) - Exact chain-order/grid-slot match
22
+ * - chainOrderMatchesSlotWithTolerance(...) - Match within price tolerance
23
+ * - crossingCandidateChainId(order) - Chain id of a crossing-check candidate
24
+ * - isCrossingCheckCandidate(order) - Predicate for crossing-placement guards
25
+ * - buildCrossingCheckCandidates(...) - Candidate set for crossing-placement checks
26
+ * - chainOrderUnchangedFromCache(...) - Chain order still matches cached pre-update state
27
+ * - detectCrossedBookPlan(...) - Pre-broadcast crossed-book assert
28
+ * - collectKnownOnChainOrderIds(...) - On-chain ids master must converge against
29
+ *
30
+ * SECTION 3: ORDER CONSTRUCTION (5 functions)
18
31
  * - buildCreateOrderArgs(order, assetA, assetB) - Build create order arguments
19
32
  * - getOrderTypeFromUpdatedFlags(buyUpdated, sellUpdated) - Get type from update flags
20
33
  * - resolveConfiguredPriceBound(value, fallback, startPrice, mode) - Resolve price bounds
21
34
  * - buildFillKey(fillOrParts) - Build a stable fill dedupe key
22
35
  * - buildCreateOpFingerprint(params) - Build fingerprint for create operations
23
36
  *
24
- * SECTION 3: STATE TRANSITIONS (2 functions)
37
+ * SECTION 4: STATE TRANSITIONS & PLACEHOLDERS (6 functions)
25
38
  * - virtualizeOrder(order) - Convert order to VIRTUAL state
26
39
  * - convertToSpreadPlaceholder(order) - Convert order to SPREAD placeholder
27
- *
28
- * SECTION 4: FILTERING & COUNTING (5 functions)
40
+ * - toRailHolePlaceholder(order) - Convert to a rail-typed hole placeholder
41
+ * - geometryTypeForSlotIndex(...) - BUY/SELL type for a slot index
42
+ * - resolveSpreadOrderSide(order) - Resolve the real side of a SPREAD slot
43
+ * - resolveOnChainRetypeType(...) - Type to keep when a live-order slot would retype
44
+ *
45
+ * SECTION 5: GAP EVACUATION (3 functions)
46
+ * - detectGapEvacuationCandidates(...) - Detect gap-evacuation candidates by geometry
47
+ * - updateGapEvacuationStreaks(...) - Tick per-slot gap-evacuation streak counter
48
+ * - collectRefillSlotIds(...) - Refill-slot wire for the COW boundary hold
49
+ *
50
+ * SECTION 6: FILTERING & DRIFT DIAGNOSTICS (12 functions)
51
+ * - parseSlotIndex(id) - Parse "slot-N" to its rail index
29
52
  * - filterOrdersByType(orders, orderType) - Filter orders by type
30
-
31
53
  * - buildOutsideInPairGroups(items, accessors) - Outside->center pair grouping
32
54
  * - extractBatchOperationResults(result) - Extract operation_results from chain batch result
33
55
  * - formatUnmatchedChainOrder(order) - Format structural drift diagnostics
34
- *
35
- * SECTION 5: STATE PREDICATES (7 functions)
56
+ * - isNonBlockingUnmatchedOrder(...) - Deliberate hold that must not read as drift
57
+ * - isStrandedHoldOrder(...) - Stranded hold detection
58
+ * - isOrderGoneErrorMessage(err) - Detect "chain order does not exist"
59
+ * - recordDuplicateOrphanDetection(orderId) - Record a duplicate-orphan detection
60
+ * - clearDuplicateOrphanDetection(orderId) - Clear the detection counter
61
+ * - duplicateOrphanLogInfo(...) - Log level + re-detection info for duplicate orphans
62
+ * - _filterUnmatchedChainOrders(...) - Drop a satisfied id from the unmatched list
63
+ *
64
+ * SECTION 7: STATE PREDICATES (8 functions)
36
65
  * - isOrderOnChain(order) - Check if order is ACTIVE or PARTIAL
37
66
  * - isOrderVirtual(order) - Check if order is VIRTUAL
38
67
  * - hasOnChainId(order) - Check if order has blockchain orderId
39
68
  * - isOrderPlaced(order) - Check if order is placed on chain
40
69
  * - isPhantomOrder(order) - Check if order is phantom (ACTIVE without orderId)
41
70
  * - isSlotAvailable(order) - Check if slot is available for placement
71
+ * - isEmptyGridSlot(order) - Empty reusable placeholder test
42
72
  * - isOrderHealthy(order, context) - Comprehensive order health check
43
73
  *
44
- * SECTION 6: SIZE VALIDATION (2 functions)
74
+ * SECTION 8: SIZE VALIDATION (2 functions)
45
75
  * - checkSizeThreshold(size, threshold) - Check if size exceeds threshold
46
76
  * - checkSizesBeforeMinimum(sizes, minSize) - Check sizes against minimum
47
77
  *
48
- * SECTION 7: GRID BOUNDARY & ROLES (3 functions)
78
+ * SECTION 9: GRID BOUNDARY & ROLES (5 functions)
49
79
  * - calculateIdealBoundary(allSlots, startPrice, gapSlots) - Calculate ideal boundary
50
80
  * - assignGridRoles(allSlots, boundaryIdx, gapSlots, ...) - Assign BUY/SELL roles
51
81
  * - shouldFlagOutOfSpread(order, startPrice, configSpread) - Check if order is out of spread
82
+ * - deriveTargetBoundary(...) - Target boundary for a rebalance plan
83
+ * - isShiftEligibleFill(...) - Whether a fill may drive boundary shift/rotation
52
84
  *
53
- * SECTION 8: GRID INDEXING (2 functions)
85
+ * SECTION 10: GRID INDEXING (2 functions)
54
86
  * - buildIndexes(grid) - Build complete index set from grid
55
87
  * - validateIndexes(grid, indexes) - Validate index consistency
56
88
  *
57
- * SECTION 9: ORDER COMPARISON & DELTA (3 functions)
89
+ * SECTION 11: ORDER COMPARISON & DELTA (2 functions)
58
90
  * - ordersEqual(a, b) - Compare two orders for equality
59
91
  * - buildDelta(masterGrid, workingGrid) - Build delta actions between grids
60
- * - getOrderSize(order) - Extract order size with fallback
61
92
  *
62
- * SECTION 10: STRATEGY CALCULATIONS (7 functions)
93
+ * SECTION 12: STRATEGY / EDGE / BUDGET (11 functions)
63
94
  * - resolveEdgeCount(config, side) - Clamped per-side edge count (>=0 int, 0 disables)
64
95
  * - resolveEdgeOrders(config) - Total edge orders buy+sell (fee/count totals)
65
- * - resolveLiveEdgeAnchorPrice(manager, side) - Live-grid edge anchor (genesis ladder extreme; null when no usable ladder)
96
+ * - selectEdgeSlots(sortedAsc, count, excludeIds, edge, anchorPrice?) - Shared position picker (both edges anchor toward their bound)
97
+ * - getCoreOrdersTotal(config) - Total target order count across both sides
98
+ * - getSideBudget(...) - Side budget after BTS fee deduction
99
+ * - calculateBudgetedSizes(...) - Sizes for all slots on a side using weighted distribution
100
+ * - edgeOrderIdSet(allSlots, config, orderType, anchorPrice?, excludeIds?) - Edge order id set (config count; shares the picker ordering; excludeIds carries the window exclusion)
101
+ * - liveWindowIdSet(...) - Window member ids for one side from the live manager
66
102
  * - resolveEdgeAnchorPrice(config, side) - Config-bound anchor fallback (buy→minPrice, sell→maxPrice; null when unresolvable)
103
+ * - resolveLiveEdgeAnchorPrice(manager, side) - Live-grid edge anchor (genesis ladder extreme; null when no usable ladder)
67
104
  * - compareEdge(a, b, edge, anchorPrice) - Shared anchored edge comparator (single ordering source)
68
- * - edgeOrderIdSet(allSlots, config, orderType, anchorPrice?, excludeIds?) - Edge order id set (config count; shares the picker ordering; excludeIds carries the window exclusion)
69
- * - selectEdgeSlots(sortedAsc, count, excludeIds, edge, anchorPrice?) - Shared position picker (both edges anchor toward their bound)
105
+ *
106
+ * SECTION 13: GRID PRICE INVARIANT (2 functions)
107
+ * - checkGridPriceInvariant(...) - The price emitted for a slot must equal its genesis price
108
+ * - reportGridPriceInvariant(...) - Report one GRID-PRICE-INVARIANT check
109
+ *
110
+ * SECTION 14: PERSISTED CRAWL & PLACEMENT GRACE (3 functions)
111
+ * - consumePendingFillCrawls(...) - Apply recorded-but-uncommitted fill crawls to the boundary
112
+ * - recordOrderPlacement(...) - Record a fresh on-chain placement timestamp
113
+ * - isFreshlyPlacedOrder(...) - Chain order placed within the surplus-cancel grace
70
114
  *
71
115
  * ===============================================================================
72
116
  */
@@ -1835,7 +1879,7 @@ function isOrderOnChain(order) {
1835
1879
  * @param {Object} slot - The slot being retyped
1836
1880
  * @param {number} idx - Slot index
1837
1881
  * @param {number} buyEndIdx - Boundary index (last BUY slot)
1838
- * @param {Object} ORDER_TYPES - ORDER_TYPES constants
1882
+ * @param {Object} orderTypes - ORDER_TYPES constants
1839
1883
  * @returns {string} Type to keep for the on-chain slot
1840
1884
  */
1841
1885
  function resolveOnChainRetypeType(slot, idx, buyEndIdx, orderTypes) {
@@ -2323,9 +2367,14 @@ function buildDelta(masterGrid, workingGrid, options = {}) {
2323
2367
  }
2324
2368
  return actions;
2325
2369
  }
2326
- // ================================================================================
2327
- // SECTION 10: STRATEGY CALCULATIONS
2328
- // ================================================================================
2370
+ /** Normalise a ledger record into the identity the commit clears by. */
2371
+ function toCrawlEntry(e) {
2372
+ return {
2373
+ slotId: String(e?.slotId ?? ''),
2374
+ side: String(e?.side ?? ''),
2375
+ ts: Number.isFinite(Number(e?.ts)) ? Number(e?.ts) : undefined,
2376
+ };
2377
+ }
2329
2378
  /**
2330
2379
  * Check whether a fill is eligible to drive boundary shift / rotation.
2331
2380
  * Partials only count when they are delayed-rotation triggers.
@@ -2426,7 +2475,7 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2426
2475
  if (referencePrice === null) {
2427
2476
  const fallbackCap = Math.max(Math.floor((config?.coreOrders?.sell ?? 1) / 2), Math.floor((config?.coreOrders?.buy ?? 1) / 2), 1);
2428
2477
  const effectiveBudget = crossChunkBudget ?? fallbackCap;
2429
- return { boundaryIdx: null, remainingBudget: effectiveBudget };
2478
+ return { boundaryIdx: null, remainingBudget: effectiveBudget, consumedCrawlIds: [] };
2430
2479
  }
2431
2480
  newBoundaryIdx = calculateIdealBoundary(allSlots, referencePrice, gapSlots);
2432
2481
  if (!Number.isFinite(newBoundaryIdx) || newBoundaryIdx < 0) {
@@ -2434,7 +2483,7 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2434
2483
  // exists (calculateIdealBoundary returns -1). Stay null rather
2435
2484
  // than letting the clamp below fabricate a slot-0 boundary.
2436
2485
  const fallbackCap = Math.max(Math.floor((config?.coreOrders?.sell ?? 1) / 2), Math.floor((config?.coreOrders?.buy ?? 1) / 2), 1);
2437
- return { boundaryIdx: null, remainingBudget: crossChunkBudget ?? fallbackCap };
2486
+ return { boundaryIdx: null, remainingBudget: crossChunkBudget ?? fallbackCap, consumedCrawlIds: [] };
2438
2487
  }
2439
2488
  recovered = true;
2440
2489
  }
@@ -2466,12 +2515,50 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2466
2515
  // anything older is still owed and shifts here. Edge-slot entries
2467
2516
  // never crawl (static insurance), same as live fills.
2468
2517
  const currentSlotIds = new Set((fills ?? []).map((f) => f?.id).filter((id) => typeof id === 'string' && id.length > 0));
2469
- const owedPending = (pendingCrawls ?? []).filter((e) => e
2470
- && typeof e.slotId === 'string' && e.slotId.length > 0
2518
+ const allPending = (pendingCrawls ?? [])
2519
+ .filter((e) => !!e
2520
+ && typeof e.slotId === 'string' && e.slotId.length > 0);
2521
+ const owedPending = allPending.filter((e) => e
2471
2522
  && !currentSlotIds.has(e.slotId)
2472
2523
  && (e.side === ORDER_TYPES.BUY || e.side === ORDER_TYPES.SELL)
2473
2524
  && !(e.side === ORDER_TYPES.BUY && edgeBuyIds && edgeBuyIds.has(e.slotId))
2474
2525
  && !(e.side === ORDER_TYPES.SELL && edgeSellIds && edgeSellIds.has(e.slotId)));
2526
+ /**
2527
+ * Ledger records this derivation CONSUMED:
2528
+ * - everything it deliberately never counts (current-batch slots whose
2529
+ * shift comes from `fills`, edge-classified slots which never crawl,
2530
+ * malformed records), and
2531
+ * - the owed entries whose shift it actually APPLIED.
2532
+ *
2533
+ * `applied` is the (possibly capped) net shift. A capped fold applies only
2534
+ * part of the owed net, so only that part may be consumed — the remainder
2535
+ * stays owed, or the next derivation would either lose it (clear-all) or
2536
+ * apply it twice (keep-all).
2537
+ */
2538
+ const consumedFor = (applied) => {
2539
+ const never = allPending.filter((e) => !owedPending.includes(e));
2540
+ let appliedEntries = [];
2541
+ if (cap <= 0) {
2542
+ // No cross-chunk budget left: NOTHING was applied, so every owed
2543
+ // record stays owed (a net-zero reading here is not a cancellation).
2544
+ appliedEntries = [];
2545
+ }
2546
+ else if (applied === 0) {
2547
+ // A net-zero mix was fully accounted for by cancelling out.
2548
+ appliedEntries = owedPending;
2549
+ }
2550
+ else {
2551
+ // Consume same-side entries up to the applied magnitude; the mixed
2552
+ // remainder still nets out to (net - applied) for the next run.
2553
+ const dirSide = applied > 0 ? ORDER_TYPES.SELL : ORDER_TYPES.BUY;
2554
+ appliedEntries = owedPending
2555
+ .filter((e) => e.side === dirSide)
2556
+ .slice(0, Math.abs(applied));
2557
+ }
2558
+ return [...never, ...appliedEntries].map(toCrawlEntry);
2559
+ };
2560
+ /** Every owed record is subsumed (absolute anchor / generation discard). */
2561
+ const consumedAll = () => allPending.map(toCrawlEntry);
2475
2562
  for (const fill of fills ?? []) {
2476
2563
  if (!isShiftEligibleFill(fill))
2477
2564
  continue;
@@ -2512,8 +2599,18 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2512
2599
  return {
2513
2600
  boundaryIdx: Math.max(0, Math.min((allSlots.length - gapSlots - 1) >= 0 ? (allSlots.length - gapSlots - 1) : (allSlots.length - 1), newBoundaryIdx)),
2514
2601
  remainingBudget: effectiveBudget,
2602
+ // The absolute fill anchor positions from live prices, which already
2603
+ // reflect every owed delta. The remaining delta is NOT added on top
2604
+ // (double-count guard), so every record is subsumed regardless of
2605
+ // what the cap would have admitted.
2606
+ consumedCrawlIds: consumedAll(),
2515
2607
  };
2516
2608
  }
2609
+ // A truncated shift (or an exhausted cross-chunk budget) applies only part
2610
+ // of the owed net, so the consumed set below is scoped to WHAT WAS APPLIED:
2611
+ // the commit must neither lose the remainder (the 2026-10-25 leak: 7 fills,
2612
+ // boundary +3 planned, all 7 records dropped) nor leave an applied entry
2613
+ // owed for a second pass.
2517
2614
  if (Math.abs(netShift) > cap) {
2518
2615
  netShift = Math.sign(netShift) * cap;
2519
2616
  }
@@ -2531,6 +2628,7 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2531
2628
  return {
2532
2629
  boundaryIdx: Math.max(0, Math.min(ceiling, newBoundaryIdx)),
2533
2630
  remainingBudget,
2631
+ consumedCrawlIds: consumedFor(netShift),
2534
2632
  };
2535
2633
  }
2536
2634
  /**