dexbot 1.6.14 → 1.6.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/CHANGELOG.md +60 -4
  2. package/README.md +4 -4
  3. package/analysis/README.md +6 -6
  4. package/analysis/tradingview/README.md +2 -1
  5. package/claw/README.md +7 -7
  6. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
  7. package/claw/modules/chain_queries.ts +3 -3
  8. package/claw/package.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/dist/analysis/ama_fitting/fetch_lp_candles.js +8 -1
  12. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
  13. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
  14. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
  15. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
  16. package/dist/analysis/bot_key_utils.js +9 -7
  17. package/dist/analysis/chart_utils.d.ts +9 -2
  18. package/dist/analysis/chart_utils.js +51 -1
  19. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
  20. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +99 -11
  21. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +57 -4
  22. package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
  23. package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
  24. package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
  25. package/dist/dexbot.js +112 -141
  26. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
  27. package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
  28. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
  29. package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
  30. package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
  31. package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
  32. package/dist/market_adapter/inputs/window_cache.js +53 -17
  33. package/dist/market_adapter/lp_chart_core.js +1 -0
  34. package/dist/market_adapter/utils/chain.js +4 -3
  35. package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
  36. package/dist/market_adapter/utils/pair_orientation.js +142 -0
  37. package/dist/modules/account_bots.d.ts +40 -3
  38. package/dist/modules/account_bots.js +80 -37
  39. package/dist/modules/account_orders.d.ts +4 -1
  40. package/dist/modules/account_orders.js +4 -1
  41. package/dist/modules/bitshares-native/resolvers.js +3 -3
  42. package/dist/modules/bitshares-native/subscriptions.js +1 -1
  43. package/dist/modules/bitshares_client.d.ts +12 -10
  44. package/dist/modules/bitshares_client.js +12 -10
  45. package/dist/modules/bot_defaults.d.ts +13 -2
  46. package/dist/modules/bot_defaults.js +31 -2
  47. package/dist/modules/bot_settings.js +6 -3
  48. package/dist/modules/chain_keys.d.ts +5 -1
  49. package/dist/modules/chain_keys.js +5 -1
  50. package/dist/modules/chain_orders.d.ts +6 -2
  51. package/dist/modules/chain_orders.js +6 -2
  52. package/dist/modules/constants.d.ts +11 -0
  53. package/dist/modules/constants.js +31 -1
  54. package/dist/modules/credit_runtime.d.ts +35 -5
  55. package/dist/modules/credit_runtime.js +219 -38
  56. package/dist/modules/dexbot_class.d.ts +22 -2
  57. package/dist/modules/dexbot_class.js +61 -21
  58. package/dist/modules/dexbot_cow_runtime.js +19 -18
  59. package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
  60. package/dist/modules/dexbot_fill_runtime.js +4 -7
  61. package/dist/modules/dexbot_maintenance_runtime.d.ts +7 -2
  62. package/dist/modules/dexbot_maintenance_runtime.js +52 -7
  63. package/dist/modules/dexbot_startup_runtime.js +3 -2
  64. package/dist/modules/dexbot_state_recovery.js +1 -1
  65. package/dist/modules/graceful_shutdown.d.ts +6 -2
  66. package/dist/modules/graceful_shutdown.js +6 -2
  67. package/dist/modules/launcher/bot_supervisor.js +4 -0
  68. package/dist/modules/launcher/launch_modes.js +6 -3
  69. package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
  70. package/dist/modules/launcher/monolithic_runtime.js +60 -1
  71. package/dist/modules/launcher/runtime_mode.d.ts +79 -0
  72. package/dist/modules/launcher/runtime_mode.js +223 -0
  73. package/dist/modules/market_adapter_whitelist.d.ts +8 -0
  74. package/dist/modules/market_adapter_whitelist.js +8 -0
  75. package/dist/modules/order/accounting.d.ts +15 -1
  76. package/dist/modules/order/accounting.js +15 -1
  77. package/dist/modules/order/async_lock.d.ts +9 -3
  78. package/dist/modules/order/async_lock.js +9 -3
  79. package/dist/modules/order/export.d.ts +0 -5
  80. package/dist/modules/order/export.js +2 -7
  81. package/dist/modules/order/format.d.ts +6 -4
  82. package/dist/modules/order/format.js +6 -4
  83. package/dist/modules/order/grid.d.ts +147 -19
  84. package/dist/modules/order/grid.js +321 -68
  85. package/dist/modules/order/grid_reconcile.js +4 -3
  86. package/dist/modules/order/grid_reconcile_internal.js +13 -18
  87. package/dist/modules/order/index.d.ts +4 -2
  88. package/dist/modules/order/index.js +1 -1
  89. package/dist/modules/order/logger_state.d.ts +1 -1
  90. package/dist/modules/order/logger_state.js +1 -1
  91. package/dist/modules/order/manager.d.ts +1 -0
  92. package/dist/modules/order/manager.js +5 -14
  93. package/dist/modules/order/sync_engine.d.ts +26 -11
  94. package/dist/modules/order/sync_engine.js +44 -20
  95. package/dist/modules/order/utils/math.d.ts +157 -47
  96. package/dist/modules/order/utils/math.js +236 -78
  97. package/dist/modules/order/utils/order.d.ts +64 -20
  98. package/dist/modules/order/utils/order.js +80 -24
  99. package/dist/modules/order/utils/system.d.ts +41 -11
  100. package/dist/modules/order/utils/system.js +43 -13
  101. package/dist/modules/order/utils/validate.d.ts +6 -3
  102. package/dist/modules/order/utils/validate.js +53 -60
  103. package/dist/modules/types.d.ts +7 -0
  104. package/dist/modules/utils/asset_symbols.d.ts +5 -5
  105. package/dist/modules/utils/asset_symbols.js +5 -5
  106. package/dist/modules/utils/errors.d.ts +2 -1
  107. package/dist/modules/utils/errors.js +2 -1
  108. package/dist/scripts/analyze-credit.js +44 -27
  109. package/dist/scripts/diagnose-pool-history.js +35 -30
  110. package/dist/scripts/pnl.js +1 -1
  111. package/dist/scripts/rich_list.d.ts +50 -0
  112. package/dist/scripts/rich_list.js +469 -0
  113. package/dist/scripts/run-tests.js +80 -4
  114. package/dist/unlock.d.ts +2 -1
  115. package/dist/unlock.js +53 -21
  116. package/docs/BITSHARES_ONBOARDING.md +7 -0
  117. package/docs/COW_INVARIANTS.md +7 -1
  118. package/docs/DEXBOT_COMPARISON.md +6 -6
  119. package/docs/EVOLUTION.md +11 -9
  120. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -3
  121. package/docs/GRID_RECALCULATION.md +18 -6
  122. package/docs/LIFECYCLE.md +8 -8
  123. package/docs/LOGGING.md +16 -1
  124. package/docs/MPA_CREDIT_USAGE.md +10 -5
  125. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +163 -13
  126. package/docs/README.md +1 -1
  127. package/docs/WORKFLOW.md +6 -5
  128. package/docs/architecture.md +56 -2
  129. package/docs/developer_guide.md +5 -1
  130. package/market_adapter/README.md +14 -7
  131. package/modules/README.md +1 -1
  132. package/package.json +4 -1
  133. package/scripts/README.md +59 -32
  134. package/tests/README.md +40 -2
@@ -5,68 +5,112 @@
5
5
  * Includes grid indexing, order comparison, delta building, and strategy calculations.
6
6
  *
7
7
  * ===============================================================================
8
- * TABLE OF CONTENTS (35 exported functions)
8
+ * TABLE OF CONTENTS (76 exported functions)
9
9
  * ===============================================================================
10
10
  *
11
- * SECTION 1: CHAIN ORDER MATCHING & RECONCILIATION (5 functions)
11
+ * SECTION 1: CHAIN ORDER MATCHING & RECONCILIATION (7 functions)
12
12
  * - parseChainOrder(chainOrder, assets) - Parse blockchain order to grid format
13
13
  * - applyChainSizeToGridOrder(manager, gridOrder, chainSize) - Apply chain size to grid
14
14
  * - correctOrderPriceOnChain(manager, correctionInfo, ...) - Correct order price on chain
15
15
  * - correctAllPriceMismatches(manager, accountName, ...) - Correct all price mismatches
16
- *
17
- * SECTION 2: ORDER CONSTRUCTION (3 functions)
16
+ * - _validatePriceCorrectionEntry(...) - Drain-time staleness check for a queued correction
17
+ * - _stampCorrectionProvenance(...) - Stamp queue provenance on a correction entry
18
+ * - findLiveOrderOwnerByChainId(...) - Find the live grid slot that owns a chain order
19
+ *
20
+ * SECTION 2: CROSSING-PLACEMENT GUARDS (8 functions)
21
+ * - chainOrderMatchesSlot(...) - Exact chain-order/grid-slot match
22
+ * - chainOrderMatchesSlotWithTolerance(...) - Match within price tolerance
23
+ * - crossingCandidateChainId(order) - Chain id of a crossing-check candidate
24
+ * - isCrossingCheckCandidate(order) - Predicate for crossing-placement guards
25
+ * - buildCrossingCheckCandidates(...) - Candidate set for crossing-placement checks
26
+ * - chainOrderUnchangedFromCache(...) - Chain order still matches cached pre-update state
27
+ * - detectCrossedBookPlan(...) - Pre-broadcast crossed-book assert
28
+ * - collectKnownOnChainOrderIds(...) - On-chain ids master must converge against
29
+ *
30
+ * SECTION 3: ORDER CONSTRUCTION (5 functions)
18
31
  * - buildCreateOrderArgs(order, assetA, assetB) - Build create order arguments
19
32
  * - getOrderTypeFromUpdatedFlags(buyUpdated, sellUpdated) - Get type from update flags
20
33
  * - resolveConfiguredPriceBound(value, fallback, startPrice, mode) - Resolve price bounds
21
34
  * - buildFillKey(fillOrParts) - Build a stable fill dedupe key
22
35
  * - buildCreateOpFingerprint(params) - Build fingerprint for create operations
23
36
  *
24
- * SECTION 3: STATE TRANSITIONS (2 functions)
37
+ * SECTION 4: STATE TRANSITIONS & PLACEHOLDERS (6 functions)
25
38
  * - virtualizeOrder(order) - Convert order to VIRTUAL state
26
39
  * - convertToSpreadPlaceholder(order) - Convert order to SPREAD placeholder
27
- *
28
- * SECTION 4: FILTERING & COUNTING (5 functions)
40
+ * - toRailHolePlaceholder(order) - Convert to a rail-typed hole placeholder
41
+ * - geometryTypeForSlotIndex(...) - BUY/SELL type for a slot index
42
+ * - resolveSpreadOrderSide(order) - Resolve the real side of a SPREAD slot
43
+ * - resolveOnChainRetypeType(...) - Type to keep when a live-order slot would retype
44
+ *
45
+ * SECTION 5: GAP EVACUATION (3 functions)
46
+ * - detectGapEvacuationCandidates(...) - Detect gap-evacuation candidates by geometry
47
+ * - updateGapEvacuationStreaks(...) - Tick per-slot gap-evacuation streak counter
48
+ * - collectRefillSlotIds(...) - Refill-slot wire for the COW boundary hold
49
+ *
50
+ * SECTION 6: FILTERING & DRIFT DIAGNOSTICS (12 functions)
51
+ * - parseSlotIndex(id) - Parse "slot-N" to its rail index
29
52
  * - filterOrdersByType(orders, orderType) - Filter orders by type
30
-
31
53
  * - buildOutsideInPairGroups(items, accessors) - Outside->center pair grouping
32
54
  * - extractBatchOperationResults(result) - Extract operation_results from chain batch result
33
55
  * - formatUnmatchedChainOrder(order) - Format structural drift diagnostics
34
- *
35
- * SECTION 5: STATE PREDICATES (7 functions)
56
+ * - isNonBlockingUnmatchedOrder(...) - Deliberate hold that must not read as drift
57
+ * - isStrandedHoldOrder(...) - Stranded hold detection
58
+ * - isOrderGoneErrorMessage(err) - Detect "chain order does not exist"
59
+ * - recordDuplicateOrphanDetection(orderId) - Record a duplicate-orphan detection
60
+ * - clearDuplicateOrphanDetection(orderId) - Clear the detection counter
61
+ * - duplicateOrphanLogInfo(...) - Log level + re-detection info for duplicate orphans
62
+ * - _filterUnmatchedChainOrders(...) - Drop a satisfied id from the unmatched list
63
+ *
64
+ * SECTION 7: STATE PREDICATES (8 functions)
36
65
  * - isOrderOnChain(order) - Check if order is ACTIVE or PARTIAL
37
66
  * - isOrderVirtual(order) - Check if order is VIRTUAL
38
67
  * - hasOnChainId(order) - Check if order has blockchain orderId
39
68
  * - isOrderPlaced(order) - Check if order is placed on chain
40
69
  * - isPhantomOrder(order) - Check if order is phantom (ACTIVE without orderId)
41
70
  * - isSlotAvailable(order) - Check if slot is available for placement
71
+ * - isEmptyGridSlot(order) - Empty reusable placeholder test
42
72
  * - isOrderHealthy(order, context) - Comprehensive order health check
43
73
  *
44
- * SECTION 6: SIZE VALIDATION (2 functions)
74
+ * SECTION 8: SIZE VALIDATION (2 functions)
45
75
  * - checkSizeThreshold(size, threshold) - Check if size exceeds threshold
46
76
  * - checkSizesBeforeMinimum(sizes, minSize) - Check sizes against minimum
47
77
  *
48
- * SECTION 7: GRID BOUNDARY & ROLES (3 functions)
78
+ * SECTION 9: GRID BOUNDARY & ROLES (5 functions)
49
79
  * - calculateIdealBoundary(allSlots, startPrice, gapSlots) - Calculate ideal boundary
50
80
  * - assignGridRoles(allSlots, boundaryIdx, gapSlots, ...) - Assign BUY/SELL roles
51
81
  * - shouldFlagOutOfSpread(order, startPrice, configSpread) - Check if order is out of spread
82
+ * - deriveTargetBoundary(...) - Target boundary for a rebalance plan
83
+ * - isShiftEligibleFill(...) - Whether a fill may drive boundary shift/rotation
52
84
  *
53
- * SECTION 8: GRID INDEXING (2 functions)
85
+ * SECTION 10: GRID INDEXING (2 functions)
54
86
  * - buildIndexes(grid) - Build complete index set from grid
55
87
  * - validateIndexes(grid, indexes) - Validate index consistency
56
88
  *
57
- * SECTION 9: ORDER COMPARISON & DELTA (3 functions)
89
+ * SECTION 11: ORDER COMPARISON & DELTA (2 functions)
58
90
  * - ordersEqual(a, b) - Compare two orders for equality
59
91
  * - buildDelta(masterGrid, workingGrid) - Build delta actions between grids
60
- * - getOrderSize(order) - Extract order size with fallback
61
92
  *
62
- * SECTION 10: STRATEGY CALCULATIONS (7 functions)
93
+ * SECTION 12: STRATEGY / EDGE / BUDGET (11 functions)
63
94
  * - resolveEdgeCount(config, side) - Clamped per-side edge count (>=0 int, 0 disables)
64
95
  * - resolveEdgeOrders(config) - Total edge orders buy+sell (fee/count totals)
65
- * - resolveLiveEdgeAnchorPrice(manager, side) - Live-grid edge anchor (genesis ladder extreme; null when no usable ladder)
96
+ * - selectEdgeSlots(sortedAsc, count, excludeIds, edge, anchorPrice?) - Shared position picker (both edges anchor toward their bound)
97
+ * - getCoreOrdersTotal(config) - Total target order count across both sides
98
+ * - getSideBudget(...) - Side budget after BTS fee deduction
99
+ * - calculateBudgetedSizes(...) - Sizes for all slots on a side using weighted distribution
100
+ * - edgeOrderIdSet(allSlots, config, orderType, anchorPrice?, excludeIds?) - Edge order id set (config count; shares the picker ordering; excludeIds carries the window exclusion)
101
+ * - liveWindowIdSet(...) - Window member ids for one side from the live manager
66
102
  * - resolveEdgeAnchorPrice(config, side) - Config-bound anchor fallback (buy→minPrice, sell→maxPrice; null when unresolvable)
103
+ * - resolveLiveEdgeAnchorPrice(manager, side) - Live-grid edge anchor (genesis ladder extreme; null when no usable ladder)
67
104
  * - compareEdge(a, b, edge, anchorPrice) - Shared anchored edge comparator (single ordering source)
68
- * - edgeOrderIdSet(allSlots, config, orderType, anchorPrice?, excludeIds?) - Edge order id set (config count; shares the picker ordering; excludeIds carries the window exclusion)
69
- * - selectEdgeSlots(sortedAsc, count, excludeIds, edge, anchorPrice?) - Shared position picker (both edges anchor toward their bound)
105
+ *
106
+ * SECTION 13: GRID PRICE INVARIANT (2 functions)
107
+ * - checkGridPriceInvariant(...) - The price emitted for a slot must equal its genesis price
108
+ * - reportGridPriceInvariant(...) - Report one GRID-PRICE-INVARIANT check
109
+ *
110
+ * SECTION 14: PERSISTED CRAWL & PLACEMENT GRACE (3 functions)
111
+ * - consumePendingFillCrawls(...) - Apply recorded-but-uncommitted fill crawls to the boundary
112
+ * - recordOrderPlacement(...) - Record a fresh on-chain placement timestamp
113
+ * - isFreshlyPlacedOrder(...) - Chain order placed within the surplus-cancel grace
70
114
  *
71
115
  * ===============================================================================
72
116
  */
@@ -79,7 +123,7 @@ import { getErrorMessage, getErrorCode, getErrorName } from '../../utils/errors.
79
123
  import { hasGenesisLadder } from '../genesis_policy.js';
80
124
  import { parseSlotIndex as parseSlotIndexShared } from './slot.js';
81
125
  const { isValidNumber, toFiniteNumber } = Format;
82
- const { blockchainToFloat, floatToBlockchainInt, quantizeFloat, priceSlotEqual } = MathUtils;
126
+ const { blockchainToFloat, floatToBlockchainInt, quantizeFloat, slotIndexForPrice, priceSlotEqual } = MathUtils;
83
127
  const orderLogger = new Logger('Order');
84
128
  const ORDER_GONE_ERROR_FRAGMENT = 'not found';
85
129
  /**
@@ -398,7 +442,18 @@ function _validatePriceCorrectionEntry(manager, entry) {
398
442
  if (!hasGenesisLadder(manager?._genesis)) {
399
443
  return { valid: false, reason: `no price ladder (INV-GRID-004) — slot ${slotId} has no authoritative price` };
400
444
  }
401
- if (!priceSlotEqual(slot.price, Number(entry.expectedPrice), Number(precision))) {
445
+ // Genesis is guaranteed here (guarded above), so compare ladder LEVELS --
446
+ // not priceSlotEqual at the asset amount precision, which collapses
447
+ // adjacent levels for a low-precision asset and would accept a stale entry.
448
+ let sameLevel;
449
+ try {
450
+ const genesis = manager._genesis;
451
+ sameLevel = slotIndexForPrice(slot.price, genesis) === slotIndexForPrice(Number(entry.expectedPrice), genesis);
452
+ }
453
+ catch {
454
+ sameLevel = priceSlotEqual(slot.price, Number(entry.expectedPrice), Number(precision));
455
+ }
456
+ if (!sameLevel) {
402
457
  return { valid: false, reason: `slot ${slotId} now targets ${slot.price} (entry queued ${entry.expectedPrice})` };
403
458
  }
404
459
  // Size check: the broadcast sends amountToSell from the QUEUED snapshot.
@@ -1824,7 +1879,7 @@ function isOrderOnChain(order) {
1824
1879
  * @param {Object} slot - The slot being retyped
1825
1880
  * @param {number} idx - Slot index
1826
1881
  * @param {number} buyEndIdx - Boundary index (last BUY slot)
1827
- * @param {Object} ORDER_TYPES - ORDER_TYPES constants
1882
+ * @param {Object} orderTypes - ORDER_TYPES constants
1828
1883
  * @returns {string} Type to keep for the on-chain slot
1829
1884
  */
1830
1885
  function resolveOnChainRetypeType(slot, idx, buyEndIdx, orderTypes) {
@@ -2557,9 +2612,10 @@ export function consumePendingFillCrawls(manager) {
2557
2612
  catch { /* best-effort */ }
2558
2613
  }
2559
2614
  };
2560
- // NB: Number(null) === 0 — check null/undefined explicitly, or a
2615
+ // NB: Number(null) === 0 and Number('') === 0 — check null/undefined/''
2616
+ // explicitly (the '' case matches runPreBroadcastGuards), or a
2561
2617
  // boundary-less manager would "apply" onto slot 0.
2562
- if (manager?.boundaryIdx === null || manager?.boundaryIdx === undefined) {
2618
+ if (manager?.boundaryIdx === null || manager?.boundaryIdx === undefined || manager?.boundaryIdx === '') {
2563
2619
  clear();
2564
2620
  return { applied: false, reason: 'null-boundary' };
2565
2621
  }
@@ -4,45 +4,75 @@
4
4
  * Price derivation, persistence, grid correction, and UI/interactive utilities.
5
5
  *
6
6
  * ===============================================================================
7
- * TABLE OF CONTENTS (21 exported functions)
7
+ * TABLE OF CONTENTS (43 exported functions + 11 structural view types)
8
8
  * ===============================================================================
9
9
  *
10
- * SECTION 1: PRICE DERIVATION (10 functions)
10
+ * SECTION 1: PRICE DERIVATION (9 functions + 1 internal)
11
11
  * - lookupAsset(BitShares, symbol) - Lookup asset metadata from blockchain
12
+ * - resolveAssetByRef(BitShares, ref) - Resolve a full asset object from id/symbol
12
13
  * - deriveMarketPrice(BitShares, symA, symB) - Derive price from order book
13
14
  * - derivePoolPrice(BitShares, symA, symB) - Derive price from liquidity pool
15
+ * - setDerivePriceTestHook(hook) - Test-only seam for derivePrice
14
16
  * - derivePrice(BitShares, symA, symB, mode) - Derive price with fallback chain
15
17
  * - derivePriceViaBridges(BitShares, symA, symB, bridges, mode) - Multi-hop price via bridge assets
16
18
  * - derivePriceWithBridges(BitShares, symA, symB, bridges, mode) - Direct price, else bridge hops
17
- * - resolveLiquidityPoolByShareAsset(BitShares, shareAsset) - Resolve LP by share asset
18
19
  * - deriveLiquidityPoolTokenValue(BitShares, symA, symB) - Derive LP token value
19
- * - loadAmaCenterPrice(manager) - Load AMA center price
20
- * - loadAmaCenterSnapshot(manager) - Load AMA center snapshot
20
+ * - resolveLiquidityPoolByShareAsset(BitShares, shareAsset) - Resolve LP by share asset (internal)
21
21
  *
22
- * SECTION 2: FEE MANAGEMENT (1 function)
22
+ * SECTION 2: AMA CENTER SNAPSHOT (2 functions)
23
+ * - loadAmaCenterSnapshot(manager) - Load the full dynamic-grid snapshot
24
+ * - loadAmaCenterPrice(manager) - Load the AMA center price
25
+ *
26
+ * SECTION 3: FEE MANAGEMENT (1 function)
23
27
  * - initializeFeeCache(botsConfig, BitShares) - Initialize fee cache from blockchain
24
28
  *
25
- * SECTION 3: GRID STATE MANAGEMENT (3 functions)
29
+ * SECTION 4: GRID STATE MANAGEMENT (5 functions)
26
30
  * - persistGridSnapshot(manager, accountOrders) - Persist grid to storage
31
+ * - restoreGapEvacStreaks(manager) - Restore persisted gap-evacuation streaks
27
32
  * - retryPersistenceIfNeeded(manager) - Retry persistence if previous failed
28
33
  * - applyGridDivergenceCorrections(manager, ...) - Apply grid divergence corrections
29
- *
30
- * SECTION 4: UI & INTERACTIVE UTILITIES (7 functions)
34
+ * - applyPersistedPendingCrawls(...) - Apply persisted-but-uncommitted fill crawls
35
+ *
36
+ * SECTION 5: SPREAD-CORRECTION READINESS (7 functions)
37
+ * - resolveSpreadFreshnessMs(manager) - The single freshness window for spread trust
38
+ * - resolveSpreadCrossingFloor(manager) - Crossing floor spread correction must not trade through
39
+ * - refreshLiveMarketPrice(manager) - Refresh the cached live market price
40
+ * - maybeRefreshLiveMarketPrice(manager) - Refresh if stale, paced to one attempt per window
41
+ * - evaluateSpreadCorrectionReadiness(manager) - Evaluate whether spread correction may act
42
+ * - resolveSpreadMarketReference(manager) - Resolve the last real FILL price
43
+ * - resolveLastFillGuardReference(manager) - Resolve the reference the LAST-FILL-GUARD judges
44
+ *
45
+ * SECTION 6: LAST-FILL / MARKET-FILL PERSISTENCE (6 functions)
46
+ * - restoreLastMarketFill(manager) - Restore the persisted last-market-fill reference
47
+ * - normalizeLastFillPivot(row) - Normalize a persisted LAST-FILL-GUARD pivot row
48
+ * - normalizeLastMarketFill(row) - Normalize a persisted last-market-fill row
49
+ * - setLastFillPivot(manager, ...) - Write the LAST-FILL-GUARD pivot scalar family
50
+ * - resetLastFillPivot(manager) - Clear the pivot to cold state
51
+ * - restoreLastFillPivot(manager) - Restore the persisted pivot into the manager
52
+ *
53
+ * SECTION 7: UI & INTERACTIVE UTILITIES (6 functions)
31
54
  * - ensureProfilesDirectory(profilesDir) - Ensure profiles directory exists
32
55
  * - sleep(ms) - Pause execution for specified duration
33
56
  * - readInput(prompt, options) - Read user input from stdin
34
57
  * - readPassword(prompt) - Read password with masked echo
35
58
  * - withRetry(fn, options) - Execute async function with exponential backoff
36
- * - withTimeout(promise, timeoutMs, options) - defined in ./timeout
37
59
  * - withBlockchainRetry(fn, label, options) - Blockchain op with timeout + retry + node failover
60
+ * (withTimeout lives in ./timeout)
38
61
  *
39
- * SECTION 6: GENERAL UTILITIES (5 functions)
62
+ * SECTION 8: GENERAL UTILITIES (7 functions)
40
63
  * - resolveAccountRef(manager, account) - Resolve best account reference
41
64
  * - deepFreeze(obj) - Recursively freeze object for immutability
42
65
  * - cloneMap(map) - Create shallow clone of Map
43
66
  * - ensureDir(dirPath) - Ensure directory exists, creating recursively
67
+ * - nowIso() - Current time as an ISO string
68
+ * - fireStructuralResync(manager, ...) - Fire-and-forget structural grid resync
44
69
  * - parseJsonWithComments(raw) - Parse JSON with comment stripping
45
70
  *
71
+ * STRUCTURAL VIEW TYPES:
72
+ * AssetMeta, PoolReserve, PoolEntry, BitSharesClient, AmaCenterSnapshot,
73
+ * FeeCacheEntryData, SpreadCorrectionRefusalReason, SpreadCorrectionReadiness,
74
+ * UnmatchedChainOrderLike, GridResizeResult, CowResult
75
+ *
46
76
  * ===============================================================================
47
77
  */
48
78
  import type { OrderManagerLike, BotLike, AccountOrdersLike, ManagedOrder, AccountTotals, CowAction } from '../../types.js';
@@ -4,45 +4,75 @@
4
4
  * Price derivation, persistence, grid correction, and UI/interactive utilities.
5
5
  *
6
6
  * ===============================================================================
7
- * TABLE OF CONTENTS (21 exported functions)
7
+ * TABLE OF CONTENTS (43 exported functions + 11 structural view types)
8
8
  * ===============================================================================
9
9
  *
10
- * SECTION 1: PRICE DERIVATION (10 functions)
10
+ * SECTION 1: PRICE DERIVATION (9 functions + 1 internal)
11
11
  * - lookupAsset(BitShares, symbol) - Lookup asset metadata from blockchain
12
+ * - resolveAssetByRef(BitShares, ref) - Resolve a full asset object from id/symbol
12
13
  * - deriveMarketPrice(BitShares, symA, symB) - Derive price from order book
13
14
  * - derivePoolPrice(BitShares, symA, symB) - Derive price from liquidity pool
15
+ * - setDerivePriceTestHook(hook) - Test-only seam for derivePrice
14
16
  * - derivePrice(BitShares, symA, symB, mode) - Derive price with fallback chain
15
17
  * - derivePriceViaBridges(BitShares, symA, symB, bridges, mode) - Multi-hop price via bridge assets
16
18
  * - derivePriceWithBridges(BitShares, symA, symB, bridges, mode) - Direct price, else bridge hops
17
- * - resolveLiquidityPoolByShareAsset(BitShares, shareAsset) - Resolve LP by share asset
18
19
  * - deriveLiquidityPoolTokenValue(BitShares, symA, symB) - Derive LP token value
19
- * - loadAmaCenterPrice(manager) - Load AMA center price
20
- * - loadAmaCenterSnapshot(manager) - Load AMA center snapshot
20
+ * - resolveLiquidityPoolByShareAsset(BitShares, shareAsset) - Resolve LP by share asset (internal)
21
21
  *
22
- * SECTION 2: FEE MANAGEMENT (1 function)
22
+ * SECTION 2: AMA CENTER SNAPSHOT (2 functions)
23
+ * - loadAmaCenterSnapshot(manager) - Load the full dynamic-grid snapshot
24
+ * - loadAmaCenterPrice(manager) - Load the AMA center price
25
+ *
26
+ * SECTION 3: FEE MANAGEMENT (1 function)
23
27
  * - initializeFeeCache(botsConfig, BitShares) - Initialize fee cache from blockchain
24
28
  *
25
- * SECTION 3: GRID STATE MANAGEMENT (3 functions)
29
+ * SECTION 4: GRID STATE MANAGEMENT (5 functions)
26
30
  * - persistGridSnapshot(manager, accountOrders) - Persist grid to storage
31
+ * - restoreGapEvacStreaks(manager) - Restore persisted gap-evacuation streaks
27
32
  * - retryPersistenceIfNeeded(manager) - Retry persistence if previous failed
28
33
  * - applyGridDivergenceCorrections(manager, ...) - Apply grid divergence corrections
29
- *
30
- * SECTION 4: UI & INTERACTIVE UTILITIES (7 functions)
34
+ * - applyPersistedPendingCrawls(...) - Apply persisted-but-uncommitted fill crawls
35
+ *
36
+ * SECTION 5: SPREAD-CORRECTION READINESS (7 functions)
37
+ * - resolveSpreadFreshnessMs(manager) - The single freshness window for spread trust
38
+ * - resolveSpreadCrossingFloor(manager) - Crossing floor spread correction must not trade through
39
+ * - refreshLiveMarketPrice(manager) - Refresh the cached live market price
40
+ * - maybeRefreshLiveMarketPrice(manager) - Refresh if stale, paced to one attempt per window
41
+ * - evaluateSpreadCorrectionReadiness(manager) - Evaluate whether spread correction may act
42
+ * - resolveSpreadMarketReference(manager) - Resolve the last real FILL price
43
+ * - resolveLastFillGuardReference(manager) - Resolve the reference the LAST-FILL-GUARD judges
44
+ *
45
+ * SECTION 6: LAST-FILL / MARKET-FILL PERSISTENCE (6 functions)
46
+ * - restoreLastMarketFill(manager) - Restore the persisted last-market-fill reference
47
+ * - normalizeLastFillPivot(row) - Normalize a persisted LAST-FILL-GUARD pivot row
48
+ * - normalizeLastMarketFill(row) - Normalize a persisted last-market-fill row
49
+ * - setLastFillPivot(manager, ...) - Write the LAST-FILL-GUARD pivot scalar family
50
+ * - resetLastFillPivot(manager) - Clear the pivot to cold state
51
+ * - restoreLastFillPivot(manager) - Restore the persisted pivot into the manager
52
+ *
53
+ * SECTION 7: UI & INTERACTIVE UTILITIES (6 functions)
31
54
  * - ensureProfilesDirectory(profilesDir) - Ensure profiles directory exists
32
55
  * - sleep(ms) - Pause execution for specified duration
33
56
  * - readInput(prompt, options) - Read user input from stdin
34
57
  * - readPassword(prompt) - Read password with masked echo
35
58
  * - withRetry(fn, options) - Execute async function with exponential backoff
36
- * - withTimeout(promise, timeoutMs, options) - defined in ./timeout
37
59
  * - withBlockchainRetry(fn, label, options) - Blockchain op with timeout + retry + node failover
60
+ * (withTimeout lives in ./timeout)
38
61
  *
39
- * SECTION 6: GENERAL UTILITIES (5 functions)
62
+ * SECTION 8: GENERAL UTILITIES (7 functions)
40
63
  * - resolveAccountRef(manager, account) - Resolve best account reference
41
64
  * - deepFreeze(obj) - Recursively freeze object for immutability
42
65
  * - cloneMap(map) - Create shallow clone of Map
43
66
  * - ensureDir(dirPath) - Ensure directory exists, creating recursively
67
+ * - nowIso() - Current time as an ISO string
68
+ * - fireStructuralResync(manager, ...) - Fire-and-forget structural grid resync
44
69
  * - parseJsonWithComments(raw) - Parse JSON with comment stripping
45
70
  *
71
+ * STRUCTURAL VIEW TYPES:
72
+ * AssetMeta, PoolReserve, PoolEntry, BitSharesClient, AmaCenterSnapshot,
73
+ * FeeCacheEntryData, SpreadCorrectionRefusalReason, SpreadCorrectionReadiness,
74
+ * UnmatchedChainOrderLike, GridResizeResult, CowResult
75
+ *
46
76
  * ===============================================================================
47
77
  */
48
78
  import { createRequire } from 'node:module';
@@ -1587,7 +1617,7 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
1587
1617
  // orders through the budget allocation below but never shift rails. The
1588
1618
  // fund-ratio writer was removed — it moved the boundary without guaranteed
1589
1619
  // 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:
1620
+ // the new boundary (<bot> 91->94) with no repair path. Remaining writers:
1591
1621
  // fills (deriveTargetBoundary, same-cycle rotations) and spread promotion
1592
1622
  // (shifts only onto slots placed in the same atomic batch).
1593
1623
  let resizeCowResult = null;
@@ -1627,7 +1657,7 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
1627
1657
  // GUARD keeps gap-band strays typed BUY/SELL (never SPREAD+ACTIVE), so
1628
1658
  // without a geometric filter they are selected as "closest to market"
1629
1659
  // 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
1660
+ // boundary shift moves into the rail (<bot>: boundary 107->110 left
1631
1661
  // the sell rail parked at 111-130 with the bottom three, 111-113,
1632
1662
  // inside the new spread gap; real spread 0.5% instead of the 2.0%
1633
1663
  // target).
@@ -12,14 +12,17 @@
12
12
  * SECTION 2: VALIDATION
13
13
  * - validateOrder()
14
14
  * - validateGridForPersistence()
15
- * - calculateRequiredFunds()
15
+ * - calculateRequiredFunds() (internal)
16
16
  * - validateWorkingGridFunds()
17
17
  * - checkFundDrift()
18
18
  *
19
19
  * SECTION 3: GRID RECONCILIATION (COW Pipeline)
20
20
  * - reconcileGrid()
21
21
  * - optimizeRebalanceActions()
22
- * - summarizeActions()
22
+ * - summarizeActions() (internal)
23
+ * - hasExecutableActions()
24
+ * - validateCreateTargetSlots()
25
+ * - stampGapEvacuationRotation()
23
26
  * - hasActionForOrder()
24
27
  * - removeActionsForOrder()
25
28
  * - projectTargetToWorkingGrid()
@@ -220,7 +223,7 @@ declare function hasExecutableActions(rebalanceResult: unknown): boolean;
220
223
  * with {chainOrderId, price, size, type} to check beyond the grid
221
224
  * @returns {{isValid: boolean, violations: Array<Object>, violatingTargetIds: Set<string>}} Validation result
222
225
  */
223
- declare function validateCreateTargetSlots(actions: CowAction[], orders: Map<string, ManagedOrder>, _assets?: AssetPair | null, chainOrderCandidates?: UnmatchedChainOrder[]): {
226
+ declare function validateCreateTargetSlots(actions: CowAction[], orders: Map<string, ManagedOrder>, _assets?: AssetPair | null, chainOrderCandidates?: UnmatchedChainOrder[], incrementPercent?: number | null): {
224
227
  isValid: boolean;
225
228
  violations: CreateTargetViolation[];
226
229
  violatingTargetIds: Set<string>;
@@ -12,14 +12,17 @@
12
12
  * SECTION 2: VALIDATION
13
13
  * - validateOrder()
14
14
  * - validateGridForPersistence()
15
- * - calculateRequiredFunds()
15
+ * - calculateRequiredFunds() (internal)
16
16
  * - validateWorkingGridFunds()
17
17
  * - checkFundDrift()
18
18
  *
19
19
  * SECTION 3: GRID RECONCILIATION (COW Pipeline)
20
20
  * - reconcileGrid()
21
21
  * - optimizeRebalanceActions()
22
- * - summarizeActions()
22
+ * - summarizeActions() (internal)
23
+ * - hasExecutableActions()
24
+ * - validateCreateTargetSlots()
25
+ * - stampGapEvacuationRotation()
23
26
  * - hasActionForOrder()
24
27
  * - removeActionsForOrder()
25
28
  * - projectTargetToWorkingGrid()
@@ -35,7 +38,7 @@
35
38
  // ===============================================================================
36
39
  import * as Format from '../format.js';
37
40
  import { ORDER_STATES, ORDER_TYPES, COW_ACTIONS, COW_ORIGINS, GRID_LIMITS } from '../../constants.js';
38
- import { floatToBlockchainInt, blockchainToFloat, getPrecisionSlack, getPrecisionByOrderType, getDoubleDustThreshold, getSellStartIdx, isSlotIndexInGapBand, isEvacuationRotationAllowed, clamp, priceSlotEqual } from './math.js';
41
+ import { floatToBlockchainInt, blockchainToFloat, getPrecisionSlack, getPrecisionByOrderType, getDoubleDustThreshold, getSellStartIdx, isSlotIndexInGapBand, isEvacuationRotationAllowed, clamp, pricesOnSameLevel, sameGridPrice } from './math.js';
39
42
  import { parseSlotIndex } from './slot.js';
40
43
  import { isOrderOnChain, isPhantomOrder, convertToSpreadPlaceholder, detectGapEvacuationCandidates, updateGapEvacuationStreaks, isNonBlockingUnmatchedOrder } from './order.js';
41
44
  const { isValidNumber, toFiniteNumber } = Format;
@@ -608,13 +611,15 @@ function optimizeRebalanceActions(actions, masterGrid, options = {}) {
608
611
  // Explicit null/undefined guard BEFORE Number(): Number(null) === 0 is
609
612
  // finite and would turn an absent boundary into a valid slot-0 geometry,
610
613
  // stamping a bogus gap-evacuation bypass (undefined already fails open via
611
- // NaN, so only null was hazardous).
614
+ // NaN, so only null was hazardous). '' is equally hazardous (Number('')
615
+ // === 0) and is guarded here the same way as in
616
+ // stampGapEvacuationRotation.
612
617
  const rawOptBoundary = options?.boundaryIdx;
613
618
  const rawOptGapSlots = options?.gapSlots;
614
- const optBoundary = (rawOptBoundary === null || rawOptBoundary === undefined)
619
+ const optBoundary = (rawOptBoundary === null || rawOptBoundary === undefined || rawOptBoundary === '')
615
620
  ? NaN
616
621
  : Number(rawOptBoundary);
617
- const optGapSlots = (rawOptGapSlots === null || rawOptGapSlots === undefined)
622
+ const optGapSlots = (rawOptGapSlots === null || rawOptGapSlots === undefined || rawOptGapSlots === '')
618
623
  ? NaN
619
624
  : Number(rawOptGapSlots);
620
625
  const hasOptGeometry = Number.isFinite(optBoundary) && Number.isFinite(optGapSlots) && optGapSlots >= 0;
@@ -734,7 +739,7 @@ function hasExecutableActions(rebalanceResult) {
734
739
  * with {chainOrderId, price, size, type} to check beyond the grid
735
740
  * @returns {{isValid: boolean, violations: Array<Object>, violatingTargetIds: Set<string>}} Validation result
736
741
  */
737
- function validateCreateTargetSlots(actions, orders, _assets = null, chainOrderCandidates = []) {
742
+ function validateCreateTargetSlots(actions, orders, _assets = null, chainOrderCandidates = [], incrementPercent = null) {
738
743
  const safeActions = Array.isArray(actions) ? actions : [];
739
744
  const orderMap = orders instanceof Map ? orders : new Map();
740
745
  const releasedSlotIds = new Set();
@@ -807,9 +812,9 @@ function validateCreateTargetSlots(actions, orders, _assets = null, chainOrderCa
807
812
  // set entirely, letting a CREATE collide with a slot-unknown
808
813
  // chain order sitting at the same price level (duplicate order).
809
814
  if (_assets) {
810
- // priceSlotEqual is a top-level import (the old inline
811
- // require('./math.js') threw under ESM and the catch-all
812
- // below silently disabled the whole fallback).
815
+ // Tolerance-based level check (pricesOnSameLevel); NOT
816
+ // priceSlotEqual at the asset precision, which collapses
817
+ // adjacent grid levels for a low-precision asset.
813
818
  const slotlessCandidates = validChainCandidates.filter((u) => !(u.chainSlotId || u.candidateSlotId));
814
819
  for (const entry of createEntries) {
815
820
  if (violations.some(v => v.targetId === entry.targetId))
@@ -819,14 +824,10 @@ function validateCreateTargetSlots(actions, orders, _assets = null, chainOrderCa
819
824
  continue;
820
825
  if (u.type && entry.type && u.type !== entry.type)
821
826
  continue;
822
- const precision = entry.type === 'sell' ? _assets.assetA?.precision : _assets.assetB?.precision;
823
- try {
824
- if (priceSlotEqual(u.price, entry.price, precision)) {
825
- violations.push({ targetId: entry.targetId, currentOrderId: u.chainOrderId, currentType: entry.type, currentState: 'CHAIN_ORPHAN', reason: 'chain_orphan_collision' });
826
- break;
827
- }
827
+ if (pricesOnSameLevel(Number(u.price), Number(u.size) || 0, u.type, Number(entry.price), Number(entry.size) || 0, entry.type, _assets, incrementPercent)) {
828
+ violations.push({ targetId: entry.targetId, currentOrderId: u.chainOrderId, currentType: entry.type, currentState: 'CHAIN_ORPHAN', reason: 'chain_orphan_collision' });
829
+ break;
828
830
  }
829
- catch { }
830
831
  }
831
832
  }
832
833
  }
@@ -840,21 +841,24 @@ function validateCreateTargetSlots(actions, orders, _assets = null, chainOrderCa
840
841
  else
841
842
  seen.add(entry.targetId);
842
843
  }
843
- // Same-batch bit-identical duplicate price across DIFFERENT target slots.
844
+ // Same-batch duplicate price across DIFFERENT target slots.
844
845
  // The genesis-frozen slot mapping gives every slot a distinct price
845
- // level, so two CREATEs at the exact same price on different slots
846
- // indicate a degenerate plan (production incident 2026-08-29: several
847
- // slots planned at one price; every batch was filtered down to a
848
- // single op and the grid rebuild crawled at one placement per cycle).
849
- // The tolerance-based price-collision check that caught this class was
850
- // removed with the slot-based rewrite; this exact-equality check
851
- // restores the protection without tolerance false-positives. First
852
- // target per (type, price) wins; later duplicates are skipped by the
853
- // caller via violatingTargetIds.
854
- const priceOwner = new Map();
846
+ // level, so two CREATEs at the same price on different slots indicate a
847
+ // degenerate plan (production incident 2026-08-29: several slots
848
+ // planned at one price; every batch was filtered down to a single op
849
+ // and the grid rebuild crawled at one placement per cycle).
850
+ //
851
+ // Identity is the ladder level, NOT the on-chain integer at the asset
852
+ // precision: a price is not an amount, so a low-precision asset
853
+ // (e.g. precision 4) collapses an entire adjacent band (0.000318 and
854
+ // 0.000343 both -> 3) and would flag every CREATE but the first as a
855
+ // duplicate. sameGridPrice carries 1e-9 relative slack so float noise
856
+ // in a repeated level still matches without merging distinct levels.
857
+ // First target per (type, level) wins; later duplicates are skipped by
858
+ // the caller via violatingTargetIds.
859
+ const invalidPriceTargets = new Set();
855
860
  for (const entry of createEntries) {
856
- const priceNum = Number(entry.price);
857
- if (!Number.isFinite(priceNum)) {
861
+ if (!Number.isFinite(Number(entry.price))) {
858
862
  // Fail closed: an unpriceable CREATE cannot be proven
859
863
  // collision-free, so it is rejected, not skipped.
860
864
  violations.push({
@@ -864,37 +868,26 @@ function validateCreateTargetSlots(actions, orders, _assets = null, chainOrderCa
864
868
  currentState: 'CREATE',
865
869
  reason: 'create_price_invalid',
866
870
  });
867
- continue;
868
- }
869
- // Key on the on-chain integer repr when the side precision is
870
- // known (bit-exact: prices that quantize to the same chain int
871
- // ARE the same price on the DEX); float fallback preserves the
872
- // old behavior for callers without assets context.
873
- let key;
874
- let sidePrecision = null;
875
- try {
876
- sidePrecision = _assets ? getPrecisionByOrderType(_assets, entry.type) : null;
877
- }
878
- catch {
879
- sidePrecision = null;
880
- }
881
- if (Number.isFinite(Number(sidePrecision)) && Number(sidePrecision) > 0) {
882
- try {
883
- key = `${String(entry.type)}:i${floatToBlockchainInt(priceNum, Number(sidePrecision))}`;
884
- }
885
- catch {
886
- key = `${String(entry.type)}:${priceNum}`;
887
- }
888
- }
889
- else {
890
- key = `${String(entry.type)}:${priceNum}`;
891
- }
892
- const owner = priceOwner.get(key);
893
- if (owner === undefined) {
894
- priceOwner.set(key, entry.targetId);
871
+ invalidPriceTargets.add(entry.targetId);
895
872
  }
896
- else if (owner !== entry.targetId) {
897
- violations.push({ targetId: entry.targetId, currentOrderId: null, currentType: entry.type, currentState: 'CREATE', reason: 'same_batch_price_duplicate', duplicateOf: owner });
873
+ }
874
+ const duplicateTargets = new Set();
875
+ for (let i = 0; i < createEntries.length; i++) {
876
+ const a = createEntries[i];
877
+ if (invalidPriceTargets.has(a.targetId))
878
+ continue;
879
+ for (let j = i + 1; j < createEntries.length; j++) {
880
+ const b = createEntries[j];
881
+ if (invalidPriceTargets.has(b.targetId))
882
+ continue;
883
+ if (a.targetId === b.targetId || a.type !== b.type)
884
+ continue;
885
+ if (!sameGridPrice(a.price, b.price))
886
+ continue;
887
+ if (duplicateTargets.has(b.targetId))
888
+ continue;
889
+ duplicateTargets.add(b.targetId);
890
+ violations.push({ targetId: b.targetId, currentOrderId: null, currentType: b.type, currentState: 'CREATE', reason: 'same_batch_price_duplicate', duplicateOf: a.targetId });
898
891
  }
899
892
  }
900
893
  }
@@ -222,6 +222,7 @@ export interface BotLike {
222
222
  _gridLockHoldWarnAt: number;
223
223
  _outOfSpreadSince: number;
224
224
  _outOfSpreadStaleWarned: boolean;
225
+ _outOfSpreadTransientCount: number;
225
226
  _strandedHoldSince: Map<string, number>;
226
227
  _recoverySyncInFlight: number;
227
228
  _batchInFlight: number;
@@ -506,6 +507,12 @@ export interface BotMetrics extends UnknownRecord {
506
507
  boundaryDriftExceedsWindowCount: number;
507
508
  /** Non-spread-correction CREATE/UPDATE destinations inside the gap band (shadow). */
508
509
  gapBandPlacementShadowCount: number;
510
+ /** Every spread-correction batch that failed to land (executed !== true), any cause. */
511
+ spreadCorrectionRefusedCount: number;
512
+ /** Spread-correction refusal breakdown keyed by SPREAD_CORRECTION_REFUSAL value (commit-refused, version-mismatch, create-collision, update-target-missing, unmatched-chain-orders, shutdown, batch-not-executed). */
513
+ spreadCorrectionRefusalCauses: Record<string, number>;
514
+ /** Bounded re-plan retries attempted after a transient spread-correction refusal. */
515
+ spreadCorrectionRetryCount: number;
509
516
  }
510
517
  /** An unmatched chain order surfaced by a sync pass. */
511
518
  export interface UnmatchedChainOrder extends UnknownRecord {
@@ -3,11 +3,11 @@
3
3
  *
4
4
  * BitShares stores asset symbols canonically UPPERCASE, so the assetA and
5
5
  * assetB symbols of a bot pair are always UPPERCASE on chain.
6
- * Nodes accept a lowercase lookup and answer it without error, so a lowercase
7
- * symbol never fails — it just travels on as lowercase into everything built
8
- * from it: the `symbol` field we attach to resolved assets, chart titles,
9
- * cache-file names, Kibana query terms, and strict in-process comparisons such
10
- * as the core-asset side check `assetA === 'CORE'`. That is a
6
+ * `lookup_asset_symbols` is case-sensitive: a lowercase symbol resolves to
7
+ * null (not an error), so a lowercase input silently drops the asset. Casing
8
+ * also leaks into everything built from a resolved symbol: the `symbol` field
9
+ * we attach to assets, chart titles, cache-file names, Kibana query terms, and
10
+ * strict in-process comparisons such as `assetA === 'CORE'`. That is a
11
11
  * silent-wrong-answer class of bug, not a loud
12
12
  * one, so the conversion is done ONCE here and applied at every boundary that
13
13
  * accepts a pair from a human (CLI prompts, `dexbot tv`/`dw` targets) or hands