dexbot 1.6.14 → 1.6.16

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 (134) hide show
  1. package/CHANGELOG.md +60 -4
  2. package/README.md +4 -4
  3. package/analysis/README.md +6 -6
  4. package/analysis/tradingview/README.md +2 -1
  5. package/claw/README.md +7 -7
  6. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
  7. package/claw/modules/chain_queries.ts +3 -3
  8. package/claw/package.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  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/tradingview_uplot_chart_generator.d.ts +2 -1
  20. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +99 -11
  21. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +57 -4
  22. package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
  23. package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
  24. package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
  25. package/dist/dexbot.js +112 -141
  26. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
  27. package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
  28. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
  29. package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
  30. package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
  31. package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
  32. package/dist/market_adapter/inputs/window_cache.js +53 -17
  33. package/dist/market_adapter/lp_chart_core.js +1 -0
  34. package/dist/market_adapter/utils/chain.js +4 -3
  35. package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
  36. package/dist/market_adapter/utils/pair_orientation.js +142 -0
  37. package/dist/modules/account_bots.d.ts +40 -3
  38. package/dist/modules/account_bots.js +80 -37
  39. package/dist/modules/account_orders.d.ts +4 -1
  40. package/dist/modules/account_orders.js +4 -1
  41. package/dist/modules/bitshares-native/resolvers.js +3 -3
  42. package/dist/modules/bitshares-native/subscriptions.js +1 -1
  43. package/dist/modules/bitshares_client.d.ts +12 -10
  44. package/dist/modules/bitshares_client.js +12 -10
  45. package/dist/modules/bot_defaults.d.ts +13 -2
  46. package/dist/modules/bot_defaults.js +31 -2
  47. package/dist/modules/bot_settings.js +6 -3
  48. package/dist/modules/chain_keys.d.ts +5 -1
  49. package/dist/modules/chain_keys.js +5 -1
  50. package/dist/modules/chain_orders.d.ts +6 -2
  51. package/dist/modules/chain_orders.js +6 -2
  52. package/dist/modules/constants.d.ts +11 -0
  53. package/dist/modules/constants.js +31 -1
  54. package/dist/modules/credit_runtime.d.ts +35 -5
  55. package/dist/modules/credit_runtime.js +219 -38
  56. package/dist/modules/dexbot_class.d.ts +22 -2
  57. package/dist/modules/dexbot_class.js +61 -21
  58. package/dist/modules/dexbot_cow_runtime.js +19 -18
  59. package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
  60. package/dist/modules/dexbot_fill_runtime.js +4 -7
  61. package/dist/modules/dexbot_maintenance_runtime.d.ts +7 -2
  62. package/dist/modules/dexbot_maintenance_runtime.js +52 -7
  63. package/dist/modules/dexbot_startup_runtime.js +3 -2
  64. package/dist/modules/dexbot_state_recovery.js +1 -1
  65. package/dist/modules/graceful_shutdown.d.ts +6 -2
  66. package/dist/modules/graceful_shutdown.js +6 -2
  67. package/dist/modules/launcher/bot_supervisor.js +4 -0
  68. package/dist/modules/launcher/launch_modes.js +6 -3
  69. package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
  70. package/dist/modules/launcher/monolithic_runtime.js +60 -1
  71. package/dist/modules/launcher/runtime_mode.d.ts +79 -0
  72. package/dist/modules/launcher/runtime_mode.js +223 -0
  73. package/dist/modules/market_adapter_whitelist.d.ts +8 -0
  74. package/dist/modules/market_adapter_whitelist.js +8 -0
  75. package/dist/modules/order/accounting.d.ts +15 -1
  76. package/dist/modules/order/accounting.js +15 -1
  77. package/dist/modules/order/async_lock.d.ts +9 -3
  78. package/dist/modules/order/async_lock.js +9 -3
  79. package/dist/modules/order/export.d.ts +0 -5
  80. package/dist/modules/order/export.js +2 -7
  81. package/dist/modules/order/format.d.ts +6 -4
  82. package/dist/modules/order/format.js +6 -4
  83. package/dist/modules/order/grid.d.ts +147 -19
  84. package/dist/modules/order/grid.js +321 -68
  85. package/dist/modules/order/grid_reconcile.js +4 -3
  86. package/dist/modules/order/grid_reconcile_internal.js +13 -18
  87. package/dist/modules/order/index.d.ts +4 -2
  88. package/dist/modules/order/index.js +1 -1
  89. package/dist/modules/order/logger_state.d.ts +1 -1
  90. package/dist/modules/order/logger_state.js +1 -1
  91. package/dist/modules/order/manager.d.ts +1 -0
  92. package/dist/modules/order/manager.js +5 -14
  93. package/dist/modules/order/sync_engine.d.ts +26 -11
  94. package/dist/modules/order/sync_engine.js +44 -20
  95. package/dist/modules/order/utils/math.d.ts +157 -47
  96. package/dist/modules/order/utils/math.js +236 -78
  97. package/dist/modules/order/utils/order.d.ts +64 -20
  98. package/dist/modules/order/utils/order.js +80 -24
  99. package/dist/modules/order/utils/system.d.ts +41 -11
  100. package/dist/modules/order/utils/system.js +43 -13
  101. package/dist/modules/order/utils/validate.d.ts +6 -3
  102. package/dist/modules/order/utils/validate.js +53 -60
  103. package/dist/modules/types.d.ts +7 -0
  104. package/dist/modules/utils/asset_symbols.d.ts +5 -5
  105. package/dist/modules/utils/asset_symbols.js +5 -5
  106. package/dist/modules/utils/errors.d.ts +2 -1
  107. package/dist/modules/utils/errors.js +2 -1
  108. package/dist/scripts/analyze-credit.js +44 -27
  109. package/dist/scripts/diagnose-pool-history.js +35 -30
  110. package/dist/scripts/pnl.js +1 -1
  111. package/dist/scripts/rich_list.d.ts +50 -0
  112. package/dist/scripts/rich_list.js +469 -0
  113. package/dist/scripts/run-tests.js +80 -4
  114. package/dist/unlock.d.ts +2 -1
  115. package/dist/unlock.js +53 -21
  116. package/docs/BITSHARES_ONBOARDING.md +7 -0
  117. package/docs/COW_INVARIANTS.md +7 -1
  118. package/docs/DEXBOT_COMPARISON.md +6 -6
  119. package/docs/EVOLUTION.md +11 -9
  120. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -3
  121. package/docs/GRID_RECALCULATION.md +18 -6
  122. package/docs/LIFECYCLE.md +8 -8
  123. package/docs/LOGGING.md +16 -1
  124. package/docs/MPA_CREDIT_USAGE.md +10 -5
  125. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +163 -13
  126. package/docs/README.md +1 -1
  127. package/docs/WORKFLOW.md +6 -5
  128. package/docs/architecture.md +56 -2
  129. package/docs/developer_guide.md +5 -1
  130. package/market_adapter/README.md +14 -7
  131. package/modules/README.md +1 -1
  132. package/package.json +4 -1
  133. package/scripts/README.md +59 -32
  134. package/tests/README.md +40 -2
@@ -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
  */
@@ -804,49 +842,140 @@ function calculatePriceTolerance(gridPrice, orderSize, orderType, assets = null)
804
842
  return Math.min(tolerance, maxTolerance);
805
843
  }
806
844
  /**
807
- * Scan an iterable of candidate items for a price collision with the target order.
808
- * Each candidate must have `id` and a price accessible via `item.price ?? item.order?.price`.
809
- *
810
- * @param {Iterable} items - Candidates to scan (manager.orders values or opContexts)
811
- * @param {string} excludeId - Slot id to skip (the item being created)
812
- * @param {number} targetPrice
813
- * @param {number} targetSize
814
- * @param {string} targetType - ORDER_TYPES.BUY or SELL
815
- * @param {object} assets - Manager assets (assetA/assetB with precision)
816
- * @param {Function} [isValid] - Optional predicate; candidate must return true to be considered
817
- * @returns {object|null} The colliding item, or null
818
- */
819
- function findPriceCollision(items, excludeId, targetPrice, targetSize, targetType, assets, isValid) {
820
- for (const item of items) {
821
- if (item.id === excludeId)
822
- continue;
823
- if (isValid && !isValid(item))
824
- continue;
825
- const price = item.price ?? item.order?.price;
826
- const size = item.size ?? item.order?.size ?? 0;
827
- if (price == null || targetPrice == null)
845
+ * Whether two prices denote the same order-book price LEVEL, using the
846
+ * chain-representable price tolerance derived from both assets' precisions and
847
+ * the order size(s).
848
+ *
849
+ * WHY NOT priceSlotEqual(priceA, priceB, assetPrecision): a price is not an
850
+ * asset AMOUNT. Rounding it through one asset's precision
851
+ * (floatToBlockchainInt) collapses an entire adjacent grid band whenever the
852
+ * OTHER asset has low precision -- e.g. with a precision-4 quote asset both
853
+ * 0.000318 and 0.000319 round to 3, so every BUY after the first looked like a
854
+ * duplicate. The real on-chain price resolution is roughly
855
+ * 10^-precision / orderSize, which is exactly what calculatePriceTolerance
856
+ * derives. Use this for every production "same price level" check.
857
+ *
858
+ * Both types are evaluated and the tighter tolerance is kept (most
859
+ * conservative): a buy-vs-sell comparison where either side uses a
860
+ * precision-0 asset can otherwise produce a tolerance wider than the grid
861
+ * increment and falsely collide adjacent levels.
862
+ *
863
+ * @param {number} priceA - First price
864
+ * @param {number} sizeA - First order size (same side as typeA)
865
+ * @param {string|null|undefined} typeA - First order type (ORDER_TYPES)
866
+ * @param {number} priceB - Second price
867
+ * @param {number} sizeB - Second order size (same side as typeB)
868
+ * @param {string|null|undefined} typeB - Second order type (ORDER_TYPES)
869
+ * @param {object|null} assets - Manager assets (assetA/assetB with precision)
870
+ * @param {number|null} [incrementPercent] - Grid increment; when supplied the
871
+ * tolerance is clamped to half a grid step so a dust-inflated
872
+ * (MIN_ORDER_SIZE_FACTOR floor) tolerance cannot merge adjacent levels.
873
+ * @returns {boolean} True when the two prices sit on the same level
874
+ */
875
+ function pricesOnSameLevel(priceA, sizeA, typeA, priceB, sizeB, typeB, assets = null, incrementPercent = null) {
876
+ const pa = Number(priceA);
877
+ const pb = Number(priceB);
878
+ if (!Number.isFinite(pa) || !Number.isFinite(pb))
879
+ return pa === pb;
880
+ const size = Math.max(Number(sizeA) || 0, Number(sizeB) || 0);
881
+ const gridPrice = Math.min(pa, pb);
882
+ let tolerance = null;
883
+ for (const type of [typeA, typeB]) {
884
+ if (type == null)
828
885
  continue;
829
- // Compute tolerance for both the target order's type and the
830
- // candidate item's type, then take the minimum (most conservative).
831
- // Without this, a buy-vs-sell comparison where one side uses a
832
- // precision-0 asset can produce tolerance > grid increment from
833
- // the MIN_ORDER_SIZE_FACTOR=50 floor alone, causing adjacent grid
834
- // levels to falsely collide (see validateCreateTargetSlots layer 2
835
- // comment for the full analysis).
836
- const toleranceTarget = calculatePriceTolerance(Math.min(price, targetPrice), Math.max(size, targetSize), targetType, assets);
837
- let tolerance = toleranceTarget;
838
- const itemType = item.type ?? item.order?.type;
839
- if (toleranceTarget != null && itemType != null) {
840
- const toleranceItem = calculatePriceTolerance(Math.min(price, targetPrice), Math.max(size, targetSize), itemType, assets);
841
- if (toleranceItem != null) {
842
- tolerance = Math.min(toleranceTarget, toleranceItem);
843
- }
886
+ let t = null;
887
+ try {
888
+ t = calculatePriceTolerance(gridPrice, size, type, assets);
889
+ }
890
+ catch {
891
+ t = null;
844
892
  }
845
- if (tolerance != null && Math.abs(price - targetPrice) <= tolerance) {
846
- return item;
893
+ if (t != null && Number.isFinite(t)) {
894
+ tolerance = tolerance == null ? t : Math.min(tolerance, t);
847
895
  }
848
896
  }
849
- return null;
897
+ if (tolerance == null)
898
+ return pa === pb;
899
+ // Hard cap: never let the tolerance span more than half a grid step. The
900
+ // precision/floor maths above can otherwise exceed the increment for
901
+ // dust-sized or low-precision orders, merging two legitimately adjacent
902
+ // levels (the caller passes the increment when it has one).
903
+ const inc = Number(incrementPercent);
904
+ if (Number.isFinite(inc) && inc > 0) {
905
+ tolerance = Math.min(tolerance, Math.abs(gridPrice) * (inc / 100) * 0.5);
906
+ }
907
+ return Math.abs(pa - pb) <= tolerance;
908
+ }
909
+ /**
910
+ * Relative slack for grid price identity. Large enough to absorb float noise
911
+ * (re-serialization, a stored value recomputed through a different but
912
+ * algebraically equivalent path) yet far below any real grid increment, so it
913
+ * cannot merge two genuinely distinct ladder levels.
914
+ */
915
+ const GRID_PRICE_REL_EPSILON = 1e-9;
916
+ /**
917
+ * Whether two GENESIS-derived grid prices denote the same ladder level by
918
+ * EXACT identity (with float-noise slack).
919
+ *
920
+ * Grid slot prices are frozen ladder values (bit-identical per level), so
921
+ * exact equality is the correct identity for a grid-vs-grid comparison.
922
+ * Deliberately NOT priceSlotEqual at the asset precision (collapses an
923
+ * adjacent band for a low-precision asset) and NOT the chain tolerance (which
924
+ * can exceed the grid increment and merge two legitimately adjacent levels).
925
+ * Prefer sameGridLevel(genesis) where a ladder is available: it maps a drifted
926
+ * price back to its nearest ladder level. Use pricesOnSameLevel instead when
927
+ * one side is a chain-derived price that may sit a few chain quanta off its
928
+ * level.
929
+ *
930
+ * @param {number} priceA - First grid price
931
+ * @param {number} priceB - Second grid price
932
+ * @returns {boolean} True when both are the same ladder level
933
+ */
934
+ function sameGridPrice(priceA, priceB) {
935
+ const a = Number(priceA);
936
+ const b = Number(priceB);
937
+ if (!Number.isFinite(a) || !Number.isFinite(b))
938
+ return a === b;
939
+ if (a === b)
940
+ return true;
941
+ return Math.abs(a - b) <= GRID_PRICE_REL_EPSILON * Math.max(1, Math.abs(a), Math.abs(b));
942
+ }
943
+ /**
944
+ * Whether two grid prices denote the same ladder level, resolving each price
945
+ * to its nearest level through the frozen genesis ladder when one is supplied.
946
+ * This is robust to a price that was chain-corrected / rounded a quantum off
947
+ * its level: slotIndexForPrice maps it back to the level it came from, while a
948
+ * price that genuinely moved to another level resolves to a different index.
949
+ *
950
+ * PRECONDITION / HARDENING: slotIndexForPrice CLAMPS an out-of-rail price onto
951
+ * the edge levels, so two distinct out-of-rail prices would otherwise resolve
952
+ * "equal". This helper therefore only uses slot identity when BOTH prices sit
953
+ * inside [levels[0], levels[N-1]]; otherwise it falls back to exact-level
954
+ * identity (sameGridPrice, with float-noise slack). Callers pass in-rail grid
955
+ * prices today, but the guard makes out-of-rail misuse safe.
956
+ *
957
+ * @param {number} priceA - First grid price
958
+ * @param {number} priceB - Second grid price
959
+ * @param {unknown} genesis - Frozen genesis ladder (`manager._genesis`)
960
+ * @returns {boolean} True when both prices resolve to the same ladder level
961
+ */
962
+ function sameGridLevel(priceA, priceB, genesis) {
963
+ const a = Number(priceA);
964
+ const b = Number(priceB);
965
+ const levels = genesis?.priceLevels;
966
+ if (Array.isArray(levels) && levels.length > 0) {
967
+ const lo = Number(levels[0]);
968
+ const hi = Number(levels[levels.length - 1]);
969
+ const inRail = (p) => Number.isFinite(p) && p >= lo && p <= hi;
970
+ if (!inRail(a) || !inRail(b))
971
+ return sameGridPrice(a, b);
972
+ try {
973
+ const g = genesis;
974
+ return slotIndexForPrice(a, g) === slotIndexForPrice(b, g);
975
+ }
976
+ catch { /* unjudgeable ladder — fall through to exact-level identity */ }
977
+ }
978
+ return sameGridPrice(a, b);
850
979
  }
851
980
  /**
852
981
  * Find an opposite-side order that a candidate placement would CROSS.
@@ -861,10 +990,9 @@ function findPriceCollision(items, excludeId, targetPrice, targetSize, targetTyp
861
990
  * sell ladder was re-priced into marketable buys, triggering a fatal
862
991
  * fund assertion).
863
992
  *
864
- * Unlike findPriceCollision (same-price check), this catches crossings at
865
- * ANY price overlap and is intended for the re-pricing UPDATE / CREATE
866
- * paths. The caller decides the exemption policy (e.g. crossed orders
867
- * cancelled earlier in the same plan).
993
+ * Unlike a same-price check, this catches crossings at ANY price overlap and
994
+ * is intended for the re-pricing UPDATE / CREATE paths. The caller decides the
995
+ * exemption policy (e.g. crossed orders cancelled earlier in the same plan).
868
996
  *
869
997
  * @param {Iterable<any>} items - Candidate orders (e.g. manager.orders.values())
870
998
  * @param {number} price - Candidate placement price
@@ -1288,7 +1416,7 @@ function calculateSwapInAmount(targetReceive, poolReserveOut, poolReserveIn) {
1288
1416
  *
1289
1417
  * @param {number} incrementPercent - Grid increment percentage
1290
1418
  * @param {number} targetSpreadPercent - Target spread percentage
1291
- * @param {Object} GRID_LIMITS - Grid limits constants (optional, uses defaults)
1419
+ * @param {Object} [gridLimits] - Grid limits constants (optional, uses defaults)
1292
1420
  * @returns {number} Number of gap slots
1293
1421
  */
1294
1422
  function calculateGapSlots(incrementPercent, targetSpreadPercent, gridLimits = {}) {
@@ -1305,9 +1433,22 @@ function calculateGapSlots(incrementPercent, targetSpreadPercent, gridLimits = {
1305
1433
  /**
1306
1434
  * Calculate sell start index from boundary index and gap slots.
1307
1435
  * sellStartIdx = boundaryIdx + gapSlots + 1
1436
+ *
1437
+ * Absent-aware: Number(null) === 0 and Number('') === 0 would read "no
1438
+ * boundary" as boundary 0 and manufacture a SELL-rail start at gapSlots+1.
1439
+ * Unknown geometry (null/undefined/'') returns NaN so any unguarded caller
1440
+ * fails closed via Number.isFinite instead of silently rail-biasing slot 0.
1441
+ * Every current caller guards first (resolveGapBand, isSlotInRail,
1442
+ * isSlotIndexInGapBand, geometryTypeForSlotIndex, the COW stamp paths);
1443
+ * this carries the same contract in the helper itself so a future caller
1444
+ * cannot bypass it. A genuine 0 boundary still yields gapSlots + 1.
1308
1445
  */
1309
1446
  function getSellStartIdx(boundaryIdx, gapSlots) {
1310
- return Number(boundaryIdx ?? 0) + Number(gapSlots) + 1;
1447
+ const b = Format.toKnownNumber(boundaryIdx);
1448
+ const g = Format.toKnownNumber(gapSlots);
1449
+ if (!Number.isFinite(b) || !Number.isFinite(g))
1450
+ return NaN;
1451
+ return b + g + 1;
1311
1452
  }
1312
1453
  /**
1313
1454
  * Resolve the configured gap-slot count for a manager-like object.
@@ -1316,9 +1457,13 @@ function getSellStartIdx(boundaryIdx, gapSlots) {
1316
1457
  * two can never disagree on band width.
1317
1458
  */
1318
1459
  function resolveGapSlots(manager) {
1319
- const configured = manager._gapSlots;
1320
- if (configured != null && Number.isFinite(Number(configured))) {
1321
- return Math.max(0, Math.floor(Number(configured)));
1460
+ // Absent-aware: Number('') === 0 is finite, so a '' _gapSlots would pass
1461
+ // the finite test as a valid 0 and collapse the band. '' is unknown →
1462
+ // fall back to the config-derived gap (same contract as
1463
+ // consumePendingFillCrawls' dc87ce01 fallback).
1464
+ const raw = Format.toKnownNumber(manager._gapSlots);
1465
+ if (Number.isFinite(raw)) {
1466
+ return Math.max(0, Math.floor(raw));
1322
1467
  }
1323
1468
  return calculateGapSlots(manager.config?.incrementPercent, manager.config?.targetSpreadPercent, manager.config?.gridLimits);
1324
1469
  }
@@ -1534,7 +1679,7 @@ function validatePersistedBoundary(proposedBoundary, orders, gapSlots) {
1534
1679
  * over 2-3 cycles, so a snapshot taken mid-evacuation (or stale by one
1535
1680
  * crawl, as in recovery-before-CREATE) legitimately reports this. Nuking
1536
1681
  * the snapshot for it discards the boundary progression, pending crawls,
1537
- * streaks and the queued evacuation — the exact sabotage loop seen in H-BTS
1682
+ * streaks and the queued evacuation — the exact sabotage loop seen in <bot>
1538
1683
  * 2026-09-13 (GAP-EVAC flags slot-96, COW plans 96→116, stale snapshot with
1539
1684
  * slot-94 still stranded fails validation, structural resync wipes the
1540
1685
  * plan). All other reasons (ceiling/range/crossed-book/...) are structural
@@ -1591,7 +1736,7 @@ function countGapBandSpread(manager, orders, resolveIndex) {
1591
1736
  * (grid_reconcile_internal.ts), and the COW divergence correction (system.ts).
1592
1737
  * Drift between those copies is what let a fund-driven boundary shift leave a
1593
1738
  * SPREAD GUARD-typed stray inside the gap as "closest to market" — collapsing
1594
- * the spread (h-bts: boundary 107→110 left the sell rail parked at 111-130
1739
+ * the spread (<bot>: boundary 107→110 left the sell rail parked at 111-130
1595
1740
  * with the bottom three, 111-113, inside the new spread gap; real spread 0.5%
1596
1741
  * vs the 2.0% target).
1597
1742
  *
@@ -1821,11 +1966,18 @@ function slotIdForPrice(price, genesis) {
1821
1966
  * slotIndexForPrice clamps out-of-range prices onto the edge slots (0/N-1),
1822
1967
  * so callers MUST check this before adopting or duplicate-matching: a
1823
1968
  * below-grid buy is not slot-0 and an above-grid sell is not slot-(N-1).
1824
- * Integer equality (priceSlotEqual) excuses sub-satoshi float dust at the
1825
- * edge; anything further out is out-of-grid → hold/defer, never adopt or
1826
- * cancel as a duplicate.
1827
- */
1828
- function isChainPriceOutOfGrid(price, genesis, precision) {
1969
+ * Only genuine float dust at the edge is excused; anything further out is
1970
+ * out-of-grid -> hold/defer, never adopt or cancel as a duplicate.
1971
+ *
1972
+ * The edge excuse is the chain-representable tolerance (pricesOnSameLevel),
1973
+ * clamped to half a ladder step. Deliberately NOT priceSlotEqual at the asset
1974
+ * precision: a price is not an amount, so a precision-4 asset rounds a whole
1975
+ * adjacent band below the rail onto the edge and wrongly classifies a
1976
+ * dip-protection level as in-grid (fail-open). When assets/type are missing,
1977
+ * only float noise at the edge is excused (exact-level identity), so an
1978
+ * unjudgeable outside price stays out-of-grid (fail-closed).
1979
+ */
1980
+ function isChainPriceOutOfGrid(price, genesis, size = 0, type = null, assets = null) {
1829
1981
  const levels = genesis?.priceLevels;
1830
1982
  if (!Array.isArray(levels) || levels.length === 0)
1831
1983
  return false;
@@ -1833,9 +1985,15 @@ function isChainPriceOutOfGrid(price, genesis, precision) {
1833
1985
  return false;
1834
1986
  const min = levels[0];
1835
1987
  const max = levels[levels.length - 1];
1836
- if (price < min && !priceSlotEqual(price, min, precision))
1988
+ const incrementPercent = levels.length > 1 && Number(levels[0]) > 0
1989
+ ? ((Number(levels[1]) - Number(levels[0])) / Number(levels[0])) * 100
1990
+ : null;
1991
+ const onEdge = (edge) => (assets != null && type != null)
1992
+ ? pricesOnSameLevel(price, size, type, edge, size, type, assets, incrementPercent)
1993
+ : sameGridPrice(price, edge);
1994
+ if (price < min && !onEdge(min))
1837
1995
  return true;
1838
- if (price > max && !priceSlotEqual(price, max, precision))
1996
+ if (price > max && !onEdge(max))
1839
1997
  return true;
1840
1998
  return false;
1841
1999
  }
@@ -1944,7 +2102,7 @@ function buildGenesisFromPriceLevels(startPrice, incrementPercent, gapSlots, pri
1944
2102
  createdAt: Date.now()
1945
2103
  };
1946
2104
  }
1947
- 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, findPriceCollision, findCrossedOrder, 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, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
2105
+ 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 };
1948
2106
  /**
1949
2107
  * Round a value to a given factor.
1950
2108
  * @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: {