dexbot 1.6.14 → 1.6.15

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 (70) hide show
  1. package/CHANGELOG.md +34 -4
  2. package/analysis/README.md +6 -6
  3. package/analysis/tradingview/README.md +2 -1
  4. package/claw/README.md +7 -7
  5. package/claw/package.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  8. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +80 -6
  9. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +36 -2
  10. package/dist/dexbot.js +23 -3
  11. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
  12. package/dist/modules/account_bots.d.ts +3 -0
  13. package/dist/modules/account_bots.js +3 -0
  14. package/dist/modules/bitshares-native/subscriptions.js +1 -1
  15. package/dist/modules/bot_defaults.d.ts +13 -2
  16. package/dist/modules/bot_defaults.js +31 -2
  17. package/dist/modules/bot_settings.js +3 -0
  18. package/dist/modules/constants.d.ts +6 -0
  19. package/dist/modules/constants.js +24 -0
  20. package/dist/modules/credit_runtime.d.ts +35 -5
  21. package/dist/modules/credit_runtime.js +219 -38
  22. package/dist/modules/dexbot_class.d.ts +19 -1
  23. package/dist/modules/dexbot_class.js +58 -20
  24. package/dist/modules/dexbot_cow_runtime.js +19 -18
  25. package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
  26. package/dist/modules/dexbot_fill_runtime.js +4 -7
  27. package/dist/modules/dexbot_maintenance_runtime.d.ts +7 -2
  28. package/dist/modules/dexbot_maintenance_runtime.js +52 -7
  29. package/dist/modules/dexbot_startup_runtime.js +3 -2
  30. package/dist/modules/dexbot_state_recovery.js +1 -1
  31. package/dist/modules/order/export.js +2 -2
  32. package/dist/modules/order/grid.d.ts +118 -1
  33. package/dist/modules/order/grid.js +292 -50
  34. package/dist/modules/order/grid_reconcile.js +4 -3
  35. package/dist/modules/order/grid_reconcile_internal.js +13 -18
  36. package/dist/modules/order/index.d.ts +3 -1
  37. package/dist/modules/order/manager.d.ts +1 -0
  38. package/dist/modules/order/manager.js +5 -14
  39. package/dist/modules/order/sync_engine.js +18 -9
  40. package/dist/modules/order/utils/math.d.ts +98 -26
  41. package/dist/modules/order/utils/math.js +177 -57
  42. package/dist/modules/order/utils/order.js +16 -4
  43. package/dist/modules/order/utils/system.js +2 -2
  44. package/dist/modules/order/utils/validate.d.ts +1 -1
  45. package/dist/modules/order/utils/validate.js +48 -58
  46. package/dist/modules/types.d.ts +7 -0
  47. package/dist/scripts/analyze-credit.js +44 -27
  48. package/dist/scripts/diagnose-pool-history.js +35 -30
  49. package/dist/scripts/pnl.js +1 -1
  50. package/dist/scripts/rich_list.d.ts +18 -0
  51. package/dist/scripts/rich_list.js +461 -0
  52. package/dist/scripts/run-tests.js +80 -4
  53. package/dist/unlock.d.ts +2 -1
  54. package/dist/unlock.js +4 -3
  55. package/docs/COW_INVARIANTS.md +6 -0
  56. package/docs/DEXBOT_COMPARISON.md +6 -6
  57. package/docs/EVOLUTION.md +10 -9
  58. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  59. package/docs/LOGGING.md +16 -1
  60. package/docs/MPA_CREDIT_USAGE.md +10 -5
  61. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +159 -9
  62. package/docs/README.md +1 -1
  63. package/docs/WORKFLOW.md +1 -0
  64. package/docs/architecture.md +56 -2
  65. package/docs/developer_guide.md +5 -1
  66. package/market_adapter/README.md +4 -4
  67. package/modules/README.md +1 -1
  68. package/package.json +2 -1
  69. package/scripts/README.md +59 -32
  70. package/tests/README.md +11 -2
@@ -123,7 +123,7 @@ function batchReadOrdersSeam(mgr, orderIds, timeoutMs) {
123
123
  const { BitShares } = client;
124
124
  import { NATIVE_CLIENT } from '../constants.js';
125
125
  const { toFiniteNumber } = Format;
126
- import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, priceForSlot, priceSlotEqual } from './utils/math.js';
126
+ import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, priceForSlot, priceSlotEqual, pricesOnSameLevel } from './utils/math.js';
127
127
  import { parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance, _filterUnmatchedChainOrders } from './utils/order.js';
128
128
  import { parseSlotIndex } from './utils/slot.js';
129
129
  import { resolveProcessedFillPersistenceMode } from './processed_fill_store.js';
@@ -228,7 +228,7 @@ function describeNearestAdoptionCandidates(mgr, chainOrder, precision, matchedGr
228
228
  const priceDiff = Math.abs(price - chainPrice);
229
229
  let priceEqual = false;
230
230
  try {
231
- priceEqual = chainPriceOnSameLevel(chainPrice, price, mgr?._genesis, precision);
231
+ priceEqual = chainPriceOnSameLevel(chainPrice, price, mgr?._genesis, precision, mgr?.assets, chainSize, toFiniteNumber(slot.size), chainOrder.type, mgr?.config?.incrementPercent);
232
232
  }
233
233
  catch {
234
234
  priceEqual = chainPrice === price;
@@ -293,13 +293,20 @@ function describeNearestAdoptionCandidates(mgr, chainOrder, precision, matchedGr
293
293
  * correction / duplicate / re-slot warranted. Unjudgeable inputs (no ladder,
294
294
  * non-finite price) fall back to integer equality at the asset precision.
295
295
  */
296
- function chainPriceOnSameLevel(chainPrice, slotPrice, genesis, precision) {
296
+ function chainPriceOnSameLevel(chainPrice, slotPrice, genesis, precision, assets = null, chainSize = 0, slotSize = 0, type = null, incrementPercent = null) {
297
297
  if (hasGenesisLadder(genesis)) {
298
298
  try {
299
299
  const g = genesis;
300
300
  return slotIndexForPrice(chainPrice, g) === slotIndexForPrice(slotPrice, g);
301
301
  }
302
- catch { /* unjudgeable — fall through to integer equality */ }
302
+ catch { /* unjudgeable — fall through to price-level comparison */ }
303
+ }
304
+ // No ladder (legacy/migration window): compare the chain price to the slot
305
+ // price with the chain-representable tolerance, capped to half a grid step.
306
+ // NOT priceSlotEqual at the asset amount precision, which collapses
307
+ // adjacent levels for a low-precision asset.
308
+ if (assets != null) {
309
+ return pricesOnSameLevel(chainPrice, chainSize, type, slotPrice, slotSize, type, assets, incrementPercent);
303
310
  }
304
311
  try {
305
312
  return priceSlotEqual(chainPrice, slotPrice, precision);
@@ -975,7 +982,7 @@ class SyncEngine {
975
982
  // drift of a few quanta inside one level is normal and must
976
983
  // not queue a price correction.
977
984
  const precision = gridOrder.type === ORDER_TYPES.SELL ? assetAPrecision : assetBPrecision;
978
- const isPriceEqual = chainPriceOnSameLevel(chainOrder.price, gridOrder.price, mgr._genesis, precision);
985
+ const isPriceEqual = chainPriceOnSameLevel(chainOrder.price, gridOrder.price, mgr._genesis, precision, mgr.assets, toFiniteNumber(chainOrder.size), gridOrder.size, gridOrder.type, mgr.config?.incrementPercent);
979
986
  if (!isPriceEqual) {
980
987
  queueCorrection({
981
988
  gridOrder: { ...gridOrder },
@@ -1017,7 +1024,7 @@ class SyncEngine {
1017
1024
  // ladder level as the slot (the swap tiebreak's whole
1018
1025
  // premise — a duplicate at this level).
1019
1026
  const precision = gridOrder.type === ORDER_TYPES.SELL ? assetAPrecision : assetBPrecision;
1020
- if (!chainPriceOnSameLevel(candidateOrder.price, gridOrder.price, mgr._genesis, precision))
1027
+ if (!chainPriceOnSameLevel(candidateOrder.price, gridOrder.price, mgr._genesis, precision, mgr.assets, toFiniteNumber(candidateOrder.size), gridOrder.size, gridOrder.type, mgr.config?.incrementPercent))
1021
1028
  continue;
1022
1029
  if (floatToBlockchainInt(candidateOrder.size, precision) !== currentSizeInt)
1023
1030
  continue;
@@ -1231,8 +1238,7 @@ class SyncEngine {
1231
1238
  // (no adopt, no cancelOnly), e.g. dip-protection levels
1232
1239
  // sitting below a fresh grid after a reset.
1233
1240
  {
1234
- const precision = (chainOrder.type === ORDER_TYPES.SELL) ? assetAPrecision : assetBPrecision;
1235
- if (isChainPriceOutOfGrid(chainOrder.price, genesisLadder, precision)) {
1241
+ if (isChainPriceOutOfGrid(chainOrder.price, genesisLadder, toFiniteNumber(chainOrder.size), chainOrder.type, mgr.assets)) {
1236
1242
  unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'out-of-grid-deferred', candidateSlotId: slotId });
1237
1243
  mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: price outside grid range, deferred (nearest slot ${slotId})`, 'warn');
1238
1244
  continue;
@@ -1248,7 +1254,10 @@ class SyncEngine {
1248
1254
  // legitimate in-rail orphan waits one sync cycle
1249
1255
  // post-boundary-commit before adoption. Strictly better than
1250
1256
  // adopting a gap stray into the wrong slot.
1251
- if (boundaryIdx == null || !Number.isFinite(Number(boundaryIdx))) {
1257
+ // '' guard: Number('') === 0 is finite, so an empty-string
1258
+ // boundary would read as boundary 0 (same trap guarded in
1259
+ // runPreBroadcastGuards / resolveGapBand).
1260
+ if (boundaryIdx == null || boundaryIdx === '' || !Number.isFinite(Number(boundaryIdx))) {
1252
1261
  unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'boundary-unknown-deferred', candidateSlotId: slotId });
1253
1262
  mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: boundary unknown, deferred until boundary commits (nearest slot ${slotId})`, 'warn');
1254
1263
  continue;
@@ -589,19 +589,76 @@ declare function getBtsSide(assetA: string | undefined, assetB: string | undefin
589
589
  */
590
590
  declare function calculatePriceTolerance(gridPrice: unknown, orderSize: unknown, orderType: string, assets?: AssetPair | null): number | null;
591
591
  /**
592
- * Scan an iterable of candidate items for a price collision with the target order.
593
- * Each candidate must have `id` and a price accessible via `item.price ?? item.order?.price`.
594
- *
595
- * @param {Iterable} items - Candidates to scan (manager.orders values or opContexts)
596
- * @param {string} excludeId - Slot id to skip (the item being created)
597
- * @param {number} targetPrice
598
- * @param {number} targetSize
599
- * @param {string} targetType - ORDER_TYPES.BUY or SELL
600
- * @param {object} assets - Manager assets (assetA/assetB with precision)
601
- * @param {Function} [isValid] - Optional predicate; candidate must return true to be considered
602
- * @returns {object|null} The colliding item, or null
603
- */
604
- declare function findPriceCollision(items: Iterable<CollisionItem>, excludeId: string, targetPrice: number, targetSize: number, targetType: string, assets: AssetPair | null, isValid?: ((item: CollisionItem) => boolean) | null): CollisionItem | null;
592
+ * Whether two prices denote the same order-book price LEVEL, using the
593
+ * chain-representable price tolerance derived from both assets' precisions and
594
+ * the order size(s).
595
+ *
596
+ * WHY NOT priceSlotEqual(priceA, priceB, assetPrecision): a price is not an
597
+ * asset AMOUNT. Rounding it through one asset's precision
598
+ * (floatToBlockchainInt) collapses an entire adjacent grid band whenever the
599
+ * OTHER asset has low precision -- e.g. with a precision-4 quote asset both
600
+ * 0.000318 and 0.000319 round to 3, so every BUY after the first looked like a
601
+ * duplicate. The real on-chain price resolution is roughly
602
+ * 10^-precision / orderSize, which is exactly what calculatePriceTolerance
603
+ * derives. Use this for every production "same price level" check.
604
+ *
605
+ * Both types are evaluated and the tighter tolerance is kept (most
606
+ * conservative): a buy-vs-sell comparison where either side uses a
607
+ * precision-0 asset can otherwise produce a tolerance wider than the grid
608
+ * increment and falsely collide adjacent levels.
609
+ *
610
+ * @param {number} priceA - First price
611
+ * @param {number} sizeA - First order size (same side as typeA)
612
+ * @param {string|null|undefined} typeA - First order type (ORDER_TYPES)
613
+ * @param {number} priceB - Second price
614
+ * @param {number} sizeB - Second order size (same side as typeB)
615
+ * @param {string|null|undefined} typeB - Second order type (ORDER_TYPES)
616
+ * @param {object|null} assets - Manager assets (assetA/assetB with precision)
617
+ * @param {number|null} [incrementPercent] - Grid increment; when supplied the
618
+ * tolerance is clamped to half a grid step so a dust-inflated
619
+ * (MIN_ORDER_SIZE_FACTOR floor) tolerance cannot merge adjacent levels.
620
+ * @returns {boolean} True when the two prices sit on the same level
621
+ */
622
+ declare function pricesOnSameLevel(priceA: number, sizeA: number, typeA: string | null | undefined, priceB: number, sizeB: number, typeB: string | null | undefined, assets?: AssetPair | null, incrementPercent?: number | null | undefined): boolean;
623
+ /**
624
+ * Whether two GENESIS-derived grid prices denote the same ladder level by
625
+ * EXACT identity (with float-noise slack).
626
+ *
627
+ * Grid slot prices are frozen ladder values (bit-identical per level), so
628
+ * exact equality is the correct identity for a grid-vs-grid comparison.
629
+ * Deliberately NOT priceSlotEqual at the asset precision (collapses an
630
+ * adjacent band for a low-precision asset) and NOT the chain tolerance (which
631
+ * can exceed the grid increment and merge two legitimately adjacent levels).
632
+ * Prefer sameGridLevel(genesis) where a ladder is available: it maps a drifted
633
+ * price back to its nearest ladder level. Use pricesOnSameLevel instead when
634
+ * one side is a chain-derived price that may sit a few chain quanta off its
635
+ * level.
636
+ *
637
+ * @param {number} priceA - First grid price
638
+ * @param {number} priceB - Second grid price
639
+ * @returns {boolean} True when both are the same ladder level
640
+ */
641
+ declare function sameGridPrice(priceA: number, priceB: number): boolean;
642
+ /**
643
+ * Whether two grid prices denote the same ladder level, resolving each price
644
+ * to its nearest level through the frozen genesis ladder when one is supplied.
645
+ * This is robust to a price that was chain-corrected / rounded a quantum off
646
+ * its level: slotIndexForPrice maps it back to the level it came from, while a
647
+ * price that genuinely moved to another level resolves to a different index.
648
+ *
649
+ * PRECONDITION / HARDENING: slotIndexForPrice CLAMPS an out-of-rail price onto
650
+ * the edge levels, so two distinct out-of-rail prices would otherwise resolve
651
+ * "equal". This helper therefore only uses slot identity when BOTH prices sit
652
+ * inside [levels[0], levels[N-1]]; otherwise it falls back to exact-level
653
+ * identity (sameGridPrice, with float-noise slack). Callers pass in-rail grid
654
+ * prices today, but the guard makes out-of-rail misuse safe.
655
+ *
656
+ * @param {number} priceA - First grid price
657
+ * @param {number} priceB - Second grid price
658
+ * @param {unknown} genesis - Frozen genesis ladder (`manager._genesis`)
659
+ * @returns {boolean} True when both prices resolve to the same ladder level
660
+ */
661
+ declare function sameGridLevel(priceA: number, priceB: number, genesis: unknown): boolean;
605
662
  /**
606
663
  * Find an opposite-side order that a candidate placement would CROSS.
607
664
  *
@@ -615,10 +672,9 @@ declare function findPriceCollision(items: Iterable<CollisionItem>, excludeId: s
615
672
  * sell ladder was re-priced into marketable buys, triggering a fatal
616
673
  * fund assertion).
617
674
  *
618
- * Unlike findPriceCollision (same-price check), this catches crossings at
619
- * ANY price overlap and is intended for the re-pricing UPDATE / CREATE
620
- * paths. The caller decides the exemption policy (e.g. crossed orders
621
- * cancelled earlier in the same plan).
675
+ * Unlike a same-price check, this catches crossings at ANY price overlap and
676
+ * is intended for the re-pricing UPDATE / CREATE paths. The caller decides the
677
+ * exemption policy (e.g. crossed orders cancelled earlier in the same plan).
622
678
  *
623
679
  * @param {Iterable<any>} items - Candidate orders (e.g. manager.orders.values())
624
680
  * @param {number} price - Candidate placement price
@@ -796,8 +852,17 @@ declare function calculateGapSlots(incrementPercent: number | undefined, targetS
796
852
  /**
797
853
  * Calculate sell start index from boundary index and gap slots.
798
854
  * sellStartIdx = boundaryIdx + gapSlots + 1
855
+ *
856
+ * Absent-aware: Number(null) === 0 and Number('') === 0 would read "no
857
+ * boundary" as boundary 0 and manufacture a SELL-rail start at gapSlots+1.
858
+ * Unknown geometry (null/undefined/'') returns NaN so any unguarded caller
859
+ * fails closed via Number.isFinite instead of silently rail-biasing slot 0.
860
+ * Every current caller guards first (resolveGapBand, isSlotInRail,
861
+ * isSlotIndexInGapBand, geometryTypeForSlotIndex, the COW stamp paths);
862
+ * this carries the same contract in the helper itself so a future caller
863
+ * cannot bypass it. A genuine 0 boundary still yields gapSlots + 1.
799
864
  */
800
- declare function getSellStartIdx(boundaryIdx: number | null, gapSlots: number | null): number;
865
+ declare function getSellStartIdx(boundaryIdx: number | string | null | undefined, gapSlots: number | string | null | undefined): number;
801
866
  /**
802
867
  * Resolve the configured gap-slot count for a manager-like object.
803
868
  * Single source of truth for the `_gapSlots ?? calculateGapSlots(config)`
@@ -930,7 +995,7 @@ declare function validatePersistedBoundary(proposedBoundary: number | null | und
930
995
  * over 2-3 cycles, so a snapshot taken mid-evacuation (or stale by one
931
996
  * crawl, as in recovery-before-CREATE) legitimately reports this. Nuking
932
997
  * the snapshot for it discards the boundary progression, pending crawls,
933
- * streaks and the queued evacuation — the exact sabotage loop seen in H-BTS
998
+ * streaks and the queued evacuation — the exact sabotage loop seen in <bot>
934
999
  * 2026-09-13 (GAP-EVAC flags slot-96, COW plans 96→116, stale snapshot with
935
1000
  * slot-94 still stranded fails validation, structural resync wipes the
936
1001
  * plan). All other reasons (ceiling/range/crossed-book/...) are structural
@@ -974,7 +1039,7 @@ declare function countGapBandSpread(manager: OrderManagerLike, orders: Iterable<
974
1039
  * (grid_reconcile_internal.ts), and the COW divergence correction (system.ts).
975
1040
  * Drift between those copies is what let a fund-driven boundary shift leave a
976
1041
  * SPREAD GUARD-typed stray inside the gap as "closest to market" — collapsing
977
- * the spread (h-bts: boundary 107→110 left the sell rail parked at 111-130
1042
+ * the spread (<bot>: boundary 107→110 left the sell rail parked at 111-130
978
1043
  * with the bottom three, 111-113, inside the new spread gap; real spread 0.5%
979
1044
  * vs the 2.0% target).
980
1045
  *
@@ -1076,11 +1141,18 @@ declare function slotIdForPrice(price: number, genesis: GridGenesis): string;
1076
1141
  * slotIndexForPrice clamps out-of-range prices onto the edge slots (0/N-1),
1077
1142
  * so callers MUST check this before adopting or duplicate-matching: a
1078
1143
  * below-grid buy is not slot-0 and an above-grid sell is not slot-(N-1).
1079
- * Integer equality (priceSlotEqual) excuses sub-satoshi float dust at the
1080
- * edge; anything further out is out-of-grid → hold/defer, never adopt or
1081
- * cancel as a duplicate.
1082
- */
1083
- declare function isChainPriceOutOfGrid(price: number, genesis: GridGenesis, precision: number): boolean;
1144
+ * Only genuine float dust at the edge is excused; anything further out is
1145
+ * out-of-grid -> hold/defer, never adopt or cancel as a duplicate.
1146
+ *
1147
+ * The edge excuse is the chain-representable tolerance (pricesOnSameLevel),
1148
+ * clamped to half a ladder step. Deliberately NOT priceSlotEqual at the asset
1149
+ * precision: a price is not an amount, so a precision-4 asset rounds a whole
1150
+ * adjacent band below the rail onto the edge and wrongly classifies a
1151
+ * dip-protection level as in-grid (fail-open). When assets/type are missing,
1152
+ * only float noise at the edge is excused (exact-level identity), so an
1153
+ * unjudgeable outside price stays out-of-grid (fail-closed).
1154
+ */
1155
+ declare function isChainPriceOutOfGrid(price: number, genesis: GridGenesis, size?: number, type?: string | null, assets?: AssetPair | null): boolean;
1084
1156
  declare function assertSlotPriceInvariant(slot: unknown, genesis: GridGenesis): void;
1085
1157
  declare function priceSlotEqual(a: number, b: number, precision: number): boolean;
1086
1158
  /**
@@ -1106,7 +1178,7 @@ declare function priceSlotEqual(a: number, b: number, precision: number): boolea
1106
1178
  declare function derivePriceLevels(startPrice: number, minPrice: number, maxPrice: number, incrementPercent: number): number[];
1107
1179
  declare function buildGenesisFromPriceLevels(startPrice: number, incrementPercent: number, gapSlots: number, priceLevels: number[]): GridGenesis;
1108
1180
  export type { FeeCacheEntry };
1109
- 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 };
1181
+ 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 };
1110
1182
  /**
1111
1183
  * Round a value to a given factor.
1112
1184
  * @param {number} value - Value to round
@@ -804,49 +804,140 @@ function calculatePriceTolerance(gridPrice, orderSize, orderType, assets = null)
804
804
  return Math.min(tolerance, maxTolerance);
805
805
  }
806
806
  /**
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))
807
+ * Whether two prices denote the same order-book price LEVEL, using the
808
+ * chain-representable price tolerance derived from both assets' precisions and
809
+ * the order size(s).
810
+ *
811
+ * WHY NOT priceSlotEqual(priceA, priceB, assetPrecision): a price is not an
812
+ * asset AMOUNT. Rounding it through one asset's precision
813
+ * (floatToBlockchainInt) collapses an entire adjacent grid band whenever the
814
+ * OTHER asset has low precision -- e.g. with a precision-4 quote asset both
815
+ * 0.000318 and 0.000319 round to 3, so every BUY after the first looked like a
816
+ * duplicate. The real on-chain price resolution is roughly
817
+ * 10^-precision / orderSize, which is exactly what calculatePriceTolerance
818
+ * derives. Use this for every production "same price level" check.
819
+ *
820
+ * Both types are evaluated and the tighter tolerance is kept (most
821
+ * conservative): a buy-vs-sell comparison where either side uses a
822
+ * precision-0 asset can otherwise produce a tolerance wider than the grid
823
+ * increment and falsely collide adjacent levels.
824
+ *
825
+ * @param {number} priceA - First price
826
+ * @param {number} sizeA - First order size (same side as typeA)
827
+ * @param {string|null|undefined} typeA - First order type (ORDER_TYPES)
828
+ * @param {number} priceB - Second price
829
+ * @param {number} sizeB - Second order size (same side as typeB)
830
+ * @param {string|null|undefined} typeB - Second order type (ORDER_TYPES)
831
+ * @param {object|null} assets - Manager assets (assetA/assetB with precision)
832
+ * @param {number|null} [incrementPercent] - Grid increment; when supplied the
833
+ * tolerance is clamped to half a grid step so a dust-inflated
834
+ * (MIN_ORDER_SIZE_FACTOR floor) tolerance cannot merge adjacent levels.
835
+ * @returns {boolean} True when the two prices sit on the same level
836
+ */
837
+ function pricesOnSameLevel(priceA, sizeA, typeA, priceB, sizeB, typeB, assets = null, incrementPercent = null) {
838
+ const pa = Number(priceA);
839
+ const pb = Number(priceB);
840
+ if (!Number.isFinite(pa) || !Number.isFinite(pb))
841
+ return pa === pb;
842
+ const size = Math.max(Number(sizeA) || 0, Number(sizeB) || 0);
843
+ const gridPrice = Math.min(pa, pb);
844
+ let tolerance = null;
845
+ for (const type of [typeA, typeB]) {
846
+ if (type == null)
824
847
  continue;
825
- const price = item.price ?? item.order?.price;
826
- const size = item.size ?? item.order?.size ?? 0;
827
- if (price == null || targetPrice == null)
828
- 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
- }
848
+ let t = null;
849
+ try {
850
+ t = calculatePriceTolerance(gridPrice, size, type, assets);
844
851
  }
845
- if (tolerance != null && Math.abs(price - targetPrice) <= tolerance) {
846
- return item;
852
+ catch {
853
+ t = null;
854
+ }
855
+ if (t != null && Number.isFinite(t)) {
856
+ tolerance = tolerance == null ? t : Math.min(tolerance, t);
847
857
  }
848
858
  }
849
- return null;
859
+ if (tolerance == null)
860
+ return pa === pb;
861
+ // Hard cap: never let the tolerance span more than half a grid step. The
862
+ // precision/floor maths above can otherwise exceed the increment for
863
+ // dust-sized or low-precision orders, merging two legitimately adjacent
864
+ // levels (the caller passes the increment when it has one).
865
+ const inc = Number(incrementPercent);
866
+ if (Number.isFinite(inc) && inc > 0) {
867
+ tolerance = Math.min(tolerance, Math.abs(gridPrice) * (inc / 100) * 0.5);
868
+ }
869
+ return Math.abs(pa - pb) <= tolerance;
870
+ }
871
+ /**
872
+ * Relative slack for grid price identity. Large enough to absorb float noise
873
+ * (re-serialization, a stored value recomputed through a different but
874
+ * algebraically equivalent path) yet far below any real grid increment, so it
875
+ * cannot merge two genuinely distinct ladder levels.
876
+ */
877
+ const GRID_PRICE_REL_EPSILON = 1e-9;
878
+ /**
879
+ * Whether two GENESIS-derived grid prices denote the same ladder level by
880
+ * EXACT identity (with float-noise slack).
881
+ *
882
+ * Grid slot prices are frozen ladder values (bit-identical per level), so
883
+ * exact equality is the correct identity for a grid-vs-grid comparison.
884
+ * Deliberately NOT priceSlotEqual at the asset precision (collapses an
885
+ * adjacent band for a low-precision asset) and NOT the chain tolerance (which
886
+ * can exceed the grid increment and merge two legitimately adjacent levels).
887
+ * Prefer sameGridLevel(genesis) where a ladder is available: it maps a drifted
888
+ * price back to its nearest ladder level. Use pricesOnSameLevel instead when
889
+ * one side is a chain-derived price that may sit a few chain quanta off its
890
+ * level.
891
+ *
892
+ * @param {number} priceA - First grid price
893
+ * @param {number} priceB - Second grid price
894
+ * @returns {boolean} True when both are the same ladder level
895
+ */
896
+ function sameGridPrice(priceA, priceB) {
897
+ const a = Number(priceA);
898
+ const b = Number(priceB);
899
+ if (!Number.isFinite(a) || !Number.isFinite(b))
900
+ return a === b;
901
+ if (a === b)
902
+ return true;
903
+ return Math.abs(a - b) <= GRID_PRICE_REL_EPSILON * Math.max(1, Math.abs(a), Math.abs(b));
904
+ }
905
+ /**
906
+ * Whether two grid prices denote the same ladder level, resolving each price
907
+ * to its nearest level through the frozen genesis ladder when one is supplied.
908
+ * This is robust to a price that was chain-corrected / rounded a quantum off
909
+ * its level: slotIndexForPrice maps it back to the level it came from, while a
910
+ * price that genuinely moved to another level resolves to a different index.
911
+ *
912
+ * PRECONDITION / HARDENING: slotIndexForPrice CLAMPS an out-of-rail price onto
913
+ * the edge levels, so two distinct out-of-rail prices would otherwise resolve
914
+ * "equal". This helper therefore only uses slot identity when BOTH prices sit
915
+ * inside [levels[0], levels[N-1]]; otherwise it falls back to exact-level
916
+ * identity (sameGridPrice, with float-noise slack). Callers pass in-rail grid
917
+ * prices today, but the guard makes out-of-rail misuse safe.
918
+ *
919
+ * @param {number} priceA - First grid price
920
+ * @param {number} priceB - Second grid price
921
+ * @param {unknown} genesis - Frozen genesis ladder (`manager._genesis`)
922
+ * @returns {boolean} True when both prices resolve to the same ladder level
923
+ */
924
+ function sameGridLevel(priceA, priceB, genesis) {
925
+ const a = Number(priceA);
926
+ const b = Number(priceB);
927
+ const levels = genesis?.priceLevels;
928
+ if (Array.isArray(levels) && levels.length > 0) {
929
+ const lo = Number(levels[0]);
930
+ const hi = Number(levels[levels.length - 1]);
931
+ const inRail = (p) => Number.isFinite(p) && p >= lo && p <= hi;
932
+ if (!inRail(a) || !inRail(b))
933
+ return sameGridPrice(a, b);
934
+ try {
935
+ const g = genesis;
936
+ return slotIndexForPrice(a, g) === slotIndexForPrice(b, g);
937
+ }
938
+ catch { /* unjudgeable ladder — fall through to exact-level identity */ }
939
+ }
940
+ return sameGridPrice(a, b);
850
941
  }
851
942
  /**
852
943
  * Find an opposite-side order that a candidate placement would CROSS.
@@ -861,10 +952,9 @@ function findPriceCollision(items, excludeId, targetPrice, targetSize, targetTyp
861
952
  * sell ladder was re-priced into marketable buys, triggering a fatal
862
953
  * fund assertion).
863
954
  *
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).
955
+ * Unlike a same-price check, this catches crossings at ANY price overlap and
956
+ * is intended for the re-pricing UPDATE / CREATE paths. The caller decides the
957
+ * exemption policy (e.g. crossed orders cancelled earlier in the same plan).
868
958
  *
869
959
  * @param {Iterable<any>} items - Candidate orders (e.g. manager.orders.values())
870
960
  * @param {number} price - Candidate placement price
@@ -1305,9 +1395,22 @@ function calculateGapSlots(incrementPercent, targetSpreadPercent, gridLimits = {
1305
1395
  /**
1306
1396
  * Calculate sell start index from boundary index and gap slots.
1307
1397
  * sellStartIdx = boundaryIdx + gapSlots + 1
1398
+ *
1399
+ * Absent-aware: Number(null) === 0 and Number('') === 0 would read "no
1400
+ * boundary" as boundary 0 and manufacture a SELL-rail start at gapSlots+1.
1401
+ * Unknown geometry (null/undefined/'') returns NaN so any unguarded caller
1402
+ * fails closed via Number.isFinite instead of silently rail-biasing slot 0.
1403
+ * Every current caller guards first (resolveGapBand, isSlotInRail,
1404
+ * isSlotIndexInGapBand, geometryTypeForSlotIndex, the COW stamp paths);
1405
+ * this carries the same contract in the helper itself so a future caller
1406
+ * cannot bypass it. A genuine 0 boundary still yields gapSlots + 1.
1308
1407
  */
1309
1408
  function getSellStartIdx(boundaryIdx, gapSlots) {
1310
- return Number(boundaryIdx ?? 0) + Number(gapSlots) + 1;
1409
+ const b = Format.toKnownNumber(boundaryIdx);
1410
+ const g = Format.toKnownNumber(gapSlots);
1411
+ if (!Number.isFinite(b) || !Number.isFinite(g))
1412
+ return NaN;
1413
+ return b + g + 1;
1311
1414
  }
1312
1415
  /**
1313
1416
  * Resolve the configured gap-slot count for a manager-like object.
@@ -1316,9 +1419,13 @@ function getSellStartIdx(boundaryIdx, gapSlots) {
1316
1419
  * two can never disagree on band width.
1317
1420
  */
1318
1421
  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)));
1422
+ // Absent-aware: Number('') === 0 is finite, so a '' _gapSlots would pass
1423
+ // the finite test as a valid 0 and collapse the band. '' is unknown →
1424
+ // fall back to the config-derived gap (same contract as
1425
+ // consumePendingFillCrawls' dc87ce01 fallback).
1426
+ const raw = Format.toKnownNumber(manager._gapSlots);
1427
+ if (Number.isFinite(raw)) {
1428
+ return Math.max(0, Math.floor(raw));
1322
1429
  }
1323
1430
  return calculateGapSlots(manager.config?.incrementPercent, manager.config?.targetSpreadPercent, manager.config?.gridLimits);
1324
1431
  }
@@ -1534,7 +1641,7 @@ function validatePersistedBoundary(proposedBoundary, orders, gapSlots) {
1534
1641
  * over 2-3 cycles, so a snapshot taken mid-evacuation (or stale by one
1535
1642
  * crawl, as in recovery-before-CREATE) legitimately reports this. Nuking
1536
1643
  * the snapshot for it discards the boundary progression, pending crawls,
1537
- * streaks and the queued evacuation — the exact sabotage loop seen in H-BTS
1644
+ * streaks and the queued evacuation — the exact sabotage loop seen in <bot>
1538
1645
  * 2026-09-13 (GAP-EVAC flags slot-96, COW plans 96→116, stale snapshot with
1539
1646
  * slot-94 still stranded fails validation, structural resync wipes the
1540
1647
  * plan). All other reasons (ceiling/range/crossed-book/...) are structural
@@ -1591,7 +1698,7 @@ function countGapBandSpread(manager, orders, resolveIndex) {
1591
1698
  * (grid_reconcile_internal.ts), and the COW divergence correction (system.ts).
1592
1699
  * Drift between those copies is what let a fund-driven boundary shift leave a
1593
1700
  * 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
1701
+ * the spread (<bot>: boundary 107→110 left the sell rail parked at 111-130
1595
1702
  * with the bottom three, 111-113, inside the new spread gap; real spread 0.5%
1596
1703
  * vs the 2.0% target).
1597
1704
  *
@@ -1821,11 +1928,18 @@ function slotIdForPrice(price, genesis) {
1821
1928
  * slotIndexForPrice clamps out-of-range prices onto the edge slots (0/N-1),
1822
1929
  * so callers MUST check this before adopting or duplicate-matching: a
1823
1930
  * 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) {
1931
+ * Only genuine float dust at the edge is excused; anything further out is
1932
+ * out-of-grid -> hold/defer, never adopt or cancel as a duplicate.
1933
+ *
1934
+ * The edge excuse is the chain-representable tolerance (pricesOnSameLevel),
1935
+ * clamped to half a ladder step. Deliberately NOT priceSlotEqual at the asset
1936
+ * precision: a price is not an amount, so a precision-4 asset rounds a whole
1937
+ * adjacent band below the rail onto the edge and wrongly classifies a
1938
+ * dip-protection level as in-grid (fail-open). When assets/type are missing,
1939
+ * only float noise at the edge is excused (exact-level identity), so an
1940
+ * unjudgeable outside price stays out-of-grid (fail-closed).
1941
+ */
1942
+ function isChainPriceOutOfGrid(price, genesis, size = 0, type = null, assets = null) {
1829
1943
  const levels = genesis?.priceLevels;
1830
1944
  if (!Array.isArray(levels) || levels.length === 0)
1831
1945
  return false;
@@ -1833,9 +1947,15 @@ function isChainPriceOutOfGrid(price, genesis, precision) {
1833
1947
  return false;
1834
1948
  const min = levels[0];
1835
1949
  const max = levels[levels.length - 1];
1836
- if (price < min && !priceSlotEqual(price, min, precision))
1950
+ const incrementPercent = levels.length > 1 && Number(levels[0]) > 0
1951
+ ? ((Number(levels[1]) - Number(levels[0])) / Number(levels[0])) * 100
1952
+ : null;
1953
+ const onEdge = (edge) => (assets != null && type != null)
1954
+ ? pricesOnSameLevel(price, size, type, edge, size, type, assets, incrementPercent)
1955
+ : sameGridPrice(price, edge);
1956
+ if (price < min && !onEdge(min))
1837
1957
  return true;
1838
- if (price > max && !priceSlotEqual(price, max, precision))
1958
+ if (price > max && !onEdge(max))
1839
1959
  return true;
1840
1960
  return false;
1841
1961
  }
@@ -1944,7 +2064,7 @@ function buildGenesisFromPriceLevels(startPrice, incrementPercent, gapSlots, pri
1944
2064
  createdAt: Date.now()
1945
2065
  };
1946
2066
  }
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 };
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 };
1948
2068
  /**
1949
2069
  * Round a value to a given factor.
1950
2070
  * @param {number} value - Value to round
@@ -79,7 +79,7 @@ import { getErrorMessage, getErrorCode, getErrorName } from '../../utils/errors.
79
79
  import { hasGenesisLadder } from '../genesis_policy.js';
80
80
  import { parseSlotIndex as parseSlotIndexShared } from './slot.js';
81
81
  const { isValidNumber, toFiniteNumber } = Format;
82
- const { blockchainToFloat, floatToBlockchainInt, quantizeFloat, priceSlotEqual } = MathUtils;
82
+ const { blockchainToFloat, floatToBlockchainInt, quantizeFloat, slotIndexForPrice, priceSlotEqual } = MathUtils;
83
83
  const orderLogger = new Logger('Order');
84
84
  const ORDER_GONE_ERROR_FRAGMENT = 'not found';
85
85
  /**
@@ -398,7 +398,18 @@ function _validatePriceCorrectionEntry(manager, entry) {
398
398
  if (!hasGenesisLadder(manager?._genesis)) {
399
399
  return { valid: false, reason: `no price ladder (INV-GRID-004) — slot ${slotId} has no authoritative price` };
400
400
  }
401
- if (!priceSlotEqual(slot.price, Number(entry.expectedPrice), Number(precision))) {
401
+ // Genesis is guaranteed here (guarded above), so compare ladder LEVELS --
402
+ // not priceSlotEqual at the asset amount precision, which collapses
403
+ // adjacent levels for a low-precision asset and would accept a stale entry.
404
+ let sameLevel;
405
+ try {
406
+ const genesis = manager._genesis;
407
+ sameLevel = slotIndexForPrice(slot.price, genesis) === slotIndexForPrice(Number(entry.expectedPrice), genesis);
408
+ }
409
+ catch {
410
+ sameLevel = priceSlotEqual(slot.price, Number(entry.expectedPrice), Number(precision));
411
+ }
412
+ if (!sameLevel) {
402
413
  return { valid: false, reason: `slot ${slotId} now targets ${slot.price} (entry queued ${entry.expectedPrice})` };
403
414
  }
404
415
  // Size check: the broadcast sends amountToSell from the QUEUED snapshot.
@@ -2557,9 +2568,10 @@ export function consumePendingFillCrawls(manager) {
2557
2568
  catch { /* best-effort */ }
2558
2569
  }
2559
2570
  };
2560
- // NB: Number(null) === 0 — check null/undefined explicitly, or a
2571
+ // NB: Number(null) === 0 and Number('') === 0 — check null/undefined/''
2572
+ // explicitly (the '' case matches runPreBroadcastGuards), or a
2561
2573
  // boundary-less manager would "apply" onto slot 0.
2562
- if (manager?.boundaryIdx === null || manager?.boundaryIdx === undefined) {
2574
+ if (manager?.boundaryIdx === null || manager?.boundaryIdx === undefined || manager?.boundaryIdx === '') {
2563
2575
  clear();
2564
2576
  return { applied: false, reason: 'null-boundary' };
2565
2577
  }
@@ -1587,7 +1587,7 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
1587
1587
  // orders through the budget allocation below but never shift rails. The
1588
1588
  // fund-ratio writer was removed — it moved the boundary without guaranteed
1589
1589
  // same-batch refills, so a guard-vetoed refill stranded empty slots past
1590
- // the new boundary (h-bts 91->94) with no repair path. Remaining writers:
1590
+ // the new boundary (<bot> 91->94) with no repair path. Remaining writers:
1591
1591
  // fills (deriveTargetBoundary, same-cycle rotations) and spread promotion
1592
1592
  // (shifts only onto slots placed in the same atomic batch).
1593
1593
  let resizeCowResult = null;
@@ -1627,7 +1627,7 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
1627
1627
  // GUARD keeps gap-band strays typed BUY/SELL (never SPREAD+ACTIVE), so
1628
1628
  // without a geometric filter they are selected as "closest to market"
1629
1629
  // and left inside the gap — collapsing the spread when a fill-driven
1630
- // boundary shift moves into the rail (h-bts: boundary 107->110 left
1630
+ // boundary shift moves into the rail (<bot>: boundary 107->110 left
1631
1631
  // the sell rail parked at 111-130 with the bottom three, 111-113,
1632
1632
  // inside the new spread gap; real spread 0.5% instead of the 2.0%
1633
1633
  // target).