dexbot 1.6.13 → 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 (114) hide show
  1. package/CHANGELOG.md +66 -4
  2. package/README.md +2 -2
  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/AI_BOT_LIBRARY_API.md +1 -1
  7. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  8. package/claw/modules/claw_catalog.ts +8 -4
  9. package/claw/modules/dexbot_profiles.ts +59 -15
  10. package/claw/modules/types.ts +2 -1
  11. package/claw/package.json +1 -1
  12. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  13. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  14. package/claw/skills/margin-trading/SKILL.md +1 -1
  15. package/claw/skills/margin-trading/references/position-management.md +1 -1
  16. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +105 -31
  17. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +36 -2
  18. package/dist/dexbot.js +23 -3
  19. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
  20. package/dist/modules/account_bots.d.ts +10 -6
  21. package/dist/modules/account_bots.js +13 -10
  22. package/dist/modules/account_orders.d.ts +36 -4
  23. package/dist/modules/account_orders.js +76 -5
  24. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  25. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  26. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  27. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  28. package/dist/modules/bitshares-native/subscriptions.js +1 -1
  29. package/dist/modules/bot_defaults.d.ts +29 -4
  30. package/dist/modules/bot_defaults.js +65 -10
  31. package/dist/modules/bot_settings.d.ts +4 -0
  32. package/dist/modules/bot_settings.js +58 -21
  33. package/dist/modules/config.js +6 -1
  34. package/dist/modules/constants.d.ts +13 -5
  35. package/dist/modules/constants.js +36 -5
  36. package/dist/modules/credit_runtime.d.ts +35 -5
  37. package/dist/modules/credit_runtime.js +219 -38
  38. package/dist/modules/dexbot_class.d.ts +23 -0
  39. package/dist/modules/dexbot_class.js +60 -17
  40. package/dist/modules/dexbot_cow_runtime.d.ts +62 -174
  41. package/dist/modules/dexbot_cow_runtime.js +350 -64
  42. package/dist/modules/dexbot_credential_client.d.ts +1 -16
  43. package/dist/modules/dexbot_credential_client.js +1 -1
  44. package/dist/modules/dexbot_fill_runtime.d.ts +2 -2
  45. package/dist/modules/dexbot_fill_runtime.js +16 -8
  46. package/dist/modules/dexbot_maintenance_runtime.d.ts +24 -81
  47. package/dist/modules/dexbot_maintenance_runtime.js +104 -70
  48. package/dist/modules/dexbot_startup_runtime.js +15 -2
  49. package/dist/modules/dexbot_state_recovery.js +17 -1
  50. package/dist/modules/key_store.d.ts +0 -5
  51. package/dist/modules/key_store.js +1 -1
  52. package/dist/modules/order/accounting.js +11 -11
  53. package/dist/modules/order/export.js +4 -4
  54. package/dist/modules/order/format.d.ts +15 -1
  55. package/dist/modules/order/format.js +19 -1
  56. package/dist/modules/order/genesis_policy.d.ts +1 -1
  57. package/dist/modules/order/genesis_policy.js +1 -1
  58. package/dist/modules/order/grid.d.ts +141 -12
  59. package/dist/modules/order/grid.js +666 -92
  60. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  61. package/dist/modules/order/grid_reconcile.js +9 -8
  62. package/dist/modules/order/grid_reconcile_internal.js +61 -58
  63. package/dist/modules/order/index.d.ts +37 -9
  64. package/dist/modules/order/logger.js +2 -2
  65. package/dist/modules/order/manager.d.ts +10 -2
  66. package/dist/modules/order/manager.js +56 -31
  67. package/dist/modules/order/strategy.d.ts +2 -2
  68. package/dist/modules/order/strategy.js +51 -21
  69. package/dist/modules/order/sync_engine.js +22 -9
  70. package/dist/modules/order/utils/math.d.ts +101 -29
  71. package/dist/modules/order/utils/math.js +215 -84
  72. package/dist/modules/order/utils/order.d.ts +58 -58
  73. package/dist/modules/order/utils/order.js +135 -106
  74. package/dist/modules/order/utils/system.d.ts +193 -6
  75. package/dist/modules/order/utils/system.js +394 -31
  76. package/dist/modules/order/utils/validate.d.ts +1 -1
  77. package/dist/modules/order/utils/validate.js +71 -59
  78. package/dist/modules/runtime_settings.d.ts +1 -1
  79. package/dist/modules/runtime_settings.js +3 -3
  80. package/dist/modules/types.d.ts +55 -4
  81. package/dist/scripts/analyze-credit.js +44 -27
  82. package/dist/scripts/analyze-orders.d.ts +1 -1
  83. package/dist/scripts/analyze-orders.js +4 -4
  84. package/dist/scripts/diagnose-pool-history.js +35 -30
  85. package/dist/scripts/divergence-calc.js +6 -6
  86. package/dist/scripts/pnl.js +1 -1
  87. package/dist/scripts/rich_list.d.ts +18 -0
  88. package/dist/scripts/rich_list.js +461 -0
  89. package/dist/scripts/run-tests.js +80 -4
  90. package/dist/scripts/validate_bots.d.ts +1 -1
  91. package/dist/scripts/validate_bots.js +3 -3
  92. package/dist/unlock.d.ts +2 -1
  93. package/dist/unlock.js +11 -5
  94. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -2
  95. package/docs/COW_INVARIANTS.md +12 -6
  96. package/docs/DEXBOT_COMPARISON.md +7 -7
  97. package/docs/EVOLUTION.md +10 -8
  98. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  99. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  100. package/docs/GRID_RECALCULATION.md +4 -1
  101. package/docs/GRID_RECONCILE.md +4 -4
  102. package/docs/LIFECYCLE.md +11 -11
  103. package/docs/LOGGING.md +30 -1
  104. package/docs/MPA_CREDIT_USAGE.md +11 -6
  105. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +170 -12
  106. package/docs/README.md +3 -3
  107. package/docs/WORKFLOW.md +1 -0
  108. package/docs/architecture.md +62 -8
  109. package/docs/developer_guide.md +12 -3
  110. package/market_adapter/README.md +4 -4
  111. package/modules/README.md +1 -1
  112. package/package.json +2 -1
  113. package/scripts/README.md +59 -32
  114. package/tests/README.md +12 -3
@@ -14,6 +14,7 @@ import * as chainOrders from './chain_orders.js';
14
14
  import * as grid from './order/grid.js';
15
15
  import { ORDER_STATES, ORDER_TYPES, TIMING, BTS_PRECISION, NATIVE_CLIENT } from './constants.js';
16
16
  import { BOT_LIVE_CONFIG_KEYS } from './runtime_settings.js';
17
+ import { migrateLegacyOrderKeys } from './bot_defaults.js';
17
18
  import { acquireIfNotHeld } from './order/async_lock.js';
18
19
  const { readOpenOrdersGuarded } = chainOrders;
19
20
  import { PATHS } from './paths.js';
@@ -59,15 +60,15 @@ const updateDynamicGridSnapshotSync = lazyShim('../market_adapter/utils/dynamic_
59
60
  // would be circular; at call time both modules are fully loaded.
60
61
  const scheduleFillConsumerRestartFn = lazyShim('./dexbot_fill_runtime', 'scheduleFillConsumerRestart');
61
62
  const reconcileGridOrders = lazyShim('./order/grid_reconcile', 'reconcileGridOrders');
62
- const resolveReserveCount = lazyShim('./order/utils/order', 'resolveReserveCount');
63
- const reserveEdgeIdSet = lazyShim('./order/utils/order', 'reserveEdgeIdSet');
63
+ const resolveEdgeCount = lazyShim('./order/utils/order', 'resolveEdgeCount');
64
+ const edgeOrderIdSet = lazyShim('./order/utils/order', 'edgeOrderIdSet');
64
65
  const liveWindowIdSet = lazyShim('./order/utils/order', 'liveWindowIdSet');
65
- const resolveLiveReserveEdgeAnchorPrice = lazyShim('./order/utils/order', 'resolveLiveReserveEdgeAnchorPrice');
66
+ const resolveLiveEdgeAnchorPrice = lazyShim('./order/utils/order', 'resolveLiveEdgeAnchorPrice');
66
67
  const formatUnmatchedChainOrder = lazyShim('./order/utils/order', 'formatUnmatchedChainOrder');
67
68
  const isNonBlockingUnmatchedOrder = lazyShim('./order/utils/order', 'isNonBlockingUnmatchedOrder');
68
69
  const isStrandedHoldOrder = lazyShim('./order/utils/order', 'isStrandedHoldOrder');
69
70
  const getSideBudget = lazyShim('./order/utils/order', 'getSideBudget');
70
- function getActiveOrdersTotal(config) { return require('./order/utils/order').getActiveOrdersTotal(config); }
71
+ function getCoreOrdersTotal(config) { return require('./order/utils/order').getCoreOrdersTotal(config); }
71
72
  const correctAllPriceMismatches = lazyShim('./order/utils/order', 'correctAllPriceMismatches');
72
73
  const isOrderOnChain = lazyShim('./order/utils/order', 'isOrderOnChain');
73
74
  const parseChainOrder = lazyShim('./order/utils/order', 'parseChainOrder');
@@ -207,7 +208,10 @@ function normalizeBotEntryForFingerprint(entry) {
207
208
  continue;
208
209
  out[key] = e[key];
209
210
  }
210
- return out;
211
+ // Canonicalize legacy order-count keys so the fingerprint and the merged
212
+ // entry agree with the allowlist (`coreOrders`/`edgeOrders`) even when the
213
+ // on-disk bots.json still carries `activeOrders`/`reserveOrders`.
214
+ return migrateLegacyOrderKeys(out);
211
215
  }
212
216
  /**
213
217
  * Build the full-entry fingerprint for one bot (stable across key order and
@@ -253,7 +257,7 @@ function mergeBotConfigKeysIntoRuntime(bot, entry, keys) {
253
257
  const applied = [];
254
258
  if (!bot?.config || !entry || typeof entry !== 'object')
255
259
  return applied;
256
- const e = entry;
260
+ const e = migrateLegacyOrderKeys({ ...entry });
257
261
  for (const key of keys) {
258
262
  // A deleted key applies as null (mirrors the former ?? null diff
259
263
  // semantics) so the running config can never keep a stale value.
@@ -284,7 +288,7 @@ function mergeBotConfigKeysIntoRuntime(bot, entry, keys) {
284
288
  function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabel) {
285
289
  const oldKey = bot.config.botKey;
286
290
  const oldIndex = bot.config.botIndex;
287
- const u = updatedBot;
291
+ const u = migrateLegacyOrderKeys({ ...updatedBot });
288
292
  // Preserve runtime-only properties set by the constructor
289
293
  // (timing, gridLimits, feeParams, etc.) that are not present
290
294
  // in the raw profile from bots.json.
@@ -546,50 +550,50 @@ function countLiveGridOrders(manager, type) {
546
550
  const active = manager.getOrdersByTypeAndState?.(type, ORDER_STATES.ACTIVE) || [];
547
551
  const partial = manager.getOrdersByTypeAndState?.(type, ORDER_STATES.PARTIAL) || [];
548
552
  // Slot-N gated: fork-kept shelf/manual orders (non-slot-N ids, e.g.
549
- // deep-*) sit outside window accounting — same gate as reserve
553
+ // deep-*) sit outside window accounting — same gate as edge
550
554
  // classification and startup cancel candidates (issue #27 follow-up).
551
- // Without this, a live shelf inflates the live window+reserves count and
552
- // masks a real window/reserve shortfall, so targeted sync never fires.
555
+ // Without this, a live shelf inflates the live window+edges count and
556
+ // masks a real window/edge shortfall, so targeted sync never fires.
553
557
  // No-op on grids that only mint slot-N ids.
554
558
  return active.concat(partial).filter((o) => o?.orderId && parseSlotIndex(o?.id) !== null).length;
555
559
  }
556
- function getTargetActiveOrders(config, side) {
557
- const configured = Number(config?.activeOrders?.[side]);
558
- // Reserve ladder rests live on-chain: countLiveGridOrders sees window +
559
- // edge orders, so the shortfall target must include reserves too —
560
- // otherwise live reserves mask window shortfalls and a filled/cancelled
561
- // reserve order never triggers targeted reconciliation.
562
- const reserves = resolveReserveCount(config, side);
563
- return Math.max(0, Number.isFinite(configured) ? configured : 1) + reserves;
560
+ function getTargetCoreOrders(config, side) {
561
+ const configured = Number(config?.coreOrders?.[side]);
562
+ // Edge ladder rests live on-chain: countLiveGridOrders sees window +
563
+ // edge orders, so the shortfall target must include edge orders too —
564
+ // otherwise live edge orders mask window shortfalls and a filled/cancelled
565
+ // edge order never triggers targeted reconciliation.
566
+ const edgeCount = resolveEdgeCount(config, side);
567
+ return Math.max(0, Number.isFinite(configured) ? configured : 1) + edgeCount;
564
568
  }
565
569
  /**
566
- * Count live on-chain reserve orders for one side (issue #27 follow-up).
570
+ * Count live on-chain edge orders for one side (issue #27 follow-up).
567
571
  *
568
- * The window shortfall check above compares live window+reserves against
569
- * window+reserves, so a pre-existing window surplus masks a reserve deficit
570
- * (e.g. target 6+2=8 vs 12 live after reserveOrders 0→2: no shortfall, no
571
- * sync, zero reserve placements). Reserves get their own independent reason
572
- * below — the mirror of the masking case getTargetActiveOrders handles.
572
+ * The window shortfall check above compares live window+edges against
573
+ * window+edges, so a pre-existing window surplus masks an edge deficit
574
+ * (e.g. target 6+2=8 vs 12 live after edgeOrders 0→2: no shortfall, no
575
+ * sync, zero edge placements). Edge orders get their own independent reason
576
+ * below — the mirror of the masking case getTargetCoreOrders handles.
573
577
  *
574
- * Classification reuses the single source of truth (reserveEdgeIdSet +
575
- * resolveLiveReserveEdgeAnchorPrice, same anchor the placement pickers use)
578
+ * Classification reuses the single source of truth (edgeOrderIdSet +
579
+ * resolveLiveEdgeAnchorPrice, same anchor the placement pickers use)
576
580
  * over the full master grid, intersected with live ACTIVE/PARTIAL orderIds
577
581
  * (same live definition as countLiveGridOrders). The edge pick excludes the
578
582
  * window (liveWindowIdSet — the same exclusion every placement picker
579
583
  * applies): window + edge are additive in targets/fees/hold-back, but
580
584
  * without the exclusion a window that reaches the grid edge (keep-low
581
585
  * window = bottom slots = floor edge) makes the edge pick land on window
582
- * members and the count reads N/N with zero dedicated reserves, so the
586
+ * members and the count reads N/N with zero dedicated edge orders, so the
583
587
  * deficit never fires (issue #27 follow-up).
584
588
  * @param {unknown} manager - OrderManager
585
- * @param {unknown} config - Bot configuration (reserve count source)
589
+ * @param {unknown} config - Bot configuration (edge count source)
586
590
  * @param {unknown} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
587
- * @returns {number|null} Live reserve count, or null when unclassifiable
591
+ * @returns {number|null} Live edge count, or null when unclassifiable
588
592
  */
589
- function countLiveReserveOrders(manager, config, type) {
593
+ function countLiveEdgeOrders(manager, config, type) {
590
594
  try {
591
595
  const side = type === ORDER_TYPES.SELL ? 'sell' : 'buy';
592
- const required = resolveReserveCount(config, side);
596
+ const required = resolveEdgeCount(config, side);
593
597
  if (!(required > 0))
594
598
  return 0;
595
599
  if (!manager)
@@ -602,13 +606,13 @@ function countLiveReserveOrders(manager, config, type) {
602
606
  const allSlots = Array.from(manager.orders.values());
603
607
  if (allSlots.length === 0)
604
608
  return null;
605
- const anchor = resolveLiveReserveEdgeAnchorPrice(manager, side);
609
+ const anchor = resolveLiveEdgeAnchorPrice(manager, side);
606
610
  // Fail open on unknown window geometry (null): without a boundary the
607
- // pickers cannot place reserves either, so keep the previous
611
+ // pickers cannot place edge orders either, so keep the previous
608
612
  // (exclusion-free) classification instead of guessing.
609
613
  const windowIds = liveWindowIdSet(manager, type);
610
- const reserveIds = reserveEdgeIdSet(allSlots, config, type, anchor, windowIds);
611
- if (!reserveIds || reserveIds.size === 0)
614
+ const edgeIds = edgeOrderIdSet(allSlots, config, type, anchor, windowIds);
615
+ if (!edgeIds || edgeIds.size === 0)
612
616
  return 0;
613
617
  const liveIds = new Set();
614
618
  if (typeof manager.getOrdersByTypeAndState === 'function') {
@@ -626,7 +630,7 @@ function countLiveReserveOrders(manager, config, type) {
626
630
  }
627
631
  }
628
632
  let live = 0;
629
- for (const id of reserveIds) {
633
+ for (const id of edgeIds) {
630
634
  if (liveIds.has(String(id)))
631
635
  live++;
632
636
  }
@@ -644,7 +648,7 @@ function _hasBudgetForSide(manager, config, side) {
644
648
  const allocated = side === 'buy' ? (funds.allocatedBuy || 0) : (funds.allocatedSell || 0);
645
649
  if (allocated <= 0)
646
650
  return false;
647
- const totalTarget = getActiveOrdersTotal(config);
651
+ const totalTarget = getCoreOrdersTotal(config);
648
652
  const budget = getSideBudget(side, funds, config, totalTarget);
649
653
  return budget > 0;
650
654
  }
@@ -674,8 +678,8 @@ export function mirrorSpreadStall(bot, stall) {
674
678
  function getTargetedSyncReason(bot) {
675
679
  if (!bot.manager || bot.config?.dryRun)
676
680
  return null;
677
- const targetBuy = getTargetActiveOrders(bot.config, 'buy');
678
- const targetSell = getTargetActiveOrders(bot.config, 'sell');
681
+ const targetBuy = getTargetCoreOrders(bot.config, 'buy');
682
+ const targetSell = getTargetCoreOrders(bot.config, 'sell');
679
683
  const liveBuy = countLiveGridOrders(bot.manager, ORDER_TYPES.BUY);
680
684
  const liveSell = countLiveGridOrders(bot.manager, ORDER_TYPES.SELL);
681
685
  const shortfalls = [];
@@ -689,18 +693,18 @@ function getTargetedSyncReason(bot) {
689
693
  shortfalls.push(`sell ${liveSell}/${targetSell}`);
690
694
  }
691
695
  }
692
- // Reserve deficit is independent of window surplus: a bot carrying extra
693
- // rail/stranded orders can sit above target while its reserve edge is
694
- // empty (live-applied reserveOrders 0→N, filled/cancelled reserve).
696
+ // Edge deficit is independent of window surplus: a bot carrying extra
697
+ // rail/stranded orders can sit above target while its edge order is
698
+ // empty (live-applied edgeOrders 0→N, filled/cancelled edge order).
695
699
  // Without this, placement waits for fills or the 4h fetch (issue #27).
696
700
  for (const [type, side] of [[ORDER_TYPES.BUY, 'buy'], [ORDER_TYPES.SELL, 'sell']]) {
697
- const required = resolveReserveCount(bot.config, side);
701
+ const required = resolveEdgeCount(bot.config, side);
698
702
  if (!(required > 0))
699
703
  continue;
700
- const liveReserves = countLiveReserveOrders(bot.manager, bot.config, type);
701
- if (liveReserves !== null && liveReserves < required) {
704
+ const liveEdges = countLiveEdgeOrders(bot.manager, bot.config, type);
705
+ if (liveEdges !== null && liveEdges < required) {
702
706
  if (_hasBudgetForSide(bot.manager, bot.config, side)) {
703
- shortfalls.push(`${side} reserves ${liveReserves}/${required}`);
707
+ shortfalls.push(`${side} edges ${liveEdges}/${required}`);
704
708
  }
705
709
  }
706
710
  }
@@ -2497,7 +2501,7 @@ async function executeMaintenanceLogic(bot, context) {
2497
2501
  }
2498
2502
  // Persistence watchdog: a correction that keeps placing nothing
2499
2503
  // while the spread stays wide is a stale grid, not patience.
2500
- trackOutOfSpreadStaleness(bot, true, spreadPlaced);
2504
+ trackOutOfSpreadStaleness(bot, true, spreadPlaced, spreadResult?.transient === true);
2501
2505
  }
2502
2506
  }
2503
2507
  catch (err) {
@@ -2528,13 +2532,16 @@ async function executeMaintenanceLogic(bot, context) {
2528
2532
  * @param {unknown} bot
2529
2533
  * @param {boolean} spreadChecked - Whether the spread check ran this tick
2530
2534
  * @param {number} ordersPlaced - Correction orders placed this tick
2535
+ * @param {boolean} [transient=false] - True when the correction was refused for
2536
+ * a retryable reason (stale plan / duplicate CREATE / unclassified non-execution)
2531
2537
  * @returns {{staleMs: number, escalated: boolean}}
2532
2538
  */
2533
- export function trackOutOfSpreadStaleness(bot, spreadChecked, ordersPlaced) {
2539
+ export function trackOutOfSpreadStaleness(bot, spreadChecked, ordersPlaced, transient = false) {
2534
2540
  const outOfSpread = Number(bot?.manager?.outOfSpread) || 0;
2535
2541
  if (ordersPlaced > 0 || outOfSpread === 0) {
2536
2542
  bot._outOfSpreadSince = 0;
2537
2543
  bot._outOfSpreadStaleWarned = false;
2544
+ bot._outOfSpreadTransientCount = 0;
2538
2545
  return { staleMs: 0, escalated: false };
2539
2546
  }
2540
2547
  if (!spreadChecked) {
@@ -2542,6 +2549,29 @@ export function trackOutOfSpreadStaleness(bot, spreadChecked, ordersPlaced) {
2542
2549
  return { staleMs: since > 0 ? Date.now() - since : 0, escalated: false };
2543
2550
  }
2544
2551
  const now = Date.now();
2552
+ // Transient refusals (stale plan / duplicate CREATE / unclassified
2553
+ // non-execution) are retried by checkSpreadCondition's bounded re-plan, so
2554
+ // they must not immediately count toward the persistent-stale clock — a
2555
+ // single concurrent commit would otherwise force a structural re-center.
2556
+ // Count them and restart the clock while under the grace budget; past it,
2557
+ // fall through so a genuinely deadlocked transient still heals.
2558
+ if (transient) {
2559
+ const transientCount = (Number(bot._outOfSpreadTransientCount) || 0) + 1;
2560
+ bot._outOfSpreadTransientCount = transientCount;
2561
+ const grace = Number(TIMING?.SPREAD_STALE_TRANSIENT_GRACE) > 0
2562
+ ? Number(TIMING.SPREAD_STALE_TRANSIENT_GRACE)
2563
+ : 3;
2564
+ if (transientCount <= grace) {
2565
+ bot._outOfSpreadSince = now;
2566
+ bot._outOfSpreadStaleWarned = false;
2567
+ bot._log(`[SPREAD-STALE] Transient spread-correction refusal ${transientCount}/${grace} ` +
2568
+ `(outOfSpread=${outOfSpread}); retrying before any structural re-center`, 'warn');
2569
+ return { staleMs: 0, escalated: false };
2570
+ }
2571
+ }
2572
+ else {
2573
+ bot._outOfSpreadTransientCount = 0;
2574
+ }
2545
2575
  if (!Number(bot._outOfSpreadSince))
2546
2576
  bot._outOfSpreadSince = now;
2547
2577
  const staleMs = now - Number(bot._outOfSpreadSince);
@@ -2758,7 +2788,7 @@ async function checkBtsBalanceAndAcquire(bot) {
2758
2788
  return;
2759
2789
  if (!bot.manager || !bot.manager.btsBalance)
2760
2790
  return;
2761
- const totalTarget = getActiveOrdersTotal(bot.config);
2791
+ const totalTarget = getCoreOrdersTotal(bot.config);
2762
2792
  const btsReservationMultiplier = bot.config?.feeParams?.BTS_RESERVATION_MULTIPLIER;
2763
2793
  const minBtsVal = calculateOrderCreationFees(bot.config.assetA, bot.config.assetB, totalTarget, btsReservationMultiplier);
2764
2794
  if (minBtsVal <= 0)
@@ -3154,6 +3184,25 @@ function markGridActivity(bot, reason = 'activity') {
3154
3184
  bot._lastGridActivityAt = Date.now();
3155
3185
  bot.manager?.logger?.log?.(`[MAINT-IDLE] Activity observed: ${reason}`, 'debug');
3156
3186
  }
3187
+ /**
3188
+ * Manager-owned counters overlaid onto the bot's metrics snapshot. The
3189
+ * grid/strategy engines write these on the MANAGER because they have no bot
3190
+ * reference. Kept in one function so wiring a new engine-owned counter does not
3191
+ * mean copying the `manager ?? bot` fallback again.
3192
+ * @param {Object} bot - DEXBot instance
3193
+ * @returns {Object} The manager-owned counters, or {} when the manager has none
3194
+ */
3195
+ function managerOwnedCounters(bot) {
3196
+ const mgr = bot.manager?._metrics;
3197
+ if (!mgr)
3198
+ return {};
3199
+ return {
3200
+ boundaryDriftExceedsWindowCount: mgr.boundaryDriftExceedsWindowCount ?? bot._metrics.boundaryDriftExceedsWindowCount,
3201
+ spreadCorrectionRefusedCount: mgr.spreadCorrectionRefusedCount ?? bot._metrics.spreadCorrectionRefusedCount,
3202
+ spreadCorrectionRefusalCauses: mgr.spreadCorrectionRefusalCauses ?? bot._metrics.spreadCorrectionRefusalCauses,
3203
+ spreadCorrectionRetryCount: mgr.spreadCorrectionRetryCount ?? bot._metrics.spreadCorrectionRetryCount
3204
+ };
3205
+ }
3157
3206
  /**
3158
3207
  * Get current metrics for monitoring and debugging.
3159
3208
  * @param {import('./dexbot_class.js').DEXBot} bot
@@ -3171,6 +3220,11 @@ function getMetrics(bot) {
3171
3220
  const heldUnmatched = unmatched.filter((u) => isNonBlockingUnmatchedOrder(u));
3172
3221
  return {
3173
3222
  ...bot._metrics,
3223
+ // Counters written by the grid/strategy engines on the MANAGER's metrics
3224
+ // object (those engines have no bot reference). Overlay them here so
3225
+ // they are actually surfaced by getMetrics(). Single wiring point: add
3226
+ // a new engine-owned counter here, not as another inline fallback.
3227
+ ...managerOwnedCounters(bot),
3174
3228
  queueDepth: bot._incomingFillQueue.length,
3175
3229
  fillProcessingLockActive: bot.manager?._fillProcessingLock?.isLocked() || false,
3176
3230
  divergenceLockActive: bot.manager?._divergenceLock?.isLocked() || false,
@@ -3254,15 +3308,10 @@ async function syncOpenOrdersAndProcessFillsImpl(bot, tag) {
3254
3308
  return { syncResult: null, aborted: true, hasUnmatched: -1, openOrders: null };
3255
3309
  }
3256
3310
  }
3257
- export { loadBotsConfigSnapshot, isWrapperAdapterOwner, checkAndApplyBotConfigChanges, buildBotConfigFingerprint, refreshDynamicWeightDistribution, performGridResync, updateBotGridResetMetadata, handlePendingTriggerReset, setupTriggerFileDetection, performPeriodicGridChecks, isOpenOrdersSyncLoopEnabled, startOpenOrdersSyncLoop, stopOpenOrdersSyncLoop, setupBlockchainFetchInterval, stopBlockchainFetchInterval, setupBotsConfigPollInterval, stopBotsConfigPollInterval, executeMaintenanceLogic, getTargetedSyncReason, maybeRunTargetedDriftReconciliation, countLiveReserveOrders, cancelDustOrders, isOrderDoesNotExistError, runGridMaintenance, releaseMarketAdapterRuntime, syncMarketAdapterOnPeriodicConfigCheck, usesAmaGridPrice, runDustHealthCheck, setupDustHealthCheckInterval, requestGridReset, wireStructuralGridResyncRequest, getPipelineSignals, markGridActivity, getMetrics, syncOpenOrdersAndProcessFills, shouldDeferMaintenanceForBroadcast, checkGridLockHoldDuration };
3311
+ export { loadBotsConfigSnapshot, isWrapperAdapterOwner, checkAndApplyBotConfigChanges, buildBotConfigFingerprint, refreshDynamicWeightDistribution, performGridResync, updateBotGridResetMetadata, handlePendingTriggerReset, setupTriggerFileDetection, performPeriodicGridChecks, isOpenOrdersSyncLoopEnabled, startOpenOrdersSyncLoop, stopOpenOrdersSyncLoop, setupBlockchainFetchInterval, stopBlockchainFetchInterval, setupBotsConfigPollInterval, stopBotsConfigPollInterval, executeMaintenanceLogic, getTargetedSyncReason, maybeRunTargetedDriftReconciliation, countLiveEdgeOrders, cancelDustOrders, isOrderDoesNotExistError, runGridMaintenance, releaseMarketAdapterRuntime, syncMarketAdapterOnPeriodicConfigCheck, usesAmaGridPrice, runDustHealthCheck, setupDustHealthCheckInterval, requestGridReset, wireStructuralGridResyncRequest, getPipelineSignals, markGridActivity, getMetrics, syncOpenOrdersAndProcessFills, shouldDeferMaintenanceForBroadcast, checkGridLockHoldDuration };
3258
3312
  export default {
3259
- loadBotsConfigSnapshot,
3260
- isWrapperAdapterOwner,
3261
- checkAndApplyBotConfigChanges,
3262
- buildBotConfigFingerprint,
3263
3313
  refreshDynamicWeightDistribution,
3264
3314
  performGridResync,
3265
- updateBotGridResetMetadata,
3266
3315
  handlePendingTriggerReset,
3267
3316
  setupTriggerFileDetection,
3268
3317
  performPeriodicGridChecks,
@@ -3274,22 +3323,9 @@ export default {
3274
3323
  setupBotsConfigPollInterval,
3275
3324
  stopBotsConfigPollInterval,
3276
3325
  executeMaintenanceLogic,
3277
- getTargetedSyncReason,
3278
- mirrorSpreadStall,
3279
- countLiveReserveOrders,
3280
- maybeRunTargetedDriftReconciliation,
3281
3326
  cancelDustOrders,
3282
- isOrderDoesNotExistError,
3283
3327
  runGridMaintenance,
3284
- trackOutOfSpreadStaleness,
3285
- stopMarketAdapterPm2,
3286
3328
  releaseMarketAdapterRuntime,
3287
- syncMarketAdapterOnPeriodicConfigCheck,
3288
- findSnapshotBotForRuntimeConfig,
3289
- runtimeConfigNeedsMarketAdapter,
3290
- usesAmaGridPrice,
3291
- checkBtsBalanceAndAcquire,
3292
- acquireBts,
3293
3329
  runDustHealthCheck,
3294
3330
  setupDustHealthCheckInterval,
3295
3331
  requestGridReset,
@@ -3298,8 +3334,6 @@ export default {
3298
3334
  markGridActivity,
3299
3335
  getMetrics,
3300
3336
  syncOpenOrdersAndProcessFills,
3301
- shouldDeferMaintenanceForBroadcast,
3302
- checkGridLockHoldDuration,
3303
3337
  _internalDeferredHold: { logDeferredHoldSummary, describeDeferredHolds, considerDeferredHoldEscalation },
3304
3338
  };
3305
3339
  //# sourceMappingURL=dexbot_maintenance_runtime.js.map
@@ -4,6 +4,7 @@ import { path } from './path_api.js';
4
4
  import * as chainOrders from './chain_orders.js';
5
5
  import { readOpenOrdersGuarded } from './chain_orders.js';
6
6
  import { ORDER_STATES, TIMING } from './constants.js';
7
+ import { Config } from './config.js';
7
8
  import { PATHS } from './paths.js';
8
9
  import { getStorage } from './storage/index.js';
9
10
  import { normalizeBotEntry } from './bot_settings.js';
@@ -13,6 +14,7 @@ import { BitShares, onReconnect as registerReconnectHook } from './bitshares_cli
13
14
  import orderModule from './order/index.js';
14
15
  import { getErrorMessage } from './utils/errors.js';
15
16
  import { processSweepOrphanFill } from './dexbot_fill_runtime.js';
17
+ import { restoreLastMarketFill } from './order/utils/system.js';
16
18
  import { ON_MISSING_GENESIS, recordMissingGenesisFault, resolvePersistedGenesis } from './order/genesis_policy.js';
17
19
  const { OrderManager, grid: Grid } = orderModule;
18
20
  const initializeFeeCache = lazyShim('./order/utils/system', 'initializeFeeCache');
@@ -209,6 +211,17 @@ async function startPostBootstrapSubsystems(bot) {
209
211
  async function finishStartupSequence(bot, startupState) {
210
212
  let { persistedGrid, persistedBtsFeesOwed, persistedBoundaryIdx, persistedBtsBalance, persistedRecentFillKeys, persistedGenesis, persistedGapEvacStreaks, } = startupState;
211
213
  try {
214
+ // Bot-scoped last-market-fill reference: restore BEFORE any chain
215
+ // touching/placement work so spread correction (including the
216
+ // post-reset path below) always has the last real trade price it must
217
+ // not cross. Independent of the boundary/genesis restore, so a
218
+ // regenerated grid still gets the anchor the genesis-bound pivot lost.
219
+ try {
220
+ restoreLastMarketFill(bot.manager, bot.manager?.accountOrders?.loadLastMarketFill?.() ?? null);
221
+ }
222
+ catch (marketRefErr) {
223
+ bot._warn(`[SPREAD-CORRECTION] Last-market-fill restore failed (${getErrorMessage(marketRefErr)}); spread correction runs without a market anchor`);
224
+ }
212
225
  if (typeof bot._fillsUnsubscribe === 'function') {
213
226
  await bot._fillsUnsubscribe().catch(() => { });
214
227
  }
@@ -412,7 +425,7 @@ async function finishStartupSequence(bot, startupState) {
412
425
  else {
413
426
  bot._log('Open-orders sync loop disabled by configuration');
414
427
  }
415
- bot._log(`DEXBot started. OrderManager running (dryRun=${!!bot.config.dryRun})`);
428
+ bot._log(`DEXBot v${Config.VERSION} started. OrderManager running (dryRun=${!!bot.config.dryRun})`);
416
429
  return;
417
430
  }
418
431
  await bot.manager._fundLock.acquire(async () => {
@@ -719,7 +732,7 @@ async function finishStartupSequence(bot, startupState) {
719
732
  else {
720
733
  bot._log('Open-orders sync loop disabled by configuration');
721
734
  }
722
- bot._log(`DEXBot started. OrderManager running (dryRun=${!!bot.config.dryRun})`);
735
+ bot._log(`DEXBot v${Config.VERSION} started. OrderManager running (dryRun=${!!bot.config.dryRun})`);
723
736
  }
724
737
  catch (err) {
725
738
  bot._warn(`Error during grid initialization: ${getErrorMessage(err)}`);
@@ -302,7 +302,7 @@ async function recoverFromPersistedGrid(bot) {
302
302
  // SPREAD-GUARD mid-evacuation state (live orders crawled into the band,
303
303
  // GAP-EVAC streak already tracking it; the snapshot may also be stale
304
304
  // by one crawl). Rejecting it here forces a structural resync that
305
- // wipes the in-progress evacuation — the H-BTS 2026-09-13 sabotage
305
+ // wipes the in-progress evacuation — the <bot> 2026-09-13 sabotage
306
306
  // loop. Warn + load instead; GAP-EVAC/sync sweeps own the cleanup.
307
307
  // All other reasons stay rebuild-worthy.
308
308
  let tolerateTransientStranding = false;
@@ -591,6 +591,22 @@ async function rejectCorruptedGridSnapshot(bot, context) {
591
591
  `drift sell=${Number(driftCheck.driftSell ?? 0).toFixed(2)} buy=${Number(driftCheck.driftBuy ?? 0).toFixed(2)}. ` +
592
592
  `Deleting corrupted snapshot.`);
593
593
  if (bot.accountOrders && typeof bot.accountOrders.clearGrid === 'function') {
594
+ // Keep a timestamped copy before the destructive clear. Drift is not
595
+ // always corruption (genuine unadopted orphans, re-anchoring), so the
596
+ // pre-reject grid/boundary/pivot/crawls are the only forensics and the
597
+ // only path to manual recovery. AccountOrders owns the path/storage
598
+ // knowledge. Best-effort: the clear proceeds either way.
599
+ try {
600
+ const backupPath = typeof bot.accountOrders.backupSnapshot === 'function'
601
+ ? await bot.accountOrders.backupSnapshot('rejected-drift')
602
+ : null;
603
+ if (backupPath) {
604
+ bot._warn(`${tag} Kept pre-reject snapshot copy at ${backupPath}`);
605
+ }
606
+ }
607
+ catch (backupErr) {
608
+ bot._warn(`${tag} Failed to keep pre-reject snapshot copy: ${getErrorMessage(backupErr)}`);
609
+ }
594
610
  try {
595
611
  await bot.accountOrders.clearGrid();
596
612
  bot._warn(`${tag} Corrupted grid snapshot deleted.`);
@@ -13,11 +13,6 @@ export interface KeyStore {
13
13
  isDaemonSigningKey(key: unknown): boolean;
14
14
  executeOperations(accountName: string, operations: ChainOrderOperation[], signingKey: unknown, extraOptions?: Record<string, unknown>): Promise<SigningResult>;
15
15
  }
16
- export declare class DaemonKeyStore implements KeyStore {
17
- resolveSigningKey(accountName: string, vaultSecret?: unknown, chainClient?: unknown): Promise<unknown>;
18
- isDaemonSigningKey(key: unknown): boolean;
19
- executeOperations(accountName: string, operations: ChainOrderOperation[], signingKey: unknown, extraOptions?: Record<string, unknown>): Promise<SigningResult>;
20
- }
21
16
  export declare function setKeyStore(impl: KeyStore | null): void;
22
17
  export declare function resetKeyStore(): void;
23
18
  export declare function getKeyStore(): KeyStore;
@@ -69,7 +69,7 @@ async function broadcastViaChainOrders(accountName, operations, signingKey) {
69
69
  await broadcastTxWithClassification(tx, accountName, operations);
70
70
  return { success: true };
71
71
  }
72
- export class DaemonKeyStore {
72
+ class DaemonKeyStore {
73
73
  async resolveSigningKey(accountName, vaultSecret, chainClient) {
74
74
  if (vaultSecret) {
75
75
  return chainKeys.resolvePrivateKey(accountName, vaultSecret, chainClient);
@@ -74,7 +74,7 @@ import { createRequire } from 'node:module';
74
74
  const require = createRequire(import.meta.url);
75
75
  import { ORDER_TYPES, ORDER_STATES, PIPELINE_TIMING, TIMING, FEE_PARAMETERS, GRID_LIMITS } from '../constants.js';
76
76
  import { resolveAccountRef } from './utils/system.js';
77
- import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, resolveReserveCount } from './utils/order.js';
77
+ import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, resolveEdgeCount } from './utils/order.js';
78
78
  import { isSlotInRail, floatToBlockchainInt } from './utils/math.js';
79
79
  import * as Format from './format.js';
80
80
  import * as fundRegistry from '../fund_registry.js';
@@ -429,19 +429,19 @@ class Accountant {
429
429
  mgr.funds.total.grid = { buy: gridBuy + virtualBuy, sell: gridSell + virtualSell };
430
430
  // STEP 6: Calculate available funds (what we can spend right now)
431
431
  // Uses utils::calculateAvailableFundsValue which deducts committe amounts
432
- // Reserve ladder rides on the side counts for fee reservation: reserves
432
+ // Edge ladder rides on the side counts for fee reservation: edge orders
433
433
  // rest live on-chain and pay creation fees like window orders.
434
- const reserveBuy = resolveReserveCount(mgr.config, 'buy');
435
- const reserveSell = resolveReserveCount(mgr.config, 'sell');
436
- const feeActiveOrders = mgr.config.activeOrders && typeof mgr.config.activeOrders === 'object'
434
+ const edgeBuy = resolveEdgeCount(mgr.config, 'buy');
435
+ const edgeSell = resolveEdgeCount(mgr.config, 'sell');
436
+ const feeCoreOrders = mgr.config.coreOrders && typeof mgr.config.coreOrders === 'object'
437
437
  ? {
438
- ...mgr.config.activeOrders,
439
- buy: Math.max(0, Number(mgr.config.activeOrders.buy) || 0) + reserveBuy,
440
- sell: Math.max(0, Number(mgr.config.activeOrders.sell) || 0) + reserveSell,
438
+ ...mgr.config.coreOrders,
439
+ buy: Math.max(0, Number(mgr.config.coreOrders.buy) || 0) + edgeBuy,
440
+ sell: Math.max(0, Number(mgr.config.coreOrders.sell) || 0) + edgeSell,
441
441
  }
442
- : mgr.config.activeOrders;
443
- mgr.funds.available.buy = calculateAvailableFundsValue('buy', mgr.accountTotals, mgr.funds, mgr.config.assetA, mgr.config.assetB, feeActiveOrders, mgr.config.min_BTS_value, mgr.config?.feeParams ?? null);
444
- mgr.funds.available.sell = calculateAvailableFundsValue('sell', mgr.accountTotals, mgr.funds, mgr.config.assetA, mgr.config.assetB, feeActiveOrders, mgr.config.min_BTS_value, mgr.config?.feeParams ?? null);
442
+ : mgr.config.coreOrders;
443
+ mgr.funds.available.buy = calculateAvailableFundsValue('buy', mgr.accountTotals, mgr.funds, mgr.config.assetA, mgr.config.assetB, feeCoreOrders, mgr.config.min_BTS_value, mgr.config?.feeParams ?? null);
444
+ mgr.funds.available.sell = calculateAvailableFundsValue('sell', mgr.accountTotals, mgr.funds, mgr.config.assetA, mgr.config.assetB, feeCoreOrders, mgr.config.min_BTS_value, mgr.config?.feeParams ?? null);
445
445
  // Ensure percentage-based allocations are applied to the newly calculated totals
446
446
  if (typeof mgr.applyBotFundsAllocation === 'function') {
447
447
  mgr.applyBotFundsAllocation();
@@ -477,8 +477,8 @@ async function writeSettingsJSON(botConfig, botName, outputPath) {
477
477
  max_price: botConfig.maxPrice || DEFAULT_CONFIG.maxPrice,
478
478
  increment_percent: botConfig.incrementPercent || DEFAULT_CONFIG.incrementPercent,
479
479
  target_spread_percent: botConfig.targetSpreadPercent || DEFAULT_CONFIG.targetSpreadPercent,
480
- active_orders: botConfig.activeOrders || DEFAULT_CONFIG.activeOrders,
481
- reserve_orders: botConfig.reserveOrders ?? DEFAULT_CONFIG.reserveOrders,
480
+ core_orders: botConfig.coreOrders || DEFAULT_CONFIG.coreOrders,
481
+ edge_orders: botConfig.edgeOrders ?? DEFAULT_CONFIG.edgeOrders,
482
482
  bot_funds: botConfig.botFunds || DEFAULT_CONFIG.botFunds,
483
483
  weight_distribution: botConfig.weightDistribution || DEFAULT_CONFIG.weightDistribution,
484
484
  dry_run: botConfig.dryRun || false,
@@ -516,8 +516,8 @@ async function exportBotTrades(botKey, botConfig, outputDir = './exports') {
516
516
  try {
517
517
  const logFiles = storage.readdir(logsDir);
518
518
  const want = String(botKey).toLowerCase();
519
- // Case-insensitive: log files use the display name (XRP-BTS.log)
520
- // while bot keys are lowercase (xrp-bts). Prefer the exact
519
+ // Case-insensitive: log files use the display name (<bot>.log)
520
+ // while bot keys are lowercase (e.g. <botKey>). Prefer the exact
521
521
  // "<key>.log" hit, fall back to any non-error log containing the key.
522
522
  const exactLog = logFiles.find((f) => f.toLowerCase() === `${want}.log`);
523
523
  const matchingLog = exactLog || logFiles.find((f) => f.toLowerCase().includes(want) && f.endsWith('.log') && !f.toLowerCase().includes('error'));
@@ -165,6 +165,20 @@ declare function toFiniteNumber(value: unknown, defaultValue: number | null): nu
165
165
  * non-numeric strings all yield `null`.
166
166
  */
167
167
  declare function positiveOrNull(value: unknown): number | null;
168
+ /**
169
+ * Convert a value to a finite number but treat an explicitly absent value
170
+ * (`null`/`undefined`/`''`) as unknown (`NaN`) instead of `0`.
171
+ *
172
+ * `Number(null) === 0` and `Number('') === 0` are finite, so a plain `Number()`
173
+ * coercion reads "no value" as the valid value 0 — the trap that made an
174
+ * unknown boundary read as slot 0, an unknown gap width collapse the band, and
175
+ * an unknown fill timestamp read as epoch. Use this for any geometry/index/
176
+ * count field where 0 is legitimate and absence must stay detectable.
177
+ *
178
+ * A genuine `0` (number, `'0'`, `false`) still converts to `0`. Pair with
179
+ * `Number.isFinite` at the call site where absent must fail closed.
180
+ */
181
+ declare function toKnownNumber(value: unknown): number;
168
182
  /**
169
183
  * Safely format a numeric value with specified decimals and fallback.
170
184
  *
@@ -174,5 +188,5 @@ declare function positiveOrNull(value: unknown): number | null;
174
188
  * @returns {string} Formatted value or fallback string
175
189
  */
176
190
  declare function safeFormat(value: unknown, decimals: number, fallback?: string): string;
177
- export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, positiveOrNull, safeFormat };
191
+ export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, toKnownNumber, positiveOrNull, safeFormat };
178
192
  //# sourceMappingURL=format.d.ts.map
@@ -258,6 +258,24 @@ function positiveOrNull(value) {
258
258
  const num = Number(value);
259
259
  return Number.isFinite(num) && num > 0 ? num : null;
260
260
  }
261
+ /**
262
+ * Convert a value to a finite number but treat an explicitly absent value
263
+ * (`null`/`undefined`/`''`) as unknown (`NaN`) instead of `0`.
264
+ *
265
+ * `Number(null) === 0` and `Number('') === 0` are finite, so a plain `Number()`
266
+ * coercion reads "no value" as the valid value 0 — the trap that made an
267
+ * unknown boundary read as slot 0, an unknown gap width collapse the band, and
268
+ * an unknown fill timestamp read as epoch. Use this for any geometry/index/
269
+ * count field where 0 is legitimate and absence must stay detectable.
270
+ *
271
+ * A genuine `0` (number, `'0'`, `false`) still converts to `0`. Pair with
272
+ * `Number.isFinite` at the call site where absent must fail closed.
273
+ */
274
+ function toKnownNumber(value) {
275
+ if (value === null || value === undefined || value === '')
276
+ return NaN;
277
+ return Number(value);
278
+ }
261
279
  /**
262
280
  * Safely format a numeric value with specified decimals and fallback.
263
281
  *
@@ -280,5 +298,5 @@ function safeFormat(value, decimals, fallback = 'N/A') {
280
298
  // ===============================================================================
281
299
  // EXPORTS
282
300
  // ===============================================================================
283
- export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, positiveOrNull, safeFormat };
301
+ export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, toKnownNumber, positiveOrNull, safeFormat };
284
302
  //# sourceMappingURL=format.js.map
@@ -6,7 +6,7 @@
6
6
  * missing is therefore not a degraded grid -- it is an undefined one: every
7
7
  * consumer that reads `priceForSlot(idx, genesis)` has no authority for a
8
8
  * slot's price (nearest-slot adoption, the materialize descriptor-price
9
- * fallback, reserve-edge anchoring, the `isSlotInRail` fail-open), and that is
9
+ * fallback, edge anchoring, the `isSlotInRail` fail-open), and that is
10
10
  * precisely the state on which an off-grid price became grid evidence and got
11
11
  * re-emitted. The tolerance matcher that used to cover it has been removed:
12
12
  * E2 refuses to sync such a grid and asks for the resync that re-derives the
@@ -6,7 +6,7 @@
6
6
  * missing is therefore not a degraded grid -- it is an undefined one: every
7
7
  * consumer that reads `priceForSlot(idx, genesis)` has no authority for a
8
8
  * slot's price (nearest-slot adoption, the materialize descriptor-price
9
- * fallback, reserve-edge anchoring, the `isSlotInRail` fail-open), and that is
9
+ * fallback, edge anchoring, the `isSlotInRail` fail-open), and that is
10
10
  * precisely the state on which an off-grid price became grid evidence and got
11
11
  * re-emitted. The tolerance matcher that used to cover it has been removed:
12
12
  * E2 refuses to sync such a grid and asks for the resync that re-derives the