dexbot 1.6.16 → 1.6.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/analysis/tradingview/README.md +2 -2
  3. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  4. package/claw/package.json +1 -1
  5. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  7. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +5 -3
  8. package/dist/analysis/tradingview/grid_reset_sim.js +1 -1
  9. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +4 -4
  10. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
  11. package/dist/modules/account_bots.d.ts +3 -0
  12. package/dist/modules/chain_keys.d.ts +1 -1
  13. package/dist/modules/constants.d.ts +6 -0
  14. package/dist/modules/constants.js +34 -6
  15. package/dist/modules/credit_pricing.d.ts +20 -1
  16. package/dist/modules/credit_pricing.js +23 -1
  17. package/dist/modules/credit_runtime.js +33 -16
  18. package/dist/modules/dexbot_class.d.ts +3 -1
  19. package/dist/modules/dexbot_class.js +5 -2
  20. package/dist/modules/dexbot_cow_runtime.d.ts +28 -37
  21. package/dist/modules/dexbot_cow_runtime.js +47 -66
  22. package/dist/modules/dexbot_maintenance_runtime.js +68 -10
  23. package/dist/modules/launcher/credential_daemon.d.ts +14 -2
  24. package/dist/modules/launcher/credential_daemon.js +60 -26
  25. package/dist/modules/order/grid.d.ts +7 -0
  26. package/dist/modules/order/grid.js +157 -15
  27. package/dist/modules/order/index.d.ts +15 -0
  28. package/dist/modules/order/manager.d.ts +30 -7
  29. package/dist/modules/order/manager.js +108 -12
  30. package/dist/modules/order/strategy.d.ts +5 -0
  31. package/dist/modules/order/strategy.js +23 -2
  32. package/dist/modules/order/utils/math.d.ts +41 -1
  33. package/dist/modules/order/utils/math.js +47 -1
  34. package/dist/modules/order/utils/order.d.ts +13 -0
  35. package/dist/modules/order/utils/order.js +61 -7
  36. package/dist/modules/order/utils/system.d.ts +66 -0
  37. package/dist/modules/order/utils/system.js +135 -0
  38. package/dist/modules/order/utils/validate.d.ts +3 -1
  39. package/dist/modules/order/utils/validate.js +5 -1
  40. package/dist/modules/types.d.ts +35 -2
  41. package/dist/scripts/analyze-credit.js +64 -23
  42. package/dist/scripts/bts_distribution.d.ts +66 -0
  43. package/dist/scripts/bts_distribution.js +2102 -0
  44. package/dist/scripts/token_distribution.d.ts +45 -0
  45. package/dist/scripts/token_distribution.js +1870 -0
  46. package/dist/unlock.js +42 -24
  47. package/docs/COW_INVARIANTS.md +6 -0
  48. package/docs/DEXBOT_COMPARISON.md +5 -5
  49. package/docs/EVOLUTION.md +9 -8
  50. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -1
  51. package/docs/GRID_PRICE_INVARIANT.md +6 -0
  52. package/docs/GRID_RECALCULATION.md +3 -3
  53. package/docs/LOGGING.md +9 -0
  54. package/docs/MPA_CREDIT_USAGE.md +3 -2
  55. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +117 -0
  56. package/docs/README.md +1 -1
  57. package/docs/architecture.md +98 -1
  58. package/market_adapter/README.md +2 -2
  59. package/package.json +3 -1
  60. package/scripts/README.md +85 -148
@@ -458,6 +458,52 @@ function getAssetFeesSafe(assetSymbol, assetAmount = null, isMaker = true) {
458
458
  return null;
459
459
  }
460
460
  }
461
+ /**
462
+ * Fund budget for placing a KNOWN set of pending slots (spread correction).
463
+ *
464
+ * `calculateAvailableFundsValue` computes `chainFree - virtual - fees`, where
465
+ * `virtual` is the projection of the side's not-yet-placed (VIRTUAL) slots.
466
+ * That is the right number for "how much room is left beyond the projected
467
+ * rail", but it is CIRCULAR when the caller is funding exactly those projected
468
+ * slots: if the projection is larger than the account holds free (a rail sized
469
+ * from a bigger balance, from inventory locked in resting orders, or from
470
+ * optimistic proceeds), `available` reads 0 while the chain clearly holds free
471
+ * funds, and the projection can never shrink because nothing gets placed.
472
+ * Live symptom: `planned 3, placing 0` every cycle for 84 minutes
473
+ * (`free 454560.80` vs `virtual 456046.21`).
474
+ *
475
+ * So for a known candidate set, re-derive the budget from chain truth: add the
476
+ * projection back, but never more than the candidates themselves need and never
477
+ * more than the chain actually holds free. The chain remains the final arbiter
478
+ * (an over-commit is rejected at broadcast), and the fee reservation stays
479
+ * inside `availableFund` for every healthy cycle.
480
+ *
481
+ * Only an OVERSUBSCRIPTION (projection > chain free) triggers the fallback. A
482
+ * zero caused by the fee reservation or by a genuinely empty balance is a real
483
+ * constraint: the projection fits, so honour it (and its fees) and place
484
+ * nothing.
485
+ *
486
+ * @param {{availableFund?: number, virtualIntent?: number, chainFree?: number, candidateIdeals?: number}} args
487
+ * @returns {{budget: number, oversubscribed: number, eroded: boolean}} budget to
488
+ * place with; projection excess over chain free (0 = healthy); whether the
489
+ * chain-truth re-derivation was needed
490
+ */
491
+ function deriveChainTruthFundBudget(args) {
492
+ const available = Math.max(0, toFiniteNumber(args?.availableFund, 0));
493
+ const virtual = Math.max(0, toFiniteNumber(args?.virtualIntent, 0));
494
+ const chainFree = Math.max(0, toFiniteNumber(args?.chainFree, 0));
495
+ const ideals = Math.max(0, toFiniteNumber(args?.candidateIdeals, 0));
496
+ const oversubscribed = Math.max(0, virtual - chainFree);
497
+ // `oversubscribed <= 0` means the projection FITS in the free balance, so a
498
+ // zero `available` is a real constraint (fees/reservation), not the circular
499
+ // case — never re-derive past it.
500
+ if (available > 0 || oversubscribed <= 0 || ideals <= 0 || chainFree <= 0) {
501
+ return { budget: available, oversubscribed, eroded: false };
502
+ }
503
+ // Oversubscribed: fund the candidates from what the chain really holds.
504
+ const budget = Math.min(chainFree, Math.min(virtual, ideals));
505
+ return { budget, oversubscribed, eroded: budget > 0 };
506
+ }
461
507
  /**
462
508
  * Calculate available funds for a specific side (buy or sell).
463
509
  * Deducts virtual reservations, BTS fees owed, and BTS fee reservation from chain-free balance.
@@ -2102,7 +2148,7 @@ function buildGenesisFromPriceLevels(startPrice, incrementPercent, gapSlots, pri
2102
2148
  createdAt: Date.now()
2103
2149
  };
2104
2150
  }
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 };
2151
+ export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
2106
2152
  /**
2107
2153
  * Round a value to a given factor.
2108
2154
  * @param {number} value - Value to round
@@ -1039,6 +1039,17 @@ declare function buildDelta(masterGrid: Map<string, ManagedOrder>, workingGrid:
1039
1039
  priceRelativeTolerance?: number;
1040
1040
  };
1041
1041
  }): DeltaAction[];
1042
+ /**
1043
+ * A pending-crawl ledger entry as consumed by a derivation.
1044
+ * `ts` is carried so the commit clears exactly the records the derivation
1045
+ * folded — never a newer record for the same slot (recording happens at fill
1046
+ * intake, so a slot can be re-recorded between derivation and commit).
1047
+ */
1048
+ type CrawlEntry = {
1049
+ slotId: string;
1050
+ side: string;
1051
+ ts?: number;
1052
+ };
1042
1053
  /**
1043
1054
  * Check whether a fill is eligible to drive boundary shift / rotation.
1044
1055
  * Partials only count when they are delayed-rotation triggers.
@@ -1075,6 +1086,7 @@ declare function deriveTargetBoundary(fills: Array<{
1075
1086
  } | null): {
1076
1087
  boundaryIdx: number | null;
1077
1088
  remainingBudget: number;
1089
+ consumedCrawlIds: CrawlEntry[];
1078
1090
  };
1079
1091
  /**
1080
1092
  * Apply recorded-but-uncommitted fill crawls to the committed boundary.
@@ -1403,5 +1415,6 @@ declare function collectKnownOnChainOrderIds(mgr: OrderManagerLike, placedResult
1403
1415
  all: string[];
1404
1416
  };
1405
1417
  export { parseChainOrder, applyChainSizeToGridOrder, buildFillKey, correctOrderPriceOnChain, correctAllPriceMismatches, _validatePriceCorrectionEntry, _stampCorrectionProvenance, findLiveOrderOwnerByChainId, buildCreateOrderArgs, getOrderTypeFromUpdatedFlags, resolveConfiguredPriceBound, virtualizeOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, detectGapEvacuationCandidates, updateGapEvacuationStreaks, resolveSpreadOrderSide, chainOrderMatchesSlot, chainOrderMatchesSlotWithTolerance, crossingCandidateChainId, isCrossingCheckCandidate, buildCrossingCheckCandidates, parseSlotIndex, filterOrdersByType, buildOutsideInPairGroups, extractBatchOperationResults, formatUnmatchedChainOrder, isNonBlockingUnmatchedOrder, isStrandedHoldOrder, isOrderOnChain, isOrderVirtual, hasOnChainId, isOrderPlaced, isPhantomOrder, isSlotAvailable, isEmptyGridSlot, isOrderHealthy, checkSizeThreshold, checkSizesBeforeMinimum, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, shouldFlagOutOfSpread, buildIndexes, validateIndexes, ordersEqual, buildDelta, deriveTargetBoundary, isShiftEligibleFill, resolveEdgeCount, resolveEdgeOrders, selectEdgeSlots, getCoreOrdersTotal, getSideBudget, calculateBudgetedSizes, buildCreateOpFingerprint, isOrderGoneErrorMessage, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
1418
+ export type { CrawlEntry };
1406
1419
  export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
1407
1420
  //# sourceMappingURL=order.d.ts.map
@@ -2367,9 +2367,14 @@ function buildDelta(masterGrid, workingGrid, options = {}) {
2367
2367
  }
2368
2368
  return actions;
2369
2369
  }
2370
- // ================================================================================
2371
- // SECTION 10: STRATEGY CALCULATIONS
2372
- // ================================================================================
2370
+ /** Normalise a ledger record into the identity the commit clears by. */
2371
+ function toCrawlEntry(e) {
2372
+ return {
2373
+ slotId: String(e?.slotId ?? ''),
2374
+ side: String(e?.side ?? ''),
2375
+ ts: Number.isFinite(Number(e?.ts)) ? Number(e?.ts) : undefined,
2376
+ };
2377
+ }
2373
2378
  /**
2374
2379
  * Check whether a fill is eligible to drive boundary shift / rotation.
2375
2380
  * Partials only count when they are delayed-rotation triggers.
@@ -2470,7 +2475,7 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2470
2475
  if (referencePrice === null) {
2471
2476
  const fallbackCap = Math.max(Math.floor((config?.coreOrders?.sell ?? 1) / 2), Math.floor((config?.coreOrders?.buy ?? 1) / 2), 1);
2472
2477
  const effectiveBudget = crossChunkBudget ?? fallbackCap;
2473
- return { boundaryIdx: null, remainingBudget: effectiveBudget };
2478
+ return { boundaryIdx: null, remainingBudget: effectiveBudget, consumedCrawlIds: [] };
2474
2479
  }
2475
2480
  newBoundaryIdx = calculateIdealBoundary(allSlots, referencePrice, gapSlots);
2476
2481
  if (!Number.isFinite(newBoundaryIdx) || newBoundaryIdx < 0) {
@@ -2478,7 +2483,7 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2478
2483
  // exists (calculateIdealBoundary returns -1). Stay null rather
2479
2484
  // than letting the clamp below fabricate a slot-0 boundary.
2480
2485
  const fallbackCap = Math.max(Math.floor((config?.coreOrders?.sell ?? 1) / 2), Math.floor((config?.coreOrders?.buy ?? 1) / 2), 1);
2481
- return { boundaryIdx: null, remainingBudget: crossChunkBudget ?? fallbackCap };
2486
+ return { boundaryIdx: null, remainingBudget: crossChunkBudget ?? fallbackCap, consumedCrawlIds: [] };
2482
2487
  }
2483
2488
  recovered = true;
2484
2489
  }
@@ -2510,12 +2515,50 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2510
2515
  // anything older is still owed and shifts here. Edge-slot entries
2511
2516
  // never crawl (static insurance), same as live fills.
2512
2517
  const currentSlotIds = new Set((fills ?? []).map((f) => f?.id).filter((id) => typeof id === 'string' && id.length > 0));
2513
- const owedPending = (pendingCrawls ?? []).filter((e) => e
2514
- && typeof e.slotId === 'string' && e.slotId.length > 0
2518
+ const allPending = (pendingCrawls ?? [])
2519
+ .filter((e) => !!e
2520
+ && typeof e.slotId === 'string' && e.slotId.length > 0);
2521
+ const owedPending = allPending.filter((e) => e
2515
2522
  && !currentSlotIds.has(e.slotId)
2516
2523
  && (e.side === ORDER_TYPES.BUY || e.side === ORDER_TYPES.SELL)
2517
2524
  && !(e.side === ORDER_TYPES.BUY && edgeBuyIds && edgeBuyIds.has(e.slotId))
2518
2525
  && !(e.side === ORDER_TYPES.SELL && edgeSellIds && edgeSellIds.has(e.slotId)));
2526
+ /**
2527
+ * Ledger records this derivation CONSUMED:
2528
+ * - everything it deliberately never counts (current-batch slots whose
2529
+ * shift comes from `fills`, edge-classified slots which never crawl,
2530
+ * malformed records), and
2531
+ * - the owed entries whose shift it actually APPLIED.
2532
+ *
2533
+ * `applied` is the (possibly capped) net shift. A capped fold applies only
2534
+ * part of the owed net, so only that part may be consumed — the remainder
2535
+ * stays owed, or the next derivation would either lose it (clear-all) or
2536
+ * apply it twice (keep-all).
2537
+ */
2538
+ const consumedFor = (applied) => {
2539
+ const never = allPending.filter((e) => !owedPending.includes(e));
2540
+ let appliedEntries = [];
2541
+ if (cap <= 0) {
2542
+ // No cross-chunk budget left: NOTHING was applied, so every owed
2543
+ // record stays owed (a net-zero reading here is not a cancellation).
2544
+ appliedEntries = [];
2545
+ }
2546
+ else if (applied === 0) {
2547
+ // A net-zero mix was fully accounted for by cancelling out.
2548
+ appliedEntries = owedPending;
2549
+ }
2550
+ else {
2551
+ // Consume same-side entries up to the applied magnitude; the mixed
2552
+ // remainder still nets out to (net - applied) for the next run.
2553
+ const dirSide = applied > 0 ? ORDER_TYPES.SELL : ORDER_TYPES.BUY;
2554
+ appliedEntries = owedPending
2555
+ .filter((e) => e.side === dirSide)
2556
+ .slice(0, Math.abs(applied));
2557
+ }
2558
+ return [...never, ...appliedEntries].map(toCrawlEntry);
2559
+ };
2560
+ /** Every owed record is subsumed (absolute anchor / generation discard). */
2561
+ const consumedAll = () => allPending.map(toCrawlEntry);
2519
2562
  for (const fill of fills ?? []) {
2520
2563
  if (!isShiftEligibleFill(fill))
2521
2564
  continue;
@@ -2556,8 +2599,18 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2556
2599
  return {
2557
2600
  boundaryIdx: Math.max(0, Math.min((allSlots.length - gapSlots - 1) >= 0 ? (allSlots.length - gapSlots - 1) : (allSlots.length - 1), newBoundaryIdx)),
2558
2601
  remainingBudget: effectiveBudget,
2602
+ // The absolute fill anchor positions from live prices, which already
2603
+ // reflect every owed delta. The remaining delta is NOT added on top
2604
+ // (double-count guard), so every record is subsumed regardless of
2605
+ // what the cap would have admitted.
2606
+ consumedCrawlIds: consumedAll(),
2559
2607
  };
2560
2608
  }
2609
+ // A truncated shift (or an exhausted cross-chunk budget) applies only part
2610
+ // of the owed net, so the consumed set below is scoped to WHAT WAS APPLIED:
2611
+ // the commit must neither lose the remainder (the 2026-10-25 leak: 7 fills,
2612
+ // boundary +3 planned, all 7 records dropped) nor leave an applied entry
2613
+ // owed for a second pass.
2561
2614
  if (Math.abs(netShift) > cap) {
2562
2615
  netShift = Math.sign(netShift) * cap;
2563
2616
  }
@@ -2575,6 +2628,7 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2575
2628
  return {
2576
2629
  boundaryIdx: Math.max(0, Math.min(ceiling, newBoundaryIdx)),
2577
2630
  remainingBudget,
2631
+ consumedCrawlIds: consumedFor(netShift),
2578
2632
  };
2579
2633
  }
2580
2634
  /**
@@ -498,10 +498,76 @@ export declare function resolveSpreadMarketReference(manager: OrderManagerLike):
498
498
  * @param {Object} manager - OrderManager instance
499
499
  * @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
500
500
  */
501
+ /**
502
+ * Re-anchor the boundary so the newest REAL fill sits outside its own window.
503
+ *
504
+ * A boundary crawl is ±1 slot per committed fill, so a window that ended up
505
+ * behind the fill (a sweep filled several slots while the commit dropped the
506
+ * owed crawls, or the crawl was capped) cannot catch up by crawling: every
507
+ * tightening slot on that side is then at/through the last fill and the
508
+ * last-fill guard refuses all of them, while the funds sit in the resting
509
+ * (stranded) inventory — the 2026-10-25 deadlock (7 sells swept slots 147-153,
510
+ * the boundary ended at 146 and stayed there; `last-fill-blocked` thereafter).
511
+ *
512
+ * The fill itself is the anchor, so place it outside its window:
513
+ * SELL fill at slot f -> boundary >= f - gapSlots (sellStart = f + 1)
514
+ * BUY fill at slot f -> boundary <= f - 1 (buy window ends below f)
515
+ *
516
+ * Only a genuine on-ladder fill price is accepted (same one-increment drift
517
+ * bound as `resolveOnGridPivot`), and the candidate must pass the same
518
+ * placed-order-aware validation the boundary commit gate uses, so a re-anchor
519
+ * can never strand a live order inside the re-typed band.
520
+ *
521
+ * @param {Object} manager - OrderManager (pivot + genesis)
522
+ * @param {number|null} boundaryIdx - Boundary the derivation would commit
523
+ * @param {Array<Object>} slots - Grid slots (current generation)
524
+ * @param {number} gapSlots - Gap band width
525
+ * @returns {{boundaryIdx: number|null, reanchored: boolean, from?: number|null, to?: number, side?: string, fillSlot?: number, reason?: string}}
526
+ */
527
+ export declare function reanchorBoundaryFromLastFill(manager: OrderManagerLike, boundaryIdx: number | null | undefined, slots: ManagedOrder[] | null | undefined, gapSlots: number): {
528
+ boundaryIdx: number | null;
529
+ reanchored: boolean;
530
+ from?: number | null;
531
+ to?: number;
532
+ side?: string;
533
+ fillSlot?: number;
534
+ reason?: string;
535
+ };
501
536
  export declare function resolveLastFillGuardReference(manager: OrderManagerLike): {
502
537
  price: number | null;
503
538
  type: string | null;
504
539
  };
540
+ /**
541
+ * LAST-FILL-GUARD — DIRECTION ONLY, relative to the last fill price.
542
+ *
543
+ * BUY blocked if price >= pivot (never place a higher BUY)
544
+ * SELL blocked if price <= pivot (never place a lower SELL)
545
+ *
546
+ * Lives here (not in the COW runtime) so the spread-correction PLANNER and the
547
+ * broadcast guard judge candidates with literally the same predicate: a batch
548
+ * must never be built from a create the guard will drop, and a dropped batch
549
+ * must never be reported as an unexplained "prepared but not executed".
550
+ *
551
+ * A placement on the permitted side is always profitable against the last trade
552
+ * we actually did: a BUY below the last sell, a SELL above the last buy. Equal
553
+ * price counts as blocked — that is a re-place at the just-filled level, the
554
+ * immediate re-fill loop this guard exists to prevent. Cold (no numeric pivot,
555
+ * or no fill side recorded — e.g. a book-seeded pivot) => disabled. The grid
556
+ * increment takes no part (kept in the signature for call-site stability).
557
+ *
558
+ * @param {number} price - Target order price
559
+ * @param {number} _size - Order size (unused, kept for compat)
560
+ * @param {string} type - ORDER_TYPES.BUY/SELL
561
+ * @param {number|null} lastPrice - Most recent fill price
562
+ * @param {string|null} lastType - Most recent fill side; null keeps the guard cold
563
+ * @param {number|any} _incrementPercent - Unused (kept for signature compat)
564
+ * @returns {{blocked: boolean, pivot: number|null, threshold?: number|null}}
565
+ */
566
+ export declare function isLastFillGuardBlocked(price: number, _size: number, type: unknown, lastPrice: number | null, lastType: string | null, _incrementPercent?: number): {
567
+ blocked: boolean;
568
+ pivot: number | null;
569
+ threshold?: number | null;
570
+ };
505
571
  /**
506
572
  * Restore the persisted bot-scoped last-market-fill reference into the
507
573
  * manager. Deliberately independent of the boundary and the genesis: this is
@@ -1276,6 +1276,102 @@ export function resolveSpreadMarketReference(manager) {
1276
1276
  * @param {Object} manager - OrderManager instance
1277
1277
  * @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
1278
1278
  */
1279
+ /**
1280
+ * Re-anchor the boundary so the newest REAL fill sits outside its own window.
1281
+ *
1282
+ * A boundary crawl is ±1 slot per committed fill, so a window that ended up
1283
+ * behind the fill (a sweep filled several slots while the commit dropped the
1284
+ * owed crawls, or the crawl was capped) cannot catch up by crawling: every
1285
+ * tightening slot on that side is then at/through the last fill and the
1286
+ * last-fill guard refuses all of them, while the funds sit in the resting
1287
+ * (stranded) inventory — the 2026-10-25 deadlock (7 sells swept slots 147-153,
1288
+ * the boundary ended at 146 and stayed there; `last-fill-blocked` thereafter).
1289
+ *
1290
+ * The fill itself is the anchor, so place it outside its window:
1291
+ * SELL fill at slot f -> boundary >= f - gapSlots (sellStart = f + 1)
1292
+ * BUY fill at slot f -> boundary <= f - 1 (buy window ends below f)
1293
+ *
1294
+ * Only a genuine on-ladder fill price is accepted (same one-increment drift
1295
+ * bound as `resolveOnGridPivot`), and the candidate must pass the same
1296
+ * placed-order-aware validation the boundary commit gate uses, so a re-anchor
1297
+ * can never strand a live order inside the re-typed band.
1298
+ *
1299
+ * @param {Object} manager - OrderManager (pivot + genesis)
1300
+ * @param {number|null} boundaryIdx - Boundary the derivation would commit
1301
+ * @param {Array<Object>} slots - Grid slots (current generation)
1302
+ * @param {number} gapSlots - Gap band width
1303
+ * @returns {{boundaryIdx: number|null, reanchored: boolean, from?: number|null, to?: number, side?: string, fillSlot?: number, reason?: string}}
1304
+ */
1305
+ export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlots) {
1306
+ // NB: Number(null) === 0 and Number('') === 0 — a boundary-less manager must
1307
+ // not be re-anchored onto slot 0 (same absent-value trap as
1308
+ // consumePendingFillCrawls).
1309
+ if (boundaryIdx === null || boundaryIdx === undefined || boundaryIdx === '') {
1310
+ return { boundaryIdx: boundaryIdx ?? null, reanchored: false, reason: 'no-boundary' };
1311
+ }
1312
+ const boundary = Number(boundaryIdx);
1313
+ if (!Number.isFinite(boundary))
1314
+ return { boundaryIdx: boundaryIdx ?? null, reanchored: false, reason: 'no-boundary' };
1315
+ const ref = resolveLastFillGuardReference(manager);
1316
+ const price = Number(ref?.price);
1317
+ if (!Number.isFinite(price) || price <= 0)
1318
+ return { boundaryIdx: boundary, reanchored: false, reason: 'cold-pivot' };
1319
+ const side = ref.type === ORDER_TYPES.SELL ? ORDER_TYPES.SELL : ref.type === ORDER_TYPES.BUY ? ORDER_TYPES.BUY : null;
1320
+ if (!side)
1321
+ return { boundaryIdx: boundary, reanchored: false, reason: 'no-fill-side' };
1322
+ const genesis = manager?._genesis;
1323
+ const levels = genesis?.priceLevels;
1324
+ if (!genesis || !Array.isArray(levels) || levels.length === 0) {
1325
+ return { boundaryIdx: boundary, reanchored: false, reason: 'no-genesis' };
1326
+ }
1327
+ let idx;
1328
+ try {
1329
+ idx = Number(MathUtils.slotIndexForPrice(price, genesis));
1330
+ }
1331
+ catch {
1332
+ return { boundaryIdx: boundary, reanchored: false, reason: 'unresolvable-price' };
1333
+ }
1334
+ if (!Number.isFinite(idx) || idx < 0)
1335
+ return { boundaryIdx: boundary, reanchored: false, reason: 'unresolvable-price' };
1336
+ // Only a genuine ladder level: an off-ladder (orphan/adopted) fill price
1337
+ // must not be snapped into geometry. One increment is the caller's drift
1338
+ // bound everywhere else (resolveOnGridPivot), so reuse it here.
1339
+ const levelPrice = Number(MathUtils.priceForSlot(idx, genesis));
1340
+ const incrementPct = Math.abs(Number(manager?.config?.incrementPercent));
1341
+ const maxDrift = Number.isFinite(incrementPct) && incrementPct > 0 ? incrementPct / 100 : 0.005;
1342
+ if (!Number.isFinite(levelPrice) || levelPrice <= 0 || Math.abs(levelPrice - price) / price > maxDrift) {
1343
+ return { boundaryIdx: boundary, reanchored: false, reason: 'off-ladder-fill' };
1344
+ }
1345
+ const gap = Number.isFinite(Number(gapSlots)) && Number(gapSlots) >= 0 ? Math.floor(Number(gapSlots)) : 0;
1346
+ const slotCount = Array.isArray(slots) ? slots.length : 0;
1347
+ if (slotCount === 0)
1348
+ return { boundaryIdx: boundary, reanchored: false, reason: 'no-slots' };
1349
+ const ceiling = (slotCount - gap - 1) >= 0 ? (slotCount - gap - 1) : (slotCount - 1);
1350
+ const required = side === ORDER_TYPES.SELL ? idx - gap : idx - 1;
1351
+ if (side === ORDER_TYPES.SELL ? boundary >= required : boundary <= required) {
1352
+ return { boundaryIdx: boundary, reanchored: false, reason: 'already-outside' };
1353
+ }
1354
+ const candidate = Math.max(0, Math.min(ceiling, required));
1355
+ if (candidate === boundary)
1356
+ return { boundaryIdx: boundary, reanchored: false, reason: 'no-op' };
1357
+ let check = { ok: true };
1358
+ try {
1359
+ check = MathUtils.validatePersistedBoundary(candidate, slots ?? [], gap);
1360
+ }
1361
+ catch (err) {
1362
+ check = { ok: false, reason: getErrorMessage(err) };
1363
+ }
1364
+ if (!check || check.ok !== true) {
1365
+ return { boundaryIdx: boundary, reanchored: false, reason: `unsafe: ${check?.reason ?? 'unknown'}` };
1366
+ }
1367
+ try {
1368
+ manager.logger?.log?.(`[BOUNDARY] Re-anchored from the last fill: ${side} filled at slot ${idx} ` +
1369
+ `(${price.toFixed(6)}); boundary ${boundary} -> ${candidate} so the fill sits outside ` +
1370
+ `its own window (crawl alone cannot recover a window behind the fill)`, 'warn');
1371
+ }
1372
+ catch { /* logging is best-effort */ }
1373
+ return { boundaryIdx: candidate, reanchored: true, from: boundary, to: candidate, side, fillSlot: idx };
1374
+ }
1279
1375
  export function resolveLastFillGuardReference(manager) {
1280
1376
  const livePrice = Number(manager?._lastFilledPrice);
1281
1377
  const liveType = manager?._lastFilledType;
@@ -1289,6 +1385,45 @@ export function resolveLastFillGuardReference(manager) {
1289
1385
  }
1290
1386
  return { price: null, type: null };
1291
1387
  }
1388
+ /**
1389
+ * LAST-FILL-GUARD — DIRECTION ONLY, relative to the last fill price.
1390
+ *
1391
+ * BUY blocked if price >= pivot (never place a higher BUY)
1392
+ * SELL blocked if price <= pivot (never place a lower SELL)
1393
+ *
1394
+ * Lives here (not in the COW runtime) so the spread-correction PLANNER and the
1395
+ * broadcast guard judge candidates with literally the same predicate: a batch
1396
+ * must never be built from a create the guard will drop, and a dropped batch
1397
+ * must never be reported as an unexplained "prepared but not executed".
1398
+ *
1399
+ * A placement on the permitted side is always profitable against the last trade
1400
+ * we actually did: a BUY below the last sell, a SELL above the last buy. Equal
1401
+ * price counts as blocked — that is a re-place at the just-filled level, the
1402
+ * immediate re-fill loop this guard exists to prevent. Cold (no numeric pivot,
1403
+ * or no fill side recorded — e.g. a book-seeded pivot) => disabled. The grid
1404
+ * increment takes no part (kept in the signature for call-site stability).
1405
+ *
1406
+ * @param {number} price - Target order price
1407
+ * @param {number} _size - Order size (unused, kept for compat)
1408
+ * @param {string} type - ORDER_TYPES.BUY/SELL
1409
+ * @param {number|null} lastPrice - Most recent fill price
1410
+ * @param {string|null} lastType - Most recent fill side; null keeps the guard cold
1411
+ * @param {number|any} _incrementPercent - Unused (kept for signature compat)
1412
+ * @returns {{blocked: boolean, pivot: number|null, threshold?: number|null}}
1413
+ */
1414
+ export function isLastFillGuardBlocked(price, _size, type, lastPrice, lastType, _incrementPercent) {
1415
+ const numPrice = Number(price);
1416
+ if (!Number.isFinite(numPrice))
1417
+ return { blocked: false, pivot: null };
1418
+ if (lastPrice == null || !Number.isFinite(Number(lastPrice)) || lastType == null)
1419
+ return { blocked: false, pivot: null };
1420
+ const pivot = Number(lastPrice);
1421
+ if (type === ORDER_TYPES.BUY && numPrice >= pivot)
1422
+ return { blocked: true, pivot, threshold: pivot };
1423
+ if (type === ORDER_TYPES.SELL && numPrice <= pivot)
1424
+ return { blocked: true, pivot, threshold: pivot };
1425
+ return { blocked: false, pivot: null, threshold: null };
1426
+ }
1292
1427
  /**
1293
1428
  * Restore the persisted bot-scoped last-market-fill reference into the
1294
1429
  * manager. Deliberately independent of the boundary and the genesis: this is
@@ -289,15 +289,17 @@ declare function buildAbortedResult(reason: string | null | undefined): {
289
289
  * @param {Object} params - Result parameters
290
290
  * @returns {Object} Success result object
291
291
  */
292
- declare function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundary, planningDuration, refillSlotIds }: {
292
+ declare function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundary, planningDuration, refillSlotIds, consumedCrawlIds }: {
293
293
  actions: CowAction[];
294
294
  stateUpdates: ManagedOrder[];
295
295
  workingGrid: WorkingGrid;
296
296
  workingBoundary: number | null;
297
297
  planningDuration: number;
298
298
  refillSlotIds?: unknown;
299
+ consumedCrawlIds?: unknown;
299
300
  }): {
300
301
  aborted: boolean;
302
+ consumedCrawlIds?: {} | null | undefined;
301
303
  refillSlotIds?: {} | null | undefined;
302
304
  actions: CowAction[];
303
305
  stateUpdates: ManagedOrder[];
@@ -1137,7 +1137,7 @@ function buildAbortedResult(reason) {
1137
1137
  * @param {Object} params - Result parameters
1138
1138
  * @returns {Object} Success result object
1139
1139
  */
1140
- function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundary, planningDuration, refillSlotIds }) {
1140
+ function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundary, planningDuration, refillSlotIds, consumedCrawlIds }) {
1141
1141
  return {
1142
1142
  actions,
1143
1143
  stateUpdates,
@@ -1150,6 +1150,10 @@ function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundar
1150
1150
  // planned boundary shift. May be absent/empty => executor treats as
1151
1151
  // empty (guarded default, never fail-open).
1152
1152
  ...(refillSlotIds !== undefined ? { refillSlotIds } : {}),
1153
+ // Crawl-ledger wire: the owed fill-crawl records this plan's derivation
1154
+ // actually folded. The commit clears only these; anything it could not
1155
+ // apply stays owed for the next derivation.
1156
+ ...(consumedCrawlIds !== undefined ? { consumedCrawlIds } : {}),
1153
1157
  aborted: false
1154
1158
  };
1155
1159
  }
@@ -38,7 +38,15 @@ export type OrderState = 'virtual' | 'active' | 'partial';
38
38
  * ('stale-snapshot' is degraded-ok, not a stall: the planner still acts, it
39
39
  * only withholds the LAST-FILL-GUARD bypass.)
40
40
  */
41
- export type SpreadCorrectionStall = 'no-free-funds' | 'unfunded' | 'no-candidates' | 'cold-book' | 'unmatched-orders' | 'readiness-gate' | 'batch-not-executed' | 'apply-error';
41
+ export type SpreadCorrectionStall = 'no-free-funds' | 'unfunded' | 'no-candidates' | 'cold-book' | 'unmatched-orders' | 'readiness-gate' | 'batch-not-executed' | 'apply-error'
42
+ /**
43
+ * Every tightening slot on the corrected side is at/through the last fill
44
+ * (SELL at/below it, BUY at/above it), so placement cannot repair the side:
45
+ * the bind is the grid WINDOW (a sell slot below the last sale means the
46
+ * boundary/crawl is behind the fill), not a missing candidate. Escalates on
47
+ * the short geometry window instead of the structural one.
48
+ */
49
+ | 'last-fill-blocked';
42
50
  /**
43
51
  * Dict with unknown values. The canonical replacement for
44
52
  * `Record<string, any>`; callers must narrow a value before using it.
@@ -223,6 +231,12 @@ export interface BotLike {
223
231
  _outOfSpreadSince: number;
224
232
  _outOfSpreadStaleWarned: boolean;
225
233
  _outOfSpreadTransientCount: number;
234
+ /**
235
+ * Timestamp when the spread first read within tolerance. Cleared on any
236
+ * out-of-tolerance cycle. A single good reading no longer clears the
237
+ * persistence clock — it must hold for SPREAD_STALE_IN_TOLERANCE_RESET_MS.
238
+ */
239
+ _outOfSpreadToleranceSince: number;
226
240
  _strandedHoldSince: Map<string, number>;
227
241
  _recoverySyncInFlight: number;
228
242
  _batchInFlight: number;
@@ -235,7 +249,14 @@ export interface BotLike {
235
249
  _marketAdapterWatchdogInFlight: boolean;
236
250
  _blockchainFetchInFlight: number;
237
251
  _blockchainFetchIntervalMin: number;
238
- _spreadFundsExhausted: boolean;
252
+ /**
253
+ * A spread-correction stall was mirrored this cycle. ANY cause arms the
254
+ * targeted chain refresh (a missed fill can hide the tightening slot, a stale
255
+ * hold can zero the funds), so the flag is cause-agnostic — the cause itself
256
+ * is carried in `_spreadCorrectionStall`. Formerly `_spreadFundsExhausted`,
257
+ * which mislabelled geometry stalls as fund stalls.
258
+ */
259
+ _spreadStallArmed: boolean;
239
260
  _spreadCorrectionStall: SpreadCorrectionStall | null;
240
261
  _skipEmptyReadConfirmDelay: boolean;
241
262
  _testPollIntervalMs?: number;
@@ -950,6 +971,18 @@ export interface CreditRuntimeLike {
950
971
  }
951
972
  export interface OrderManagerLike {
952
973
  _consecutiveBoundaryHolds?: number;
974
+ /**
975
+ * Set by the spread-correction planner when the corrected side's rail reserves
976
+ * more than the chain free balance (virtual > free). Cleared when a correction
977
+ * becomes fundable again. The out-of-spread watchdog escalates on its short
978
+ * fund window when this is fresh.
979
+ */
980
+ _spreadRailOversubscribed?: {
981
+ side: string;
982
+ virtual: number;
983
+ free: number;
984
+ at: number;
985
+ } | null;
953
986
  _boundaryShiftBudgetBase?: number;
954
987
  _lastBoundaryHoldInfo?: unknown;
955
988
  _lastHeldPlanSignature?: {