dexbot 1.6.17 → 1.7.0

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 (156) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +24 -18
  3. package/analysis/README.md +105 -12
  4. package/analysis/ama_fitting/README.md +2 -2
  5. package/analysis/bot_fitting/README.md +3 -3
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/analyze_args.d.ts +2 -1
  10. package/dist/analysis/analyze_dynamic_weight.js +2 -1
  11. package/dist/analysis/analyze_kalman.js +3 -2
  12. package/dist/analysis/analyze_liquidity.d.ts +17 -0
  13. package/dist/analysis/analyze_liquidity.js +325 -0
  14. package/dist/analysis/analyze_regime.js +3 -2
  15. package/dist/analysis/analyze_regime_windows.js +3 -2
  16. package/dist/analysis/analyze_volatility.js +3 -2
  17. package/dist/analysis/fills_source.d.ts +1 -8
  18. package/dist/analysis/fills_source.js +1 -1
  19. package/dist/analysis/grid_correction_check.d.ts +9 -6
  20. package/dist/analysis/grid_correction_check.js +56 -64
  21. package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
  22. package/dist/analysis/liquidity/liquidity_chain.js +178 -0
  23. package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
  24. package/dist/analysis/liquidity/liquidity_chart_generator.js +523 -0
  25. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +141 -0
  26. package/dist/analysis/liquidity/liquidity_depth_model.js +230 -0
  27. package/dist/analysis/liquidity/liquidity_view.d.ts +38 -0
  28. package/dist/analysis/liquidity/liquidity_view.js +55 -0
  29. package/dist/analysis/math_utils.d.ts +1 -1
  30. package/dist/analysis/trade_profitability.d.ts +1 -1
  31. package/dist/analysis/trade_profitability.js +2 -1
  32. package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
  33. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +3 -3
  34. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
  35. package/dist/dexbot.js +74 -169
  36. package/dist/market_adapter/cli_args.d.ts +6 -1
  37. package/dist/market_adapter/cli_args.js +16 -2
  38. package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
  39. package/dist/market_adapter/core/kibana_candles.js +3 -1
  40. package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
  41. package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
  42. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
  43. package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
  44. package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
  45. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  46. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
  47. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
  48. package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
  49. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
  50. package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
  51. package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
  52. package/dist/market_adapter/inputs/window_cache.js +14 -1
  53. package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
  54. package/dist/market_adapter/lp_chart_runner.js +3 -1
  55. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
  56. package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
  57. package/dist/market_adapter/market_adapter.d.ts +10 -2
  58. package/dist/market_adapter/market_adapter.js +10 -11
  59. package/dist/market_adapter/utils/chain.d.ts +2 -3
  60. package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
  61. package/dist/market_adapter/utils/file_json_cache.js +3 -1
  62. package/dist/market_adapter/utils/file_lock.js +1 -1
  63. package/dist/market_adapter/utils/native_history.d.ts +7 -3
  64. package/dist/market_adapter/utils/native_history.js +3 -1
  65. package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
  66. package/dist/modules/asset_lookup.d.ts +25 -0
  67. package/dist/modules/asset_lookup.js +75 -0
  68. package/dist/modules/bots_file_lock.d.ts +2 -2
  69. package/dist/modules/bots_file_lock.js +2 -2
  70. package/dist/modules/chain_scan.d.ts +64 -0
  71. package/dist/modules/chain_scan.js +80 -0
  72. package/dist/modules/cli_colors.d.ts +5 -0
  73. package/dist/modules/cli_colors.js +7 -0
  74. package/dist/modules/cli_progress.d.ts +51 -0
  75. package/dist/modules/cli_progress.js +113 -0
  76. package/dist/modules/constants.js +6 -3
  77. package/dist/modules/dexbot_class.d.ts +8 -0
  78. package/dist/modules/dexbot_class.js +10 -0
  79. package/dist/modules/dexbot_cow_runtime.d.ts +62 -1
  80. package/dist/modules/dexbot_cow_runtime.js +475 -47
  81. package/dist/modules/dexbot_credential_client.d.ts +5 -0
  82. package/dist/modules/dexbot_fill_runtime.js +20 -0
  83. package/dist/modules/dexbot_maintenance_runtime.js +71 -9
  84. package/dist/modules/dexbot_startup_runtime.js +7 -1
  85. package/dist/modules/graceful_shutdown.d.ts +2 -2
  86. package/dist/modules/graceful_shutdown.js +2 -2
  87. package/dist/modules/launcher/runtime_entry.d.ts +21 -1
  88. package/dist/modules/launcher/runtime_entry.js +36 -1
  89. package/dist/modules/launcher/runtime_mode.d.ts +4 -3
  90. package/dist/modules/liquidity_pool_ref.d.ts +32 -0
  91. package/dist/modules/liquidity_pool_ref.js +116 -0
  92. package/dist/modules/node_manager.d.ts +1 -1
  93. package/dist/modules/node_manager.js +1 -1
  94. package/dist/modules/order/accounting.js +2 -1
  95. package/dist/modules/order/export.d.ts +2 -2
  96. package/dist/modules/order/export.js +2 -2
  97. package/dist/modules/order/grid.d.ts +19 -14
  98. package/dist/modules/order/grid.js +269 -61
  99. package/dist/modules/order/grid_reconcile.js +27 -2
  100. package/dist/modules/order/grid_reconcile_internal.js +94 -15
  101. package/dist/modules/order/index.d.ts +24 -4
  102. package/dist/modules/order/manager.d.ts +12 -0
  103. package/dist/modules/order/manager.js +44 -11
  104. package/dist/modules/order/strategy.js +22 -2
  105. package/dist/modules/order/sync_engine.d.ts +32 -1
  106. package/dist/modules/order/sync_engine.js +209 -26
  107. package/dist/modules/order/utils/math.d.ts +26 -10
  108. package/dist/modules/order/utils/math.js +54 -14
  109. package/dist/modules/order/utils/order.d.ts +158 -11
  110. package/dist/modules/order/utils/order.js +434 -21
  111. package/dist/modules/order/utils/system.d.ts +136 -30
  112. package/dist/modules/order/utils/system.js +465 -63
  113. package/dist/modules/order/utils/validate.d.ts +1 -0
  114. package/dist/modules/order/utils/validate.js +37 -3
  115. package/dist/modules/storage/index.d.ts +3 -2
  116. package/dist/modules/storage/index.js +3 -2
  117. package/dist/modules/types.d.ts +14 -0
  118. package/dist/modules/utils/asset_symbols.d.ts +13 -2
  119. package/dist/modules/utils/asset_symbols.js +21 -2
  120. package/dist/scripts/analysis_runner.d.ts +10 -0
  121. package/dist/scripts/analysis_runner.js +33 -0
  122. package/dist/scripts/analyze-orders.js +2 -1
  123. package/dist/scripts/asset.d.ts +26 -0
  124. package/dist/scripts/asset.js +165 -0
  125. package/dist/scripts/bts_distribution.d.ts +1 -0
  126. package/dist/scripts/bts_distribution.js +194 -142
  127. package/dist/scripts/chart_command.d.ts +1 -1
  128. package/dist/scripts/chart_command.js +60 -86
  129. package/dist/scripts/chart_targets.d.ts +18 -0
  130. package/dist/scripts/chart_targets.js +52 -0
  131. package/dist/scripts/dw.js +1 -1
  132. package/dist/scripts/liquid.d.ts +24 -0
  133. package/dist/scripts/liquid.js +134 -0
  134. package/dist/scripts/rich_list.js +12 -16
  135. package/dist/scripts/token_distribution.d.ts +2 -0
  136. package/dist/scripts/token_distribution.js +132 -108
  137. package/dist/scripts/tv.js +1 -1
  138. package/dist/scripts/verify-browser-bundle.js +18 -0
  139. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  140. package/docs/COW_INVARIANTS.md +21 -11
  141. package/docs/DEXBOT_COMPARISON.md +6 -6
  142. package/docs/EVOLUTION.md +10 -8
  143. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +11 -11
  144. package/docs/GRID_PRICE_INVARIANT.md +28 -5
  145. package/docs/GRID_RECONCILE.md +25 -5
  146. package/docs/LIFECYCLE.md +11 -11
  147. package/docs/LOGGING.md +37 -2
  148. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +124 -36
  149. package/docs/README.md +1 -1
  150. package/docs/WORKFLOW.md +3 -1
  151. package/docs/architecture.md +115 -13
  152. package/docs/developer_guide.md +12 -0
  153. package/market_adapter/README.md +9 -4
  154. package/modules/README.md +23 -15
  155. package/package.json +6 -3
  156. package/scripts/README.md +23 -7
@@ -47,8 +47,7 @@
47
47
  * - updateGapEvacuationStreaks(...) - Tick per-slot gap-evacuation streak counter
48
48
  * - collectRefillSlotIds(...) - Refill-slot wire for the COW boundary hold
49
49
  *
50
- * SECTION 6: FILTERING & DRIFT DIAGNOSTICS (12 functions)
51
- * - parseSlotIndex(id) - Parse "slot-N" to its rail index
50
+ * SECTION 6: FILTERING & DRIFT DIAGNOSTICS (11 functions)
52
51
  * - filterOrdersByType(orders, orderType) - Filter orders by type
53
52
  * - buildOutsideInPairGroups(items, accessors) - Outside->center pair grouping
54
53
  * - extractBatchOperationResults(result) - Extract operation_results from chain batch result
@@ -121,7 +120,7 @@ import Logger from '../../order/logger.js';
121
120
  import { sleep } from './system.js';
122
121
  import { getErrorMessage, getErrorCode, getErrorName } from '../../utils/errors.js';
123
122
  import { hasGenesisLadder } from '../genesis_policy.js';
124
- import { parseSlotIndex as parseSlotIndexShared } from './slot.js';
123
+ import { parseSlotIndex } from './slot.js';
125
124
  const { isValidNumber, toFiniteNumber } = Format;
126
125
  const { blockchainToFloat, floatToBlockchainInt, quantizeFloat, slotIndexForPrice, priceSlotEqual } = MathUtils;
127
126
  const orderLogger = new Logger('Order');
@@ -327,6 +326,303 @@ function _stampCorrectionProvenance(entry, source) {
327
326
  }
328
327
  return entry;
329
328
  }
329
+ /**
330
+ * Resolve the EXECUTION price of a fill from its paid/received raw amounts
331
+ * (quote per base). This is the fill FACT the LAST-FILL-GUARD pivot and the
332
+ * boundary re-anchor need — the slot price is only a grid identity and may be
333
+ * stale after a refused-commit chain adoption or an off-ladder maker fill.
334
+ *
335
+ * Returns null when either side of the amounts is missing/unusable, so callers
336
+ * can fall back (a fill we cannot price must not move the pivot).
337
+ *
338
+ * @param {Object} assets - {assetA (base), assetB (quote)} with precisions
339
+ * @param {string|null} paysAssetId - Asset the account paid
340
+ * @param {number} paysAmountRaw - Raw (integer) amount paid
341
+ * @param {string|null} receivesAssetId - Asset the account received
342
+ * @param {number} receivesAmountRaw - Raw (integer) amount received
343
+ * @returns {number|null} Quote-per-base price, or null when unresolvable
344
+ */
345
+ function resolveExecutionPrice(assets, paysAssetId, paysAmountRaw, receivesAssetId, receivesAmountRaw) {
346
+ if (!assets?.assetA || !assets?.assetB)
347
+ return null;
348
+ const pays = Number(paysAmountRaw);
349
+ const receives = Number(receivesAmountRaw);
350
+ if (!Number.isFinite(pays) || pays <= 0)
351
+ return null;
352
+ if (!Number.isFinite(receives) || receives <= 0)
353
+ return null;
354
+ const A = assets.assetA;
355
+ const B = assets.assetB;
356
+ let baseRaw = null;
357
+ let quoteRaw = null;
358
+ if (paysAssetId === A.id && receivesAssetId === B.id) {
359
+ baseRaw = pays;
360
+ quoteRaw = receives;
361
+ }
362
+ else if (paysAssetId === B.id && receivesAssetId === A.id) {
363
+ baseRaw = receives;
364
+ quoteRaw = pays;
365
+ }
366
+ if (baseRaw === null || quoteRaw === null)
367
+ return null;
368
+ const base = MathUtils.blockchainToFloat(baseRaw, A.precision);
369
+ const quote = MathUtils.blockchainToFloat(quoteRaw, B.precision);
370
+ if (!(base > 0) || !(quote > 0))
371
+ return null;
372
+ const price = quote / base;
373
+ return Number.isFinite(price) && price > 0 ? price : null;
374
+ }
375
+ /**
376
+ * Resolve the grid SLOT a fill belongs to when its chain order id no longer
377
+ * identifies one.
378
+ *
379
+ * Every virtualisation path (`virtualizeOrder` -> `convertToSpreadPlaceholder`
380
+ * / `toRailHolePlaceholder`) NULLS `orderId`, so after a phantom cleanup or a
381
+ * refused-commit adoption the master holds no slot keyed by the filled order:
382
+ * the id lookup misses exactly when the fill matters most. The genesis ladder
383
+ * is the authority for "which slot does this price belong to" (same rule pass 2
384
+ * uses for adoption), so the fill's own execution price identifies the level.
385
+ *
386
+ * Returns null for a price outside the frozen rail: a shelf/manual order or an
387
+ * off-ladder wick must never be mapped onto an edge slot (that would arm the
388
+ * pivot with a price the grid never traded at).
389
+ *
390
+ * @param {Object} manager - OrderManager instance (genesis ladder + assets)
391
+ * @param {number} price - Fill execution price
392
+ * @param {Object} [hints] - Optional {size, type} of the fill for edge-dust tolerance
393
+ * @returns {string|null} `slot-N` id, or null when unresolvable/out-of-grid
394
+ */
395
+ function resolveSlotIdForFillPrice(manager, price, hints = {}) {
396
+ try {
397
+ const genesis = manager._genesis;
398
+ if (!hasGenesisLadder(genesis) || !Number.isFinite(price))
399
+ return null;
400
+ const ladder = genesis;
401
+ if (MathUtils.isChainPriceOutOfGrid(price, ladder, Number(hints.size) || 0, hints.type === ORDER_TYPES.BUY || hints.type === ORDER_TYPES.SELL ? hints.type : null, manager?.assets ?? null))
402
+ return null;
403
+ const idx = MathUtils.slotIndexForPrice(price, ladder);
404
+ if (!Number.isFinite(idx) || idx < 0)
405
+ return null;
406
+ const levels = ladder.priceLevels;
407
+ if (Array.isArray(levels) && levels.length > 0 && idx >= levels.length)
408
+ return null;
409
+ return `slot-${idx}`;
410
+ }
411
+ catch {
412
+ return null;
413
+ }
414
+ }
415
+ /**
416
+ * REVIVE a virtualised slot whose chain order is still LIVE on chain.
417
+ *
418
+ * The state hole this closes: a slot can be virtualised (phantom cleanup on a
419
+ * truncated read, refused-commit adoption, rotation cleanup) while its order
420
+ * still rests on the chain. In that state the slot is invisible to window
421
+ * accounting (`_countActiveOnGrid` needs ACTIVE/PARTIAL) but its order is still
422
+ * counted in `chainCount`, so the reconcile reads a shortfall it can never
423
+ * repair — and the planner sees a free level, which is how a second order can be
424
+ * created at a price that already holds one.
425
+ *
426
+ * The revive is broadcast-free (master-only): the order is already on chain, so
427
+ * this only re-materialises the slot at its chain size/state. It refuses when
428
+ * the chain order does NOT rest at this slot's level: the slot then merely
429
+ * aliases the id (a rotation source whose cancel has not landed, a re-slotted
430
+ * order) and reviving it would resurrect a level the planner emptied on purpose.
431
+ *
432
+ * @param {Object} manager - OrderManager instance
433
+ * @param {Object} slot - Master slot (must NOT be placed)
434
+ * @param {Object} chainOrder - Parsed chain order (price/size/type/orderId)
435
+ * @param {unknown} rawOnChain - Raw chain object for the slot snapshot
436
+ * @param {string} context - Update context tag for logging/accounting
437
+ * @param {Object} [options] - {skipAccounting}
438
+ * @returns {Promise<Object|null>} The revived slot when applied, else null
439
+ */
440
+ async function reviveVirtualSlotFromChain(manager, slot, chainOrder, rawOnChain, context, options = {}) {
441
+ try {
442
+ if (!manager || !slot || !slot.id || !chainOrder)
443
+ return null;
444
+ // Only a NON-placed slot can be revived; a placed one is already live.
445
+ if (isOrderPlaced(slot))
446
+ return null;
447
+ const chainId = chainOrder.orderId ?? slot.orderId ?? null;
448
+ if (!chainId)
449
+ return null;
450
+ if (slot.orderId && String(slot.orderId) !== String(chainId))
451
+ return null;
452
+ const type = chainOrder.type;
453
+ if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
454
+ return null;
455
+ const chainPrice = Number(chainOrder.price);
456
+ const chainSize = Number(chainOrder.size);
457
+ if (!Number.isFinite(chainPrice) || chainPrice <= 0)
458
+ return null;
459
+ if (!Number.isFinite(chainSize) || chainSize <= 0)
460
+ return null;
461
+ if (!MathUtils.sameGridLevel(chainPrice, Number(slot.price), manager._genesis))
462
+ return null;
463
+ const booked = toFiniteNumber(slot.size, 0);
464
+ const state = booked > chainSize ? ORDER_STATES.PARTIAL : ORDER_STATES.ACTIVE;
465
+ const { createUncertain: _staleMarker, ...rest } = slot;
466
+ const revived = {
467
+ ...rest,
468
+ type,
469
+ state,
470
+ size: chainSize,
471
+ orderId: String(chainId),
472
+ rawOnChain: (rawOnChain && typeof rawOnChain === 'object'
473
+ ? { ...rawOnChain, fetchedAt: Date.now() }
474
+ : (slot.rawOnChain ?? null)),
475
+ };
476
+ const applied = await manager._applyOrderUpdate(revived, context, {
477
+ skipAccounting: options.skipAccounting === true,
478
+ fee: 0
479
+ });
480
+ if (applied === false) {
481
+ manager.logger?.log?.(`[SYNC] Revive of virtualised slot ${slot.id} rejected — slot keeps its VIRTUAL state`, 'warn');
482
+ return null;
483
+ }
484
+ manager.logger?.log?.(`[SYNC] Revived virtualised slot ${slot.id}: its chain order ${chainId} is still live ` +
485
+ `(${type} @ ${Format.formatPrice6(chainPrice)}, size ${chainSize}) while the slot was ` +
486
+ `${ORDER_STATES.VIRTUAL} — re-materialised in place (no broadcast), so window accounting ` +
487
+ `counts it again`, 'warn');
488
+ return revived;
489
+ }
490
+ catch {
491
+ return null;
492
+ }
493
+ }
494
+ /**
495
+ * ATTRIBUTE a fill to the grid when its chain order id identifies no live slot
496
+ * ("order not found in active grid").
497
+ *
498
+ * The failure this closes (live incident): a 120s stale broadcast region
499
+ * deferred the fill queue, a phantom cleanup then virtualised the filled slots
500
+ * (which NULLS their `orderId`), and the re-delivered fills were dropped AFTER
501
+ * their accounting had been booked. Neither the LAST-FILL-GUARD pivot nor the
502
+ * owed boundary crawl learned the execution price, so the pivot stayed on a
503
+ * stale, HIGHER value and the direction rule then allowed re-buys ABOVE the
504
+ * market (9 buy-lower violations, 23.5% of the window's BTS).
505
+ *
506
+ * Two identities, in order:
507
+ * 1. the slot that still owns the chain order id (any state — a virtualised
508
+ * slot can keep its id), or
509
+ * 2. the genesis ladder level the fill's own execution price maps to (the
510
+ * common case, because virtualisation clears the id).
511
+ *
512
+ * Only what the fill PROVES is recorded: the pivot, and — when the resolved
513
+ * slot is a hole — an owed boundary crawl. The slot and the already-booked
514
+ * accounting are never touched: the funds are the accountant's business, this
515
+ * only keeps the geometry honest. A price outside the frozen rail is refused,
516
+ * so a shelf/manual order can never arm the pivot at a level the grid does not
517
+ * trade.
518
+ *
519
+ * @param {Object} manager - OrderManager instance
520
+ * @param {Object} params - fill identity {orderId, pays/receives amount+asset, isPartial}
521
+ * @returns {boolean} true when the fill was attributed to the grid
522
+ */
523
+ function attributeUnmatchedFillToGrid(manager, params) {
524
+ const mgr = manager;
525
+ if (!mgr || !(mgr.orders instanceof Map))
526
+ return false;
527
+ const input = params ?? {};
528
+ const assets = mgr.assets;
529
+ if (!assets?.assetA || !assets?.assetB)
530
+ return false;
531
+ // Identity 1: the slot that still owns this chain order id, in ANY state.
532
+ const chainOrderId = input.orderId != null && String(input.orderId).length > 0 ? String(input.orderId) : null;
533
+ let slot = null;
534
+ if (chainOrderId) {
535
+ for (const candidate of mgr.orders.values()) {
536
+ if (candidate && String(candidate.orderId ?? '') === chainOrderId) {
537
+ slot = candidate;
538
+ break;
539
+ }
540
+ }
541
+ }
542
+ // Side from the asset that was PAID: paying the quote (assetB) buys the
543
+ // base, paying the base sells it. Independent of any slot type. When the
544
+ // fill event carries no pays asset (malformed/degraded), fall back to the
545
+ // matched slot's rail type — the side must never be guessed from the price.
546
+ let type = null;
547
+ if (input.paysAssetId === assets.assetB.id)
548
+ type = ORDER_TYPES.BUY;
549
+ else if (input.paysAssetId === assets.assetA.id)
550
+ type = ORDER_TYPES.SELL;
551
+ if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL && slot
552
+ && (slot.type === ORDER_TYPES.BUY || slot.type === ORDER_TYPES.SELL)) {
553
+ type = slot.type;
554
+ }
555
+ if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
556
+ return false;
557
+ const execPrice = resolveExecutionPrice(assets, input.paysAssetId, input.paysAmountRaw, input.receivesAssetId, input.receivesAmountRaw);
558
+ let identity = slot && slot.id ? 'chain-id' : null;
559
+ let slotId = slot && slot.id ? String(slot.id) : null;
560
+ let price = execPrice;
561
+ if (identity === 'chain-id' && (price == null || !(price > 0))) {
562
+ // Unpriced fill on a known slot: its stored level is the best evidence.
563
+ const slotPrice = Number(slot?.price);
564
+ price = Number.isFinite(slotPrice) && slotPrice > 0 ? slotPrice : null;
565
+ }
566
+ // Identity 2: the ladder level the execution price maps to. Only for a
567
+ // price that is genuinely inside the frozen rail (never a shelf order).
568
+ if (identity == null) {
569
+ if (price == null || !(price > 0))
570
+ return false;
571
+ const derived = resolveSlotIdForFillPrice(mgr, price, { type });
572
+ if (!derived)
573
+ return false;
574
+ identity = 'ladder';
575
+ slotId = derived;
576
+ slot = mgr.orders.get(derived) ?? null;
577
+ }
578
+ if (price == null || !Number.isFinite(price) || price <= 0)
579
+ return false;
580
+ if (!slotId)
581
+ return false;
582
+ // 1. Pivot: the LAST-FILL-GUARD reference must track the real trade.
583
+ // recordLastFilledPrices owns the scalar family + the edge-pinned
584
+ // exclusion (a wick on an edge order must not arm it).
585
+ let pivotRecorded = false;
586
+ try {
587
+ mgr.recordLastFilledPrices?.([{ id: slotId, type, price, isPartial: input.isPartial === true }]);
588
+ // Honest reporting: the writer deliberately SKIPS edge-pinned fills (a
589
+ // wick on the static floor/ceiling must not arm the pivot), so "did the
590
+ // pivot move to this price" is the only truthful signal.
591
+ pivotRecorded = Number(mgr._lastFilledPrice) === price;
592
+ }
593
+ catch (err) {
594
+ mgr.logger?.log?.(`[SYNC] Fill-pivot record failed for unattributed fill ${chainOrderId ?? 'unknown'}: ${getErrorMessage(err)}`, 'warn');
595
+ }
596
+ // 2. Owed crawl: the same ledger the strategy maintains, and only for a
597
+ // slot that is actually a HOLE the grid owns — a crawl is owed because
598
+ // the level must be re-placed, which cannot happen while an order still
599
+ // occupies it (and cannot be consumed for a slot that does not exist).
600
+ // Same eligibility as strategy.processFillsOnly: the edge classification
601
+ // that decides whether a crawl is APPLIED lives in the boundary
602
+ // derivation. Re-delivery replaces, never stacks; dry runs never commit a
603
+ // boundary, so they must not grow the ledger.
604
+ const slotIsHole = !!slot && !isOrderPlaced(slot);
605
+ try {
606
+ if (slotIsHole && mgr.config?.dryRun !== true && Array.isArray(mgr._pendingFillCrawls)) {
607
+ const pending = mgr._pendingFillCrawls;
608
+ const at = pending.findIndex((e) => e && e.slotId === slotId);
609
+ if (at >= 0)
610
+ pending.splice(at, 1);
611
+ pending.push({ slotId, side: type, ts: Date.now() });
612
+ while (pending.length > 500)
613
+ pending.shift();
614
+ if (typeof mgr._markGridDirty === 'function')
615
+ mgr._markGridDirty();
616
+ }
617
+ }
618
+ catch { /* best-effort: the pivot above is the fail-safe */ }
619
+ mgr.logger?.log?.(`[SYNC] Fill for order ${chainOrderId ?? 'unknown'} attributed to ${slotId} via ${identity} ` +
620
+ `(${type} @ ${Format.formatPrice6(price)}): ` +
621
+ `${pivotRecorded ? 'pivot recorded' : 'pivot NOT armed (edge-pinned fill or no writer)'}` +
622
+ `${slotIsHole ? ' + owed boundary crawl' : ' (slot still holds a live order: no crawl)'}` +
623
+ `; accounting already booked`, 'warn');
624
+ return true;
625
+ }
330
626
  /**
331
627
  * Find the live grid slot that currently owns a chain order.
332
628
  * When slotId is supplied, only that exact slot is considered; otherwise all
@@ -413,8 +709,10 @@ function _validatePriceCorrectionEntry(manager, entry) {
413
709
  if (!slot) {
414
710
  return { valid: false, reason: `gap-evacuation target ${slotId || '?'} no longer owns ${entry.chainOrderId}` };
415
711
  }
416
- const idx = parseSlotIndex(slot.id);
417
- const geometry = geometryTypeForSlotIndex(idx, manager?.boundaryIdx, manager?._gapSlots);
712
+ // Live chain price first: a refused-commit adoption can leave the local
713
+ // slot id in-rail while the order actually rests inside the band.
714
+ const live = resolveLiveOrderLadderPosition(slot, manager?.assets, manager?._genesis);
715
+ const geometry = geometryTypeForSlotIndex(live.idx, manager?.boundaryIdx, manager?._gapSlots);
418
716
  if (geometry !== ORDER_TYPES.SPREAD) {
419
717
  return { valid: false, reason: `gap-evacuation target ${slotId} is no longer in the current gap band` };
420
718
  }
@@ -1350,6 +1648,54 @@ function geometryTypeForSlotIndex(idx, boundaryIdx, gapSlots) {
1350
1648
  return ORDER_TYPES.SELL;
1351
1649
  return ORDER_TYPES.SPREAD;
1352
1650
  }
1651
+ /**
1652
+ * Resolve a slot's LIVE ladder position from its on-chain price.
1653
+ *
1654
+ * `slot.id` is the local generation index; after a refused-commit adoption it
1655
+ * can be stale (an order still keyed at slot-117 can be resting at the
1656
+ * slot-138 price on chain). Evacuation geometry must therefore prefer the
1657
+ * chain order's real price, mapped onto the genesis ladder, and only fall back
1658
+ * to the stored slot index. The slot's identity price is NOT rewritten — this
1659
+ * is a read-only geometry probe (GRID-PRICE-INVARIANT stays intact).
1660
+ *
1661
+ * @param slot - Grid slot (needs id/orderId/rawOnChain)
1662
+ * @param assets - Asset pair (precision + ids) for parseChainOrder
1663
+ * @param genesis - Genesis ladder for price -> slot index
1664
+ * @returns {idx, price}: ladder index (null when unknown) and live price
1665
+ */
1666
+ function resolveLiveOrderLadderPosition(slot, assets, genesis) {
1667
+ const fallbackIdx = parseSlotIndex(slot?.id);
1668
+ const fallbackPrice = Number(slot?.price);
1669
+ const raw = slot?.rawOnChain;
1670
+ if (!raw || !assets || !genesis) {
1671
+ return { idx: fallbackIdx, price: Number.isFinite(fallbackPrice) && fallbackPrice > 0 ? fallbackPrice : null };
1672
+ }
1673
+ try {
1674
+ const parsed = parseChainOrder(raw, assets);
1675
+ if (!parsed)
1676
+ return { idx: fallbackIdx, price: Number.isFinite(fallbackPrice) && fallbackPrice > 0 ? fallbackPrice : null };
1677
+ if (slot?.orderId && parsed.orderId !== slot.orderId) {
1678
+ // The raw snapshot belongs to a different chain order: not evidence
1679
+ // for this slot.
1680
+ return { idx: fallbackIdx, price: Number.isFinite(fallbackPrice) && fallbackPrice > 0 ? fallbackPrice : null };
1681
+ }
1682
+ const livePrice = Number(parsed.price);
1683
+ if (!Number.isFinite(livePrice) || livePrice <= 0) {
1684
+ return { idx: fallbackIdx, price: Number.isFinite(fallbackPrice) && fallbackPrice > 0 ? fallbackPrice : null };
1685
+ }
1686
+ let idx = fallbackIdx;
1687
+ try {
1688
+ const resolved = Number(MathUtils.slotIndexForPrice(livePrice, genesis));
1689
+ if (Number.isFinite(resolved) && resolved >= 0)
1690
+ idx = resolved;
1691
+ }
1692
+ catch { /* keep the stored index */ }
1693
+ return { idx, price: livePrice };
1694
+ }
1695
+ catch {
1696
+ return { idx: fallbackIdx, price: Number.isFinite(fallbackPrice) && fallbackPrice > 0 ? fallbackPrice : null };
1697
+ }
1698
+ }
1353
1699
  /**
1354
1700
  * Detect gap-evacuation candidates by GEOMETRY ONLY: live on-chain orders
1355
1701
  * whose parsed slot index sits strictly inside the gap band
@@ -1357,12 +1703,17 @@ function geometryTypeForSlotIndex(idx, boundaryIdx, gapSlots) {
1357
1703
  * Phase 2 retypes in-band actives to rail types, so type-based detection
1358
1704
  * would go blind exactly when evacuation matters.
1359
1705
  *
1706
+ * The ladder index prefers the order's LIVE chain price (see
1707
+ * resolveLiveOrderLadderPosition): a refused-commit adoption can leave the
1708
+ * local slot id in-rail while the order actually rests inside the band.
1709
+ *
1360
1710
  * @param {Map} masterGrid - Master grid (slotId -> order)
1361
1711
  * @param {number} boundaryIdx - Last BUY slot index (frozen at plan-build)
1362
1712
  * @param {number} gapSlots - Spread gap slot count (frozen at plan-build)
1713
+ * @param {Object} [options] - assets/genesis for the live-price probe
1363
1714
  * @returns {Array} Candidates [{id, idx, type, price, size, orderId}]
1364
1715
  */
1365
- function detectGapEvacuationCandidates(masterGrid, boundaryIdx, gapSlots) {
1716
+ function detectGapEvacuationCandidates(masterGrid, boundaryIdx, gapSlots, options = {}) {
1366
1717
  const out = [];
1367
1718
  if (!masterGrid || typeof masterGrid.values !== 'function')
1368
1719
  return out;
@@ -1384,11 +1735,19 @@ function detectGapEvacuationCandidates(masterGrid, boundaryIdx, gapSlots) {
1384
1735
  for (const slot of masterGrid.values()) {
1385
1736
  if (!slot || !isOrderOnChain(slot) || !slot.orderId)
1386
1737
  continue;
1387
- const idx = parseSlotIndex(slot.id);
1738
+ const live = resolveLiveOrderLadderPosition(slot, options.assets, options.genesis);
1739
+ const idx = live.idx;
1388
1740
  if (idx === null || idx === undefined)
1389
1741
  continue;
1390
1742
  if (Number(idx) > b && Number(idx) < sellStartIdx) {
1391
- out.push({ id: slot.id, idx: Number(idx), type: slot.type, price: slot.price, size: slot.size, orderId: slot.orderId });
1743
+ out.push({
1744
+ id: slot.id,
1745
+ idx: Number(idx),
1746
+ type: slot.type,
1747
+ price: live.price != null ? live.price : slot.price,
1748
+ size: slot.size,
1749
+ orderId: slot.orderId
1750
+ });
1392
1751
  }
1393
1752
  }
1394
1753
  return out;
@@ -1450,15 +1809,6 @@ function updateGapEvacuationStreaks(streakMap, candidates, threshold = null) {
1450
1809
  function resolveSpreadOrderSide(price, startPrice) {
1451
1810
  return Number(price) < Number(startPrice) ? ORDER_TYPES.BUY : ORDER_TYPES.SELL;
1452
1811
  }
1453
- /**
1454
- * Parse a grid slot id ("slot-123") to its rail index. Delegates to
1455
- * shared slot.ts single source (GRID_PRICE_SLOT_DETERMINISM_PLAN §2.1).
1456
- * @param {unknown} id - grid slot id string
1457
- * @returns {number|null}
1458
- */
1459
- function parseSlotIndex(id) {
1460
- return parseSlotIndexShared(id);
1461
- }
1462
1812
  /**
1463
1813
  * Precision governing both price and size comparison for a parsed chain
1464
1814
  * order: base (assetA) for sells, quote (assetB) for buys.
@@ -1607,14 +1957,32 @@ function isCrossingCheckCandidate(o, excludeChainOrderId = null, cancelOpIndexBy
1607
1957
  function buildCrossingCheckCandidates(manager) {
1608
1958
  if (!manager)
1609
1959
  return [];
1610
- const candidates = manager.orders instanceof Map ? [...manager.orders.values()] : [];
1960
+ // LIVE PRICE: a refused-commit adoption can leave a master slot keyed at an
1961
+ // old generation level while its chain order actually rests at another
1962
+ // price (live incident: the grid still said slot-117 @1263 while the buy
1963
+ // was live at 1345.7). Using the stored price let a sell be emitted at the
1964
+ // same 1345.728664, self-crossing the live buy. Parse the chain snapshot
1965
+ // for the crossing probe only — the slot's identity price is unchanged.
1966
+ const withLivePrice = (o) => {
1967
+ const candidate = o;
1968
+ if (!candidate || typeof candidate !== 'object')
1969
+ return o;
1970
+ const live = resolveLiveOrderLadderPosition(candidate, manager.assets, manager._genesis);
1971
+ if (live.price == null || !Number.isFinite(Number(live.price)) || Number(live.price) <= 0)
1972
+ return o;
1973
+ return { ...o, price: Number(live.price) };
1974
+ };
1975
+ const candidates = manager.orders instanceof Map
1976
+ ? [...manager.orders.values()].map(withLivePrice)
1977
+ : [];
1611
1978
  if (manager._pendingBroadcasts instanceof Map) {
1612
1979
  for (const entry of manager._pendingBroadcasts.values()) {
1613
1980
  if (entry && entry.slotId && entry.order)
1614
- candidates.push(entry);
1981
+ candidates.push(withLivePrice(entry));
1615
1982
  }
1616
1983
  }
1617
1984
  if (Array.isArray(manager._lastUnmatchedChainOrders)) {
1985
+ // Unmatched chain orders already carry the chain price; keep as-is.
1618
1986
  for (const o of manager._lastUnmatchedChainOrders) {
1619
1987
  if (o && o.type != null && o.price != null)
1620
1988
  candidates.push(o);
@@ -2893,6 +3261,51 @@ function windowIdSetFromSlots(allSlots, config, orderType, boundaryIdx, gapSlots
2893
3261
  return null;
2894
3262
  }
2895
3263
  }
3264
+ /**
3265
+ * Collect the fill ids that belong to EDGE-pinned insurance orders.
3266
+ *
3267
+ * Edge orders (grid floor / ceiling) are static fat-finger insurance, not
3268
+ * market movement: the boundary crawl already excludes their fills
3269
+ * (`deriveTargetBoundary`), and the same exclusion must apply to the fill
3270
+ * reference the LAST-FILL-GUARD pivots on and the boundary re-anchor uses.
3271
+ * Without it, one wick that triggers a far-out insurance order would arm the
3272
+ * guard at that price AND re-anchor the window to the grid edge — the exact
3273
+ * "teleport" class the geometry guards exist to prevent.
3274
+ *
3275
+ * Uses the SAME classification the placement pickers use (live window ids
3276
+ * excluded, live edge anchor) so "edge" cannot mean two things.
3277
+ *
3278
+ * @param {Object} manager - OrderManager (orders Map, config, boundary)
3279
+ * @param {Array<Object>} fills - Fill batch
3280
+ * @returns {Set<string>} Slot ids of edge-pinned fills (empty when none/unknown)
3281
+ */
3282
+ function collectEdgePinnedFillIds(manager, fills) {
3283
+ const out = new Set();
3284
+ if (!manager || !Array.isArray(fills) || fills.length === 0)
3285
+ return out;
3286
+ try {
3287
+ const slots = manager.orders && typeof manager.orders.values === 'function'
3288
+ ? Array.from(manager.orders.values())
3289
+ : [];
3290
+ if (slots.length === 0)
3291
+ return out;
3292
+ for (const side of [ORDER_TYPES.BUY, ORDER_TYPES.SELL]) {
3293
+ const windowIds = liveWindowIdSet(manager, side);
3294
+ const edgeIds = edgeOrderIdSet(slots, manager?.config, side, resolveLiveEdgeAnchorPrice(manager, side), windowIds);
3295
+ if (!edgeIds || edgeIds.size === 0)
3296
+ continue;
3297
+ for (const f of fills) {
3298
+ if (!f || f.type !== side)
3299
+ continue;
3300
+ const id = String(f.id ?? '');
3301
+ if (id && edgeIds.has(id))
3302
+ out.add(id);
3303
+ }
3304
+ }
3305
+ }
3306
+ catch { /* classification is best-effort: never block fill intake */ }
3307
+ return out;
3308
+ }
2896
3309
  /**
2897
3310
  * Window member ids for one side from the live manager (see
2898
3311
  * windowIdSetFromSlots). Delegates so the manager and explicit-geometry
@@ -3197,7 +3610,7 @@ function calculateBudgetedSizes(slots, side, budget, weightDist, incrementPercen
3197
3610
  }
3198
3611
  const incrementFactor = Number(incrementPercent) / 100;
3199
3612
  return MathUtils.allocateFundsByWeights(budget, slots.length, weightDist, incrementFactor, isBuy, // Reverse for BUY (Market-Close is last in array)
3200
- 0, precision);
3613
+ precision);
3201
3614
  }
3202
3615
  // ================================================================================
3203
3616
  // SECTION: COW batch-shared pure helpers (moved from dexbot_cow_runtime.ts —
@@ -3395,6 +3808,6 @@ function collectKnownOnChainOrderIds(mgr, placedResults, placedContexts, extraCr
3395
3808
  const all = new Set([...masterIds, ...createIds]);
3396
3809
  return { masterIds: [...masterIds], createIds: [...createIds], all: [...all] };
3397
3810
  }
3398
- export { parseChainOrder, applyChainSizeToGridOrder, buildFillKey, correctOrderPriceOnChain, correctAllPriceMismatches, _validatePriceCorrectionEntry, _stampCorrectionProvenance, findLiveOrderOwnerByChainId, buildCreateOrderArgs, getOrderTypeFromUpdatedFlags, resolveConfiguredPriceBound, virtualizeOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, detectGapEvacuationCandidates, updateGapEvacuationStreaks, resolveSpreadOrderSide, chainOrderMatchesSlot, chainOrderMatchesSlotWithTolerance, crossingCandidateChainId, isCrossingCheckCandidate, buildCrossingCheckCandidates, parseSlotIndex, filterOrdersByType, buildOutsideInPairGroups, extractBatchOperationResults, formatUnmatchedChainOrder, isNonBlockingUnmatchedOrder, isStrandedHoldOrder, isOrderOnChain, isOrderVirtual, hasOnChainId, isOrderPlaced, isPhantomOrder, isSlotAvailable, isEmptyGridSlot, isOrderHealthy, checkSizeThreshold, checkSizesBeforeMinimum, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, shouldFlagOutOfSpread, buildIndexes, validateIndexes, ordersEqual, buildDelta, deriveTargetBoundary, isShiftEligibleFill, resolveEdgeCount, resolveEdgeOrders, selectEdgeSlots, getCoreOrdersTotal, getSideBudget, calculateBudgetedSizes, buildCreateOpFingerprint, isOrderGoneErrorMessage, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
3811
+ export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, resolveExecutionPrice, resolveSlotIdForFillPrice, reviveVirtualSlotFromChain, attributeUnmatchedFillToGrid, buildFillKey, correctOrderPriceOnChain, correctAllPriceMismatches, _validatePriceCorrectionEntry, _stampCorrectionProvenance, findLiveOrderOwnerByChainId, buildCreateOrderArgs, getOrderTypeFromUpdatedFlags, resolveConfiguredPriceBound, virtualizeOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, detectGapEvacuationCandidates, updateGapEvacuationStreaks, resolveSpreadOrderSide, chainOrderMatchesSlot, chainOrderMatchesSlotWithTolerance, crossingCandidateChainId, isCrossingCheckCandidate, buildCrossingCheckCandidates, filterOrdersByType, buildOutsideInPairGroups, extractBatchOperationResults, formatUnmatchedChainOrder, isNonBlockingUnmatchedOrder, isStrandedHoldOrder, isOrderOnChain, isOrderVirtual, hasOnChainId, isOrderPlaced, isPhantomOrder, isSlotAvailable, isEmptyGridSlot, isOrderHealthy, checkSizeThreshold, checkSizesBeforeMinimum, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, shouldFlagOutOfSpread, buildIndexes, validateIndexes, ordersEqual, buildDelta, deriveTargetBoundary, isShiftEligibleFill, resolveEdgeCount, resolveEdgeOrders, selectEdgeSlots, getCoreOrdersTotal, getSideBudget, calculateBudgetedSizes, buildCreateOpFingerprint, isOrderGoneErrorMessage, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, collectEdgePinnedFillIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
3399
3812
  export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
3400
3813
  //# sourceMappingURL=order.js.map