dexbot 1.6.14 → 1.6.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +34 -4
  2. package/analysis/README.md +6 -6
  3. package/analysis/tradingview/README.md +2 -1
  4. package/claw/README.md +7 -7
  5. package/claw/package.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  8. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +80 -6
  9. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +36 -2
  10. package/dist/dexbot.js +23 -3
  11. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
  12. package/dist/modules/account_bots.d.ts +3 -0
  13. package/dist/modules/account_bots.js +3 -0
  14. package/dist/modules/bitshares-native/subscriptions.js +1 -1
  15. package/dist/modules/bot_defaults.d.ts +13 -2
  16. package/dist/modules/bot_defaults.js +31 -2
  17. package/dist/modules/bot_settings.js +3 -0
  18. package/dist/modules/constants.d.ts +6 -0
  19. package/dist/modules/constants.js +24 -0
  20. package/dist/modules/credit_runtime.d.ts +35 -5
  21. package/dist/modules/credit_runtime.js +219 -38
  22. package/dist/modules/dexbot_class.d.ts +19 -1
  23. package/dist/modules/dexbot_class.js +58 -20
  24. package/dist/modules/dexbot_cow_runtime.js +19 -18
  25. package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
  26. package/dist/modules/dexbot_fill_runtime.js +4 -7
  27. package/dist/modules/dexbot_maintenance_runtime.d.ts +7 -2
  28. package/dist/modules/dexbot_maintenance_runtime.js +52 -7
  29. package/dist/modules/dexbot_startup_runtime.js +3 -2
  30. package/dist/modules/dexbot_state_recovery.js +1 -1
  31. package/dist/modules/order/export.js +2 -2
  32. package/dist/modules/order/grid.d.ts +118 -1
  33. package/dist/modules/order/grid.js +292 -50
  34. package/dist/modules/order/grid_reconcile.js +4 -3
  35. package/dist/modules/order/grid_reconcile_internal.js +13 -18
  36. package/dist/modules/order/index.d.ts +3 -1
  37. package/dist/modules/order/manager.d.ts +1 -0
  38. package/dist/modules/order/manager.js +5 -14
  39. package/dist/modules/order/sync_engine.js +18 -9
  40. package/dist/modules/order/utils/math.d.ts +98 -26
  41. package/dist/modules/order/utils/math.js +177 -57
  42. package/dist/modules/order/utils/order.js +16 -4
  43. package/dist/modules/order/utils/system.js +2 -2
  44. package/dist/modules/order/utils/validate.d.ts +1 -1
  45. package/dist/modules/order/utils/validate.js +48 -58
  46. package/dist/modules/types.d.ts +7 -0
  47. package/dist/scripts/analyze-credit.js +44 -27
  48. package/dist/scripts/diagnose-pool-history.js +35 -30
  49. package/dist/scripts/pnl.js +1 -1
  50. package/dist/scripts/rich_list.d.ts +18 -0
  51. package/dist/scripts/rich_list.js +461 -0
  52. package/dist/scripts/run-tests.js +80 -4
  53. package/dist/unlock.d.ts +2 -1
  54. package/dist/unlock.js +4 -3
  55. package/docs/COW_INVARIANTS.md +6 -0
  56. package/docs/DEXBOT_COMPARISON.md +6 -6
  57. package/docs/EVOLUTION.md +10 -9
  58. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  59. package/docs/LOGGING.md +16 -1
  60. package/docs/MPA_CREDIT_USAGE.md +10 -5
  61. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +159 -9
  62. package/docs/README.md +1 -1
  63. package/docs/WORKFLOW.md +1 -0
  64. package/docs/architecture.md +56 -2
  65. package/docs/developer_guide.md +5 -1
  66. package/market_adapter/README.md +4 -4
  67. package/modules/README.md +1 -1
  68. package/package.json +2 -1
  69. package/scripts/README.md +59 -32
  70. package/tests/README.md +11 -2
@@ -121,6 +121,193 @@ function classifySpreadStall(c) {
121
121
  return hint;
122
122
  return 'no-candidates';
123
123
  }
124
+ /**
125
+ * Spread-correction refusal causes — the single vocabulary shared by
126
+ * classifySpreadRefusalCause, the retry/transience decision and the
127
+ * spreadCorrectionRefusalCauses metric key. Keep every reader/writer keyed off
128
+ * this map so a new cause cannot leave classification and transience out of
129
+ * sync.
130
+ */
131
+ export const SPREAD_CORRECTION_REFUSAL = Object.freeze({
132
+ /** Post-broadcast working-grid commit rejected (orders may already be on chain). */
133
+ COMMIT_REFUSED: 'commit-refused',
134
+ /** Plan went stale / skipped before broadcast (base-version mismatch). */
135
+ VERSION_MISMATCH: 'version-mismatch',
136
+ /** A tracked UPDATE target was gone on chain (COW pre-broadcast guard). */
137
+ UPDATE_TARGET_MISSING: 'update-target-missing',
138
+ /** Destination slot already held an active order (plan-time dedupe). */
139
+ CREATE_COLLISION: 'create-collision',
140
+ /** Unmatched chain orders blocked the CREATE batch. */
141
+ UNMATCHED_CHAIN_ORDERS: 'unmatched-chain-orders',
142
+ /** Shutdown began while the batch was in flight. */
143
+ SHUTDOWN: 'shutdown',
144
+ /** Unclassified non-execution (fallback). */
145
+ BATCH_NOT_EXECUTED: 'batch-not-executed'
146
+ });
147
+ /**
148
+ * Causes the bounded in-cycle re-plan can heal. `commit-refused` is deliberately
149
+ * EXCLUDED: the batch reached the chain (chain adoption runs), so it is not a
150
+ * clean pre-broadcast staleness a fresh-master re-plan repairs — it should count
151
+ * toward the persistent-stale watchdog instead.
152
+ */
153
+ const TRANSIENT_SPREAD_CORRECTION_REFUSALS = new Set([
154
+ SPREAD_CORRECTION_REFUSAL.VERSION_MISMATCH,
155
+ SPREAD_CORRECTION_REFUSAL.CREATE_COLLISION,
156
+ SPREAD_CORRECTION_REFUSAL.BATCH_NOT_EXECUTED
157
+ ]);
158
+ /**
159
+ * Whether a refusal cause is retryable by the bounded spread-correction re-plan.
160
+ * @param {string} cause - A SPREAD_CORRECTION_REFUSAL value
161
+ * @returns {boolean}
162
+ */
163
+ export function isTransientSpreadRefusal(cause) {
164
+ return TRANSIENT_SPREAD_CORRECTION_REFUSALS.has(cause);
165
+ }
166
+ /**
167
+ * P0 observability: classify WHY a spread-correction batch did not land
168
+ * (executed !== true) from the COW batch result. Counter-only — never gates
169
+ * placement. Returns a SPREAD_CORRECTION_REFUSAL value so the metric key, the
170
+ * retry decision and the log all share one vocabulary.
171
+ * @param {Object|null} batchResult - The COW batch result
172
+ * @returns {string} A SPREAD_CORRECTION_REFUSAL value
173
+ */
174
+ export function classifySpreadRefusalCause(batchResult) {
175
+ const r = (batchResult ?? {});
176
+ const reason = String(r.reason ?? '').toUpperCase();
177
+ if (r.commitRefused === true)
178
+ return SPREAD_CORRECTION_REFUSAL.COMMIT_REFUSED;
179
+ if (reason === 'UPDATE_TARGET_MISSING')
180
+ return SPREAD_CORRECTION_REFUSAL.UPDATE_TARGET_MISSING;
181
+ if (reason === 'UNMATCHED_CHAIN_ORDERS')
182
+ return SPREAD_CORRECTION_REFUSAL.UNMATCHED_CHAIN_ORDERS;
183
+ if (reason === 'SHUTDOWN_IN_PROGRESS')
184
+ return SPREAD_CORRECTION_REFUSAL.SHUTDOWN;
185
+ if (r.skippedStalePlan === true || reason.includes('STALE') || reason.includes('MISMATCH') || reason.includes('BASE VERSION'))
186
+ return SPREAD_CORRECTION_REFUSAL.VERSION_MISMATCH;
187
+ if (reason.includes('COLLISION') || reason.includes('EXISTING') || reason.includes('DUPLICATE'))
188
+ return SPREAD_CORRECTION_REFUSAL.CREATE_COLLISION;
189
+ return SPREAD_CORRECTION_REFUSAL.BATCH_NOT_EXECUTED;
190
+ }
191
+ /**
192
+ * P0 observability: record a spread-correction refusal on the manager's
193
+ * metrics (the only object reachable from this planner; getMetrics overlays
194
+ * these onto the bot's counters). Counter-only; never throws, never gates.
195
+ * @param {Object} manager - OrderManager instance
196
+ * @param {string} cause - A SPREAD_CORRECTION_REFUSAL value
197
+ */
198
+ export function recordSpreadCorrectionRefusal(manager, cause) {
199
+ try {
200
+ const m = manager?._metrics;
201
+ if (!m)
202
+ return;
203
+ m.spreadCorrectionRefusedCount = (Number(m.spreadCorrectionRefusedCount) || 0) + 1;
204
+ const causes = (m.spreadCorrectionRefusalCauses && typeof m.spreadCorrectionRefusalCauses === 'object')
205
+ ? m.spreadCorrectionRefusalCauses
206
+ : (m.spreadCorrectionRefusalCauses = {});
207
+ causes[cause] = (Number(causes[cause]) || 0) + 1;
208
+ }
209
+ catch { /* metrics are best-effort */ }
210
+ }
211
+ /**
212
+ * P5 observability: count a bounded spread-correction re-plan retry. Churn
213
+ * signal — a rising retry rate means concurrent commits are repeatedly
214
+ * invalidating corrections. Counter-only; never throws.
215
+ * @param {Object} manager - OrderManager instance
216
+ */
217
+ export function recordSpreadCorrectionRetry(manager) {
218
+ try {
219
+ const m = manager?._metrics;
220
+ if (!m)
221
+ return;
222
+ m.spreadCorrectionRetryCount = (Number(m.spreadCorrectionRetryCount) || 0) + 1;
223
+ }
224
+ catch { /* metrics are best-effort */ }
225
+ }
226
+ /**
227
+ * P2 plan-time dedupe: which of a correction's planned CREATE destinations are
228
+ * now occupied by a live (ACTIVE/PARTIAL) order with a chain id?
229
+ *
230
+ * The correction is planned under _gridLock, then broadcast after the lock is
231
+ * released. A concurrent fill rebalance can commit an order onto one of the
232
+ * planned slots in that window; the COW build layer then rejects the whole
233
+ * batch (`Rejecting CREATE … existing orderId`). Detecting it here turns that
234
+ * into a cheap plan-time re-derive (see the retry loop in checkSpreadCondition)
235
+ * instead of a mid-broadcast refusal and structural resync.
236
+ *
237
+ * Pure and never throws. A missing/non-Map orders store selects the empty set.
238
+ * @param {Object} manager - OrderManager instance
239
+ * @param {Object|null} correction - Prepared spread correction
240
+ * @returns {string[]} Occupied planned slot ids
241
+ */
242
+ export function getOccupiedCorrectionSlots(manager, correction) {
243
+ const occupied = [];
244
+ try {
245
+ const orders = manager.orders;
246
+ if (!(orders instanceof Map) || !correction)
247
+ return occupied;
248
+ for (const o of correction.ordersToPlace || []) {
249
+ const cur = orders.get(o.id);
250
+ if (!cur)
251
+ continue;
252
+ const liveState = cur.state === ORDER_STATES.ACTIVE || cur.state === ORDER_STATES.PARTIAL;
253
+ if (liveState && cur.orderId)
254
+ occupied.push(o.id);
255
+ }
256
+ }
257
+ catch { /* best-effort detection */ }
258
+ return occupied;
259
+ }
260
+ /**
261
+ * P1/P3 shared re-plan: derive a spread correction from the CURRENT master
262
+ * state (side chosen from fresh on-chain book, opposite-side starvation
263
+ * fallback). Used both for the plan-time collision dedupe and the bounded
264
+ * refusal retry. Read-only against the grid; no _gridLock needed (matches the
265
+ * existing TOCTOU fund re-plan contract).
266
+ * @param {Object} manager - OrderManager instance
267
+ * @returns {Promise<Object|null>} A correction with at least one create, or null
268
+ */
269
+ export async function replanSpreadCorrectionFromFreshMaster(manager) {
270
+ const freshOnChain = _getOnChainOrders(manager);
271
+ const freshBest = getGridBestPrices(freshOnChain.onChainBuys, freshOnChain.onChainSells);
272
+ const freshPrice = (freshBest.bestBuy !== null && freshBest.bestSell !== null)
273
+ ? (freshBest.bestBuy + freshBest.bestSell) / 2
274
+ : Number(manager.config.startPrice) || 0;
275
+ const decision = determineOrderSideByFunds(manager, freshPrice);
276
+ if (!decision.side)
277
+ return null;
278
+ let c = await prepareSpreadCorrectionOrders(manager, decision.side, manager.outOfSpread);
279
+ if ((c?.ordersToPlace?.length || 0) === 0) {
280
+ const opposite = decision.side === ORDER_TYPES.BUY ? ORDER_TYPES.SELL : ORDER_TYPES.BUY;
281
+ const oc = await prepareSpreadCorrectionOrders(manager, opposite, manager.outOfSpread);
282
+ if ((oc?.ordersToPlace?.length || 0) > 0)
283
+ c = oc;
284
+ }
285
+ return c;
286
+ }
287
+ /**
288
+ * P2: resolve a planned correction whose CREATE destination(s) were taken after
289
+ * planning. Detects the collision, re-derives once from fresh master, and
290
+ * reports whether the caller should broadcast, swap in the re-plan, or refuse.
291
+ *
292
+ * Extracted from checkSpreadCondition so the branch is a real, production-called
293
+ * unit that tests can drive directly (no test-only hook in the production path).
294
+ *
295
+ * @param {Object} manager - OrderManager instance
296
+ * @param {Object|null} correction - The plan about to broadcast
297
+ * @param {number} attempt - 1-based attempt index
298
+ * @param {number} maxAttempts - Total attempts allowed
299
+ * @returns {Promise<OccupiedCorrectionResolution>}
300
+ */
301
+ export async function resolveOccupiedCorrection(manager, correction, attempt, maxAttempts) {
302
+ const occupied = getOccupiedCorrectionSlots(manager, correction);
303
+ if (!(occupied.length > 0 && attempt < maxAttempts))
304
+ return { action: 'broadcast' };
305
+ const replanned = await replanSpreadCorrectionFromFreshMaster(manager);
306
+ if (replanned && (replanned.ordersToPlace?.length || 0) > 0) {
307
+ return { action: 'replanned', correction: replanned, occupied };
308
+ }
309
+ return { action: 'blocked', occupied };
310
+ }
124
311
  /**
125
312
  * Central resolution for the RMS structural-divergence threshold (percent).
126
313
  * Single source of truth: per-bot override wins, global GRID_COMPARISON default
@@ -141,7 +328,7 @@ function _snapshotFundState(manager) {
141
328
  sellLocked: Number(manager.accountTotals?.sellLocked || 0),
142
329
  };
143
330
  }
144
- import { floatToBlockchainInt, getPrecisionByOrderType, getPrecisionsForManager, calculateOrderCreationFees, calculateOrderSizes, calculateRotationOrderSizes, calculateAvailableFundsValue, calculateGridSideDivergenceMetric, getPrecisionSlack, getMinOrderSize, getSingleDustThreshold, getGridBestPrices, calculateSpreadFromOrders, allocateFundsByWeights, calculateGapSlots as _mathGapSlots, priceSlotEqual, getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, validatePersistedBoundary, isTransientInBandRejection, adjustBudgetForBtsFees, clamp, derivePriceLevels, buildGenesisFromPriceLevels, assertSlotPriceInvariant, priceForSlot, hashPriceLevels, } from './utils/math.js';
331
+ import { floatToBlockchainInt, getPrecisionByOrderType, getPrecisionsForManager, calculateOrderCreationFees, calculateOrderSizes, calculateRotationOrderSizes, calculateAvailableFundsValue, calculateGridSideDivergenceMetric, getPrecisionSlack, getMinOrderSize, getSingleDustThreshold, getGridBestPrices, calculateSpreadFromOrders, allocateFundsByWeights, calculateGapSlots as _mathGapSlots, pricesOnSameLevel, sameGridLevel, getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, validatePersistedBoundary, isTransientInBandRejection, adjustBudgetForBtsFees, clamp, derivePriceLevels, buildGenesisFromPriceLevels, assertSlotPriceInvariant, priceForSlot, hashPriceLevels, } from './utils/math.js';
145
332
  import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, parseSlotIndex, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, resolveEdgeCount, edgeOrderIdSet, resolveLiveEdgeAnchorPrice, liveWindowIdSet, getOrderTypeFromUpdatedFlags } from './utils/order.js';
146
333
  import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot, evaluateSpreadCorrectionReadiness, maybeRefreshLiveMarketPrice } from './utils/system.js';
147
334
  import * as MathUtils from './utils/math.js';
@@ -660,7 +847,7 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
660
847
  // band, GAP-EVAC already tracking it): keep the boundary so
661
848
  // the heal path (rotation/teeth/sweeps) can run. Nuking it
662
849
  // here would discard the evacuation state for exactly the
663
- // condition evacuation exists to fix (H-BTS 2026-09-13).
850
+ // condition evacuation exists to fix (<bot> 2026-09-13).
664
851
  manager.logger?.log?.(`[GRID-LOAD] Persisted snapshot has transient in-band placement (${check.reason}): ${check.detail}. ` +
665
852
  `Keeping boundary ${restoredBoundary}; GAP-EVAC/sync sweeps own cleanup.`, 'warn');
666
853
  }
@@ -2404,12 +2591,15 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2404
2591
  // Pre-flight fund verification mitigates TOCTOU between lock release and broadcast.
2405
2592
  if (shouldApplyCorrection && updateOrdersOnChainBatch && correction && fundSnapshot) {
2406
2593
  let activeCorrection = correction;
2407
- let activeSnapshot = fundSnapshot;
2594
+ // Explicit non-null alias: fundSnapshot is assigned inside the
2595
+ // executeSpreadCheck closure, so TS control-flow cannot prove it
2596
+ // non-null here even though the guard above checked it.
2597
+ const baseFundSnapshot = fundSnapshot;
2408
2598
  const currentFunds = _snapshotFundState(manager);
2409
- const fundChanged = activeSnapshot.buyFree !== currentFunds.buyFree
2410
- || activeSnapshot.sellFree !== currentFunds.sellFree
2411
- || activeSnapshot.buyLocked !== currentFunds.buyLocked
2412
- || activeSnapshot.sellLocked !== currentFunds.sellLocked;
2599
+ const fundChanged = baseFundSnapshot.buyFree !== currentFunds.buyFree
2600
+ || baseFundSnapshot.sellFree !== currentFunds.sellFree
2601
+ || baseFundSnapshot.buyLocked !== currentFunds.buyLocked
2602
+ || baseFundSnapshot.sellLocked !== currentFunds.sellLocked;
2413
2603
  if (fundChanged) {
2414
2604
  // TOCTOU: fund state changed between lock release and broadcast.
2415
2605
  // Lock-free re-plan — no _gridLock needed because the fund read
@@ -2436,7 +2626,6 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2436
2626
  const rePlanCorrection = await prepareSpreadCorrectionOrders(manager, rePlanDecision.side, manager.outOfSpread);
2437
2627
  if (rePlanCorrection && (rePlanCorrection.ordersToPlace?.length || 0) > 0) {
2438
2628
  activeCorrection = rePlanCorrection;
2439
- activeSnapshot = currentFunds;
2440
2629
  manager.logger?.log?.(`[SPREAD] Fund state changed between lock release and broadcast — ` +
2441
2630
  `re-planned with updated funds: ${activeCorrection.ordersToPlace?.length || 0} creates`, 'info');
2442
2631
  }
@@ -2450,23 +2639,86 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2450
2639
  return { ordersPlaced: 0, partialsMoved: 0, stall };
2451
2640
  }
2452
2641
  }
2642
+ // P1: hold the broadcast/placement region across the whole attempt
2643
+ // loop (re-plan + broadcast). A defer-if-broadcasting fill rebalance
2644
+ // yields while this region is held, and a waiting one parks on
2645
+ // _awaitBroadcastIdle, so a concurrent commit is far less likely to
2646
+ // bump master between this correction's plan and its broadcast — the
2647
+ // race that made the commit guard refuse the batch. This narrows the
2648
+ // window rather than closing it absolutely (the idle wait is bounded
2649
+ // and proceeds on timeout), so the commit guard stays the backstop
2650
+ // and the retry below re-plans from fresh master. The COW batch
2651
+ // refcounts the region internally; this is the outer holder.
2652
+ const MAX_SPREAD_ATTEMPTS = Number(TIMING?.SPREAD_CORRECTION_MAX_ATTEMPTS) > 0
2653
+ ? Number(TIMING.SPREAD_CORRECTION_MAX_ATTEMPTS)
2654
+ : 2;
2655
+ let attempts = 0;
2656
+ // Whether the most recent refusal is retryable — reported to the P4
2657
+ // watchdog so a non-transient cause (commit-refused /
2658
+ // update-target-missing) counts toward staleness instead of being
2659
+ // waved through as a retry. Defaults to transient for the P2
2660
+ // collision-blocked path, which has no batch result.
2661
+ let lastTransient = true;
2662
+ let lastResult = null;
2663
+ const canHoldRegion = typeof manager.startBroadcasting === 'function'
2664
+ && typeof manager.stopBroadcasting === 'function';
2665
+ if (canHoldRegion)
2666
+ manager.startBroadcasting();
2453
2667
  try {
2454
- const batchResult = await updateOrdersOnChainBatch(activeCorrection);
2455
- if (!batchResult || batchResult.executed !== true) {
2456
- manager.logger?.log?.(`Spread correction batch was prepared but not executed. Keeping local state unchanged.`, 'warn');
2457
- // Nothing landed: ask the caller to refresh account totals +
2458
- // open orders (stale holds/balances can make the same plan
2459
- // re-derive every cycle).
2460
- return { ordersPlaced: 0, partialsMoved: 0, stall: 'batch-not-executed' };
2668
+ while (attempts < MAX_SPREAD_ATTEMPTS) {
2669
+ attempts++;
2670
+ // P2: before broadcasting, detect a planned CREATE whose
2671
+ // destination was taken by a competing batch after planning,
2672
+ // and re-derive instead of shipping a known collision.
2673
+ const resolution = await resolveOccupiedCorrection(manager, activeCorrection, attempts, MAX_SPREAD_ATTEMPTS);
2674
+ if (resolution.action !== 'broadcast') {
2675
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Plan-time dedupe: ${resolution.occupied.length} planned slot(s) occupied since planning ` +
2676
+ `(${resolution.occupied.slice(0, 8).join(', ')}${resolution.occupied.length > 8 ? ', …' : ''}); ` +
2677
+ (resolution.action === 'replanned' ? 're-planning from fresh master' : 'no re-plan candidate — refusing this cycle'), 'warn');
2678
+ recordSpreadCorrectionRefusal(manager, SPREAD_CORRECTION_REFUSAL.CREATE_COLLISION);
2679
+ if (resolution.action === 'replanned') {
2680
+ recordSpreadCorrectionRetry(manager);
2681
+ activeCorrection = resolution.correction;
2682
+ continue;
2683
+ }
2684
+ break;
2685
+ }
2686
+ const batchResult = await updateOrdersOnChainBatch(activeCorrection);
2687
+ lastResult = batchResult ?? null;
2688
+ if (batchResult && batchResult.executed === true) {
2689
+ await manager.recalculateFunds();
2690
+ const placed = activeCorrection.ordersToPlace?.length || 0;
2691
+ return { ordersPlaced: placed, partialsMoved: 0 };
2692
+ }
2693
+ const cause = classifySpreadRefusalCause(batchResult);
2694
+ recordSpreadCorrectionRefusal(manager, cause);
2695
+ const transient = isTransientSpreadRefusal(cause);
2696
+ lastTransient = transient;
2697
+ if (!transient || attempts >= MAX_SPREAD_ATTEMPTS)
2698
+ break;
2699
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Batch refused (${cause}); re-planning from fresh master ` +
2700
+ `(attempt ${attempts + 1}/${MAX_SPREAD_ATTEMPTS})`, 'warn');
2701
+ const replanned = await replanSpreadCorrectionFromFreshMaster(manager);
2702
+ if (!replanned || (replanned.ordersToPlace?.length || 0) === 0)
2703
+ break;
2704
+ recordSpreadCorrectionRetry(manager);
2705
+ activeCorrection = replanned;
2461
2706
  }
2462
- await manager.recalculateFunds();
2463
- const placed = activeCorrection.ordersToPlace?.length || 0;
2464
- return { ordersPlaced: placed, partialsMoved: 0 };
2465
2707
  }
2466
2708
  catch (err) {
2467
2709
  manager.logger?.log?.(`Error applying spread correction on-chain: ${getErrorMessage(err)}`, 'warn');
2468
2710
  return { ordersPlaced: 0, partialsMoved: 0, stall: 'apply-error' };
2469
2711
  }
2712
+ finally {
2713
+ if (canHoldRegion)
2714
+ manager.stopBroadcasting();
2715
+ }
2716
+ manager.logger?.log?.(`Spread correction batch was prepared but not executed. Keeping local state unchanged.` +
2717
+ (lastResult ? ` (cause=${classifySpreadRefusalCause(lastResult)})` : ''), 'warn');
2718
+ // Retryable only when the last refusal cause was transient; a
2719
+ // commit-refused / update-target-missing / unmatched / shutdown
2720
+ // refusal counts toward the persistent-stale watchdog.
2721
+ return { ordersPlaced: 0, partialsMoved: 0, stall: 'batch-not-executed', transient: lastTransient };
2470
2722
  }
2471
2723
  return { ordersPlaced: 0, partialsMoved: 0, stall };
2472
2724
  }
@@ -2533,26 +2785,24 @@ export async function checkWindowDust(manager) {
2533
2785
  const topSellOrder = allOrders
2534
2786
  .filter((o) => o.type === ORDER_TYPES.SELL && isLiveOrder(o))
2535
2787
  .sort((a, b) => a.price - b.price)[0];
2536
- // Check if an order has a duplicate slot — an active sibling with same price via integer round-trip.
2537
- const hasDuplicatePriceLevel = (order, assets) => {
2538
- const precision = order.type === ORDER_TYPES.SELL ? assets.assetA.precision : assets.assetB.precision;
2788
+ // Check if an order has a duplicate price level — an active sibling at
2789
+ // the same ladder level. If so, cancelling won't create a grid gap.
2790
+ // Only checks ACTIVE siblings. If two PARTIALs share a price with no active
2791
+ // sibling, neither qualifies and the gap is left to the rebalancer.
2792
+ // Grid-vs-grid: resolve both prices to their frozen ladder level
2793
+ // (genesis-aware), NOT priceSlotEqual at the asset precision (collapses
2794
+ // adjacent levels for a low-precision asset).
2795
+ const hasDuplicatePriceLevel = (order) => {
2539
2796
  for (const o of allOrders) {
2540
2797
  if (o.id === order.id)
2541
2798
  continue;
2542
2799
  if (o.type !== order.type || o.state !== ORDER_STATES.ACTIVE || !o.orderId || o.price == null)
2543
2800
  continue;
2544
- try {
2545
- if (priceSlotEqual(o.price, order.price, precision))
2546
- return true;
2547
- }
2548
- catch {
2549
- if (o.price === order.price)
2550
- return true;
2551
- }
2801
+ if (sameGridLevel(o.price, order.price, manager._genesis))
2802
+ return true;
2552
2803
  }
2553
2804
  return false;
2554
2805
  };
2555
- const assets = manager.assets;
2556
2806
  const allPartials = allOrders.filter((o) => isLiveOrder(o) && o.state === ORDER_STATES.PARTIAL);
2557
2807
  const isTopBuy = (o) => !!(topBuyOrder && o.id === topBuyOrder.id);
2558
2808
  const isTopSell = (o) => !!(topSellOrder && o.id === topSellOrder.id);
@@ -2583,8 +2833,8 @@ export async function checkWindowDust(manager) {
2583
2833
  // only cancels zero-value residuals, and an interior dust rarely has a
2584
2834
  // duplicate price level. Cancelling it frees the slot for rotation to
2585
2835
  // re-derive, so the tiny gap is closed by normal grid rebalancing.
2586
- const eligibleBuyPartials = allPartials.filter((o) => o.type === ORDER_TYPES.BUY && (isTopBuy(o) || hasDuplicatePriceLevel(o, assets) || isDustSized(o, buyThresholds)));
2587
- const eligibleSellPartials = allPartials.filter((o) => o.type === ORDER_TYPES.SELL && (isTopSell(o) || hasDuplicatePriceLevel(o, assets) || isDustSized(o, sellThresholds)));
2836
+ const eligibleBuyPartials = allPartials.filter((o) => o.type === ORDER_TYPES.BUY && (isTopBuy(o) || hasDuplicatePriceLevel(o) || isDustSized(o, buyThresholds)));
2837
+ const eligibleSellPartials = allPartials.filter((o) => o.type === ORDER_TYPES.SELL && (isTopSell(o) || hasDuplicatePriceLevel(o) || isDustSized(o, sellThresholds)));
2588
2838
  const buyDustOrders = await _getDustOrders(manager, eligibleBuyPartials, ORDER_TYPES.BUY, buyThresholds);
2589
2839
  const sellDustOrders = await _getDustOrders(manager, eligibleSellPartials, ORDER_TYPES.SELL, sellThresholds);
2590
2840
  return {
@@ -3019,15 +3269,10 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3019
3269
  const doesNotCollideUnmatched = (c) => {
3020
3270
  if (unmatchedPrices.length === 0 || c?.price == null || !Number.isFinite(c.price))
3021
3271
  return true;
3022
- const precision = railType === ORDER_TYPES.SELL ? manager.assets.assetA.precision : manager.assets.assetB.precision;
3023
- return !unmatchedPrices.some((p) => {
3024
- try {
3025
- return priceSlotEqual(p, c.price, precision);
3026
- }
3027
- catch {
3028
- return Math.abs(p - c.price) / c.price <= ((manager.config.incrementPercent ?? 0) / 100);
3029
- }
3030
- });
3272
+ // The unmatched row carries only a price; use the candidate's own
3273
+ // side/size for the tolerance. Tolerance-based, NOT priceSlotEqual at
3274
+ // the asset precision (low-precision assets collapse adjacent levels).
3275
+ return !unmatchedPrices.some((p) => pricesOnSameLevel(p, c.size, railType, c.price, c.size, railType, manager.assets, manager.config?.incrementPercent));
3031
3276
  };
3032
3277
  if (unmatchedPrices.length > 0) {
3033
3278
  manager.logger?.log?.(`[SPREAD-CORRECTION] ${unmatchedPrices.length} known-unmatched chain price level(s) excluded from ${sideName} candidates — sync will adopt them first`, 'warn');
@@ -3204,20 +3449,17 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3204
3449
  spreadCandidates = spreadCandidates.filter((c) => {
3205
3450
  if (c.price == null)
3206
3451
  return false;
3207
- const precision = railType === ORDER_TYPES.SELL ? manager.assets.assetA.precision : manager.assets.assetB.precision;
3452
+ // Grid-vs-grid: resolve both prices to their frozen ladder
3453
+ // level (genesis-aware), NOT priceSlotEqual at the asset
3454
+ // precision and NOT the chain tolerance (both can
3455
+ // collapse/merge adjacent grid levels).
3208
3456
  for (const o of allOrders) {
3209
3457
  if (!isOrderPlaced(o) || o.price == null)
3210
3458
  continue;
3211
3459
  if (o.id === c.id)
3212
3460
  continue;
3213
- try {
3214
- if (priceSlotEqual(o.price, c.price, precision))
3215
- return false;
3216
- }
3217
- catch {
3218
- if (o.price === c.price)
3219
- return false;
3220
- }
3461
+ if (sameGridLevel(o.price, c.price, manager._genesis))
3462
+ return false;
3221
3463
  }
3222
3464
  return true;
3223
3465
  });
@@ -3,7 +3,7 @@ const require = createRequire(import.meta.url);
3
3
  import { _countActiveOnGrid, _cancelChainOrder, _recoverStartupSyncFailure, _refreshStartupUpdatePlans, _executeStartupUpdateBatch, _executeStartupSequentialUpdateFallback, _executePlannedStartupCreates, _reconcileStartupSide, } from './grid_reconcile_internal.js';
4
4
  import { ORDER_TYPES, ORDER_STATES, TIMING } from '../constants.js';
5
5
  import { readOpenOrdersGuarded } from '../chain_orders.js';
6
- import { getAssetFeesSafe, priceSlotEqual } from './utils/math.js';
6
+ import { getAssetFeesSafe, pricesOnSameLevel } from './utils/math.js';
7
7
  import { isOrderPlaced, parseChainOrder, isOrderOnChain, findLiveOrderOwnerByChainId, chainOrderMatchesSlotWithTolerance, duplicateOrphanLogInfo, resolveEdgeCount, } from './utils/order.js';
8
8
  import * as Format from './format.js';
9
9
  import { getErrorMessage } from '../utils/errors.js';
@@ -251,8 +251,9 @@ export async function reconcileGridOrders({ manager, config, account, privateKey
251
251
  for (const gridOrder of activeGridOrders) {
252
252
  if (gridOrder.type !== p.type)
253
253
  continue;
254
- const precision = p.type === ORDER_TYPES.SELL ? manager.assets.assetA.precision : manager.assets.assetB.precision;
255
- const isEqual = priceSlotEqual(p.price, gridOrder.price, precision);
254
+ // Tolerance-based level check, NOT priceSlotEqual at the asset
255
+ // precision (a low-precision asset collapses adjacent levels).
256
+ const isEqual = pricesOnSameLevel(p.price, p.size ?? 0, p.type, gridOrder.price, gridOrder.size, gridOrder.type, manager.assets, manager.config?.incrementPercent);
256
257
  const priceDiff = Math.abs(p.price - gridOrder.price);
257
258
  const candidate = { gridOrder, priceDiff, isEqual };
258
259
  if (!nearest || priceDiff < nearest.priceDiff)
@@ -6,17 +6,22 @@
6
6
  */
7
7
  import { ORDER_TYPES, ORDER_STATES, TIMING, BTS_PRECISION } from '../constants.js';
8
8
  import { readOpenOrdersGuarded } from '../chain_orders.js';
9
- import { getMinOrderSize, getAssetFees, getAssetFeesSafe, blockchainToFloat, findCrossedOrder, resolveGapBand, isSlotInRail, priceSlotEqual } from './utils/math.js';
9
+ import { getMinOrderSize, getAssetFees, getAssetFeesSafe, blockchainToFloat, findCrossedOrder, resolveGapBand, isSlotInRail, pricesOnSameLevel, sameGridLevel } from './utils/math.js';
10
10
  import { isOrderPlaced, parseChainOrder, buildCreateOrderArgs, buildOutsideInPairGroups, extractBatchOperationResults, chainOrderMatchesSlotWithTolerance, buildCrossingCheckCandidates, isCrossingCheckCandidate, getSideBudget, calculateBudgetedSizes, getCoreOrdersTotal, convertToSpreadPlaceholder, isOrderGoneErrorMessage, clearDuplicateOrphanDetection, resolveEdgeCount, resolveLiveEdgeAnchorPrice, edgeOrderIdSet, compareEdge, parseSlotIndex, reportGridPriceInvariant, liveWindowIdSet } from './utils/order.js';
11
11
  import { resolveAccountRef } from './utils/system.js';
12
12
  import * as Format from './format.js';
13
13
  import { getErrorMessage, getErrorCode, getErrorName } from '../utils/errors.js';
14
14
  function computePlacementPriceCollision(manager, gridOrder) {
15
- const precision = gridOrder.type === ORDER_TYPES.SELL ? manager.assets.assetA.precision : manager.assets.assetB.precision;
15
+ // Grid-vs-grid: resolve each price to its frozen ladder level. NOT
16
+ // priceSlotEqual at the asset precision, which rounds a price through an
17
+ // asset AMOUNT precision and collapses an adjacent band for a
18
+ // low-precision asset (0.000318 and 0.000319 both -> 3 at precision 4,
19
+ // silently dropping every buy after the first). NOT the chain tolerance
20
+ // either: it can exceed the grid increment and merge adjacent levels.
16
21
  for (const o of manager.orders.values()) {
17
22
  if (!isOrderPlaced(o) || o.id === gridOrder.id)
18
23
  continue;
19
- if (priceSlotEqual(o.price, gridOrder.price, precision))
24
+ if (sameGridLevel(o.price, gridOrder.price, manager._genesis))
20
25
  return o;
21
26
  }
22
27
  return null;
@@ -1463,7 +1468,6 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
1463
1468
  if (!Number.isFinite(Number(chainPrice)))
1464
1469
  return;
1465
1470
  const chainPriceNum = Number(chainPrice);
1466
- const sidePrecision = orderType === ORDER_TYPES.SELL ? manager.assets?.assetA?.precision : manager.assets?.assetB?.precision;
1467
1471
  for (const slotOrder of manager.orders.values()) {
1468
1472
  if (!slotOrder || !slotOrder.id)
1469
1473
  continue;
@@ -1487,7 +1491,7 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
1487
1491
  continue;
1488
1492
  if (Number(slotOrder.size) <= 0)
1489
1493
  continue;
1490
- if (!priceSlotEqual(slotOrder.price, chainPriceNum, sidePrecision))
1494
+ if (!pricesOnSameLevel(slotOrder.price, slotOrder.size, orderType, chainPriceNum, slotOrder.size, orderType, manager.assets, manager.config?.incrementPercent))
1491
1495
  continue;
1492
1496
  vacatedRefillPlanned.add(slotOrder.id);
1493
1497
  refillCandidates.push(slotOrder);
@@ -1638,29 +1642,20 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
1638
1642
  // Edge ladder: edge-priced orphans cancel last (they are adoption
1639
1643
  // candidates at edge prices, not first-to-cut).
1640
1644
  if (edgeOrderIds && edgeOrderIds.size > 0) {
1641
- const sidePrecision = orderType === ORDER_TYPES.SELL
1642
- ? manager.assets?.assetA?.precision
1643
- : manager.assets?.assetB?.precision;
1644
1645
  const edgePrices = [];
1645
1646
  for (const eid of edgeOrderIds) {
1646
1647
  const slot = manager.orders.get(eid);
1647
1648
  if (slot && Number.isFinite(Number(slot.price)))
1648
1649
  edgePrices.push(Number(slot.price));
1649
1650
  }
1650
- const isEdgePriced = (price) => {
1651
+ const isEdgePriced = (price, size) => {
1651
1652
  const p = Number(price);
1653
+ const s = Number(size) || 0;
1652
1654
  if (!Number.isFinite(p))
1653
1655
  return false;
1654
- return edgePrices.some((ep) => {
1655
- try {
1656
- return priceSlotEqual(ep, p, sidePrecision);
1657
- }
1658
- catch {
1659
- return ep === p;
1660
- }
1661
- });
1656
+ return edgePrices.some((ep) => pricesOnSameLevel(ep, s, orderType, p, s, orderType, manager.assets, manager.config?.incrementPercent));
1662
1657
  };
1663
- const parked = parsedUnmatched.filter((x) => isEdgePriced(x.parsed?.price));
1658
+ const parked = parsedUnmatched.filter((x) => isEdgePriced(x.parsed?.price, x.parsed?.size));
1664
1659
  if (parked.length > 0 && parked.length < parsedUnmatched.length) {
1665
1660
  const parkedIds = new Set(parked.map((x) => x.chain?.id));
1666
1661
  parsedUnmatched.sort((a, b) => {
@@ -294,8 +294,9 @@ declare const utils: {
294
294
  getPrecisionSlack: typeof math.getPrecisionSlack;
295
295
  quantumForPrecision: typeof math.quantumForPrecision;
296
296
  calculatePriceTolerance: typeof math.calculatePriceTolerance;
297
- findPriceCollision: typeof math.findPriceCollision;
298
297
  findCrossedOrder: typeof math.findCrossedOrder;
298
+ pricesOnSameLevel: typeof math.pricesOnSameLevel;
299
+ sameGridPrice: typeof math.sameGridPrice;
299
300
  validateOrderAmountsWithinLimits: typeof math.validateOrderAmountsWithinLimits;
300
301
  getMinOrderSize: typeof math.getMinOrderSize;
301
302
  getDustThresholdFactor: typeof math.getDustThresholdFactor;
@@ -323,6 +324,7 @@ declare const utils: {
323
324
  assertSlotPriceInvariant: typeof math.assertSlotPriceInvariant;
324
325
  priceSlotEqual: typeof math.priceSlotEqual;
325
326
  derivePriceLevels: typeof math.derivePriceLevels;
327
+ sameGridLevel: typeof math.sameGridLevel;
326
328
  buildGenesisFromPriceLevels: typeof math.buildGenesisFromPriceLevels;
327
329
  hashPriceLevels: typeof math.hashPriceLevels;
328
330
  isChainPriceOutOfGrid: typeof math.isChainPriceOutOfGrid;
@@ -768,6 +768,7 @@ declare class OrderManager implements OrderManagerLike {
768
768
  ordersPlaced: number;
769
769
  partialsMoved: number;
770
770
  stall?: import("../types.js").SpreadCorrectionStall;
771
+ transient?: boolean;
771
772
  }>;
772
773
  /**
773
774
  * @param {Function} batchCb - Batch callback
@@ -27,7 +27,7 @@ import SyncEngine from './sync_engine.js';
27
27
  import { calculateCurrentSpread, checkSpreadCondition, checkGridHealth } from './grid.js';
28
28
  import * as Format from './format.js';
29
29
  import { ORDER_TYPES, ORDER_STATES, REBALANCE_STATES, TIMING, LOG_LEVEL, PIPELINE_TIMING, COW_PERFORMANCE, COW_ACTIONS, GRID_LIMITS } from '../constants.js';
30
- import { seedBotRuntimeConfig } from '../bot_defaults.js';
30
+ import { seedBotRuntimeConfig, createDefaultBotMetrics } from '../bot_defaults.js';
31
31
  import { getMinOrderSize, computeChainFundTotals, hasValidAccountTotals, resolveConfigValueWithRegistry, isExplicitZeroAllocation, floatToBlockchainInt, validateBoundaryCommit, resolveGapSlots, resolveGapBand, isSlotInRail } from './utils/math.js';
32
32
  import { validateOrder, validateGridForPersistence, validateWorkingGridFunds, checkFundDrift, reconcileGrid, optimizeRebalanceActions, projectTargetToWorkingGrid, buildStateUpdates, buildAbortedResult, buildSuccessResult, evaluateCommit } from './utils/validate.js';
33
33
  import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveEdgeCount, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder } from './utils/order.js';
@@ -599,24 +599,15 @@ class OrderManager {
599
599
  this._lastBoundaryHoldResyncAt = 0;
600
600
  this._gapEvacStreaks = new Map();
601
601
  this._gapEvacCancelQueued = new Set();
602
+ // Shared counters come from the central factory (createDefaultBotMetrics);
603
+ // the manager-owned runtime counters are added on top.
602
604
  this._metrics = {
603
- fillsProcessed: 0,
604
- batchesExecuted: 0,
605
- fillProcessingTimeMs: 0,
606
- lockContentionEvents: 0,
607
- maxQueueDepth: 0,
608
- fundRecalcCount: 0,
605
+ ...createDefaultBotMetrics(),
609
606
  lockAcquisitions: 0,
610
607
  lockContentionSkips: 0,
611
- gridLockContention: 0,
612
608
  spreadRoleConversionBlocked: 0,
613
609
  lastSyncDurationMs: 0,
614
- metricsStartTime: Date.now(),
615
- refusedCommitCount: 0,
616
- orphanFillCreditedCount: 0,
617
- restampBuyAboveAnchorCount: 0,
618
- boundaryDriftExceedsWindowCount: 0,
619
- gapBandPlacementShadowCount: 0
610
+ metricsStartTime: Date.now()
620
611
  };
621
612
  this._bootstrapping = 1;
622
613
  this.logger?.log('[BOOTSTRAP] Started', 'debug');