dexbot 1.6.18 → 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 (89) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +24 -18
  3. package/analysis/README.md +95 -3
  4. package/claw/package.json +1 -1
  5. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  7. package/dist/analysis/analyze_dynamic_weight.js +2 -1
  8. package/dist/analysis/analyze_kalman.js +3 -2
  9. package/dist/analysis/analyze_liquidity.d.ts +17 -0
  10. package/dist/analysis/analyze_liquidity.js +325 -0
  11. package/dist/analysis/analyze_regime.js +3 -2
  12. package/dist/analysis/analyze_regime_windows.js +3 -2
  13. package/dist/analysis/analyze_volatility.js +3 -2
  14. package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
  15. package/dist/analysis/liquidity/liquidity_chain.js +178 -0
  16. package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
  17. package/dist/analysis/liquidity/liquidity_chart_generator.js +523 -0
  18. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +141 -0
  19. package/dist/analysis/liquidity/liquidity_depth_model.js +230 -0
  20. package/dist/analysis/liquidity/liquidity_view.d.ts +38 -0
  21. package/dist/analysis/liquidity/liquidity_view.js +55 -0
  22. package/dist/analysis/trade_profitability.js +2 -1
  23. package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
  24. package/dist/dexbot.js +74 -169
  25. package/dist/modules/asset_lookup.d.ts +25 -0
  26. package/dist/modules/asset_lookup.js +75 -0
  27. package/dist/modules/chain_scan.d.ts +64 -0
  28. package/dist/modules/chain_scan.js +80 -0
  29. package/dist/modules/cli_colors.d.ts +5 -0
  30. package/dist/modules/cli_colors.js +7 -0
  31. package/dist/modules/cli_progress.d.ts +51 -0
  32. package/dist/modules/cli_progress.js +113 -0
  33. package/dist/modules/dexbot_cow_runtime.js +14 -4
  34. package/dist/modules/dexbot_fill_runtime.js +20 -0
  35. package/dist/modules/dexbot_maintenance_runtime.js +16 -1
  36. package/dist/modules/launcher/runtime_entry.d.ts +21 -1
  37. package/dist/modules/launcher/runtime_entry.js +36 -1
  38. package/dist/modules/liquidity_pool_ref.d.ts +32 -0
  39. package/dist/modules/liquidity_pool_ref.js +116 -0
  40. package/dist/modules/order/grid.js +9 -2
  41. package/dist/modules/order/grid_reconcile.js +22 -1
  42. package/dist/modules/order/grid_reconcile_internal.js +92 -14
  43. package/dist/modules/order/index.d.ts +15 -1
  44. package/dist/modules/order/manager.d.ts +2 -0
  45. package/dist/modules/order/manager.js +3 -0
  46. package/dist/modules/order/sync_engine.d.ts +20 -0
  47. package/dist/modules/order/sync_engine.js +101 -33
  48. package/dist/modules/order/utils/math.d.ts +18 -1
  49. package/dist/modules/order/utils/math.js +30 -1
  50. package/dist/modules/order/utils/order.d.ts +107 -1
  51. package/dist/modules/order/utils/order.js +298 -1
  52. package/dist/modules/order/utils/system.d.ts +63 -1
  53. package/dist/modules/order/utils/system.js +247 -36
  54. package/dist/modules/order/utils/validate.js +33 -2
  55. package/dist/modules/types.d.ts +5 -0
  56. package/dist/modules/utils/asset_symbols.d.ts +13 -2
  57. package/dist/modules/utils/asset_symbols.js +21 -2
  58. package/dist/scripts/analysis_runner.d.ts +10 -0
  59. package/dist/scripts/analysis_runner.js +33 -0
  60. package/dist/scripts/analyze-orders.js +2 -1
  61. package/dist/scripts/asset.d.ts +26 -0
  62. package/dist/scripts/asset.js +165 -0
  63. package/dist/scripts/bts_distribution.d.ts +1 -0
  64. package/dist/scripts/bts_distribution.js +194 -142
  65. package/dist/scripts/chart_command.d.ts +1 -1
  66. package/dist/scripts/chart_command.js +60 -86
  67. package/dist/scripts/chart_targets.d.ts +18 -0
  68. package/dist/scripts/chart_targets.js +52 -0
  69. package/dist/scripts/dw.js +1 -1
  70. package/dist/scripts/liquid.d.ts +24 -0
  71. package/dist/scripts/liquid.js +134 -0
  72. package/dist/scripts/rich_list.js +12 -16
  73. package/dist/scripts/token_distribution.d.ts +2 -0
  74. package/dist/scripts/token_distribution.js +132 -108
  75. package/dist/scripts/tv.js +1 -1
  76. package/dist/scripts/verify-browser-bundle.js +18 -0
  77. package/docs/COW_INVARIANTS.md +2 -2
  78. package/docs/DEXBOT_COMPARISON.md +6 -6
  79. package/docs/EVOLUTION.md +9 -8
  80. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  81. package/docs/GRID_PRICE_INVARIANT.md +4 -1
  82. package/docs/GRID_RECONCILE.md +20 -0
  83. package/docs/LOGGING.md +25 -3
  84. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +2 -1
  85. package/docs/README.md +1 -1
  86. package/docs/WORKFLOW.md +3 -1
  87. package/modules/README.md +5 -1
  88. package/package.json +3 -1
  89. package/scripts/README.md +23 -7
@@ -201,6 +201,112 @@ declare function isFreshlyPlacedOrder(manager: OrderManagerLike, chainOrderId: s
201
201
  * @returns {Object} The same entry, stamped
202
202
  */
203
203
  declare function _stampCorrectionProvenance(entry: PendingPriceCorrection, source: string): PendingPriceCorrection;
204
+ /**
205
+ * Resolve the EXECUTION price of a fill from its paid/received raw amounts
206
+ * (quote per base). This is the fill FACT the LAST-FILL-GUARD pivot and the
207
+ * boundary re-anchor need — the slot price is only a grid identity and may be
208
+ * stale after a refused-commit chain adoption or an off-ladder maker fill.
209
+ *
210
+ * Returns null when either side of the amounts is missing/unusable, so callers
211
+ * can fall back (a fill we cannot price must not move the pivot).
212
+ *
213
+ * @param {Object} assets - {assetA (base), assetB (quote)} with precisions
214
+ * @param {string|null} paysAssetId - Asset the account paid
215
+ * @param {number} paysAmountRaw - Raw (integer) amount paid
216
+ * @param {string|null} receivesAssetId - Asset the account received
217
+ * @param {number} receivesAmountRaw - Raw (integer) amount received
218
+ * @returns {number|null} Quote-per-base price, or null when unresolvable
219
+ */
220
+ declare function resolveExecutionPrice(assets: AssetPair | null | undefined, paysAssetId: string | null | undefined, paysAmountRaw: number | null | undefined, receivesAssetId: string | null | undefined, receivesAmountRaw: number | null | undefined): number | null;
221
+ /**
222
+ * Resolve the grid SLOT a fill belongs to when its chain order id no longer
223
+ * identifies one.
224
+ *
225
+ * Every virtualisation path (`virtualizeOrder` -> `convertToSpreadPlaceholder`
226
+ * / `toRailHolePlaceholder`) NULLS `orderId`, so after a phantom cleanup or a
227
+ * refused-commit adoption the master holds no slot keyed by the filled order:
228
+ * the id lookup misses exactly when the fill matters most. The genesis ladder
229
+ * is the authority for "which slot does this price belong to" (same rule pass 2
230
+ * uses for adoption), so the fill's own execution price identifies the level.
231
+ *
232
+ * Returns null for a price outside the frozen rail: a shelf/manual order or an
233
+ * off-ladder wick must never be mapped onto an edge slot (that would arm the
234
+ * pivot with a price the grid never traded at).
235
+ *
236
+ * @param {Object} manager - OrderManager instance (genesis ladder + assets)
237
+ * @param {number} price - Fill execution price
238
+ * @param {Object} [hints] - Optional {size, type} of the fill for edge-dust tolerance
239
+ * @returns {string|null} `slot-N` id, or null when unresolvable/out-of-grid
240
+ */
241
+ declare function resolveSlotIdForFillPrice(manager: OrderManagerLike, price: number, hints?: {
242
+ size?: number | null;
243
+ type?: string | null;
244
+ }): string | null;
245
+ /**
246
+ * REVIVE a virtualised slot whose chain order is still LIVE on chain.
247
+ *
248
+ * The state hole this closes: a slot can be virtualised (phantom cleanup on a
249
+ * truncated read, refused-commit adoption, rotation cleanup) while its order
250
+ * still rests on the chain. In that state the slot is invisible to window
251
+ * accounting (`_countActiveOnGrid` needs ACTIVE/PARTIAL) but its order is still
252
+ * counted in `chainCount`, so the reconcile reads a shortfall it can never
253
+ * repair — and the planner sees a free level, which is how a second order can be
254
+ * created at a price that already holds one.
255
+ *
256
+ * The revive is broadcast-free (master-only): the order is already on chain, so
257
+ * this only re-materialises the slot at its chain size/state. It refuses when
258
+ * the chain order does NOT rest at this slot's level: the slot then merely
259
+ * aliases the id (a rotation source whose cancel has not landed, a re-slotted
260
+ * order) and reviving it would resurrect a level the planner emptied on purpose.
261
+ *
262
+ * @param {Object} manager - OrderManager instance
263
+ * @param {Object} slot - Master slot (must NOT be placed)
264
+ * @param {Object} chainOrder - Parsed chain order (price/size/type/orderId)
265
+ * @param {unknown} rawOnChain - Raw chain object for the slot snapshot
266
+ * @param {string} context - Update context tag for logging/accounting
267
+ * @param {Object} [options] - {skipAccounting}
268
+ * @returns {Promise<Object|null>} The revived slot when applied, else null
269
+ */
270
+ declare function reviveVirtualSlotFromChain(manager: OrderManagerLike, slot: ManagedOrder, chainOrder: ParsedChainOrder | null | undefined, rawOnChain: unknown, context: string, options?: {
271
+ skipAccounting?: boolean;
272
+ }): Promise<ManagedOrder | null>;
273
+ /**
274
+ * ATTRIBUTE a fill to the grid when its chain order id identifies no live slot
275
+ * ("order not found in active grid").
276
+ *
277
+ * The failure this closes (live incident): a 120s stale broadcast region
278
+ * deferred the fill queue, a phantom cleanup then virtualised the filled slots
279
+ * (which NULLS their `orderId`), and the re-delivered fills were dropped AFTER
280
+ * their accounting had been booked. Neither the LAST-FILL-GUARD pivot nor the
281
+ * owed boundary crawl learned the execution price, so the pivot stayed on a
282
+ * stale, HIGHER value and the direction rule then allowed re-buys ABOVE the
283
+ * market (9 buy-lower violations, 23.5% of the window's BTS).
284
+ *
285
+ * Two identities, in order:
286
+ * 1. the slot that still owns the chain order id (any state — a virtualised
287
+ * slot can keep its id), or
288
+ * 2. the genesis ladder level the fill's own execution price maps to (the
289
+ * common case, because virtualisation clears the id).
290
+ *
291
+ * Only what the fill PROVES is recorded: the pivot, and — when the resolved
292
+ * slot is a hole — an owed boundary crawl. The slot and the already-booked
293
+ * accounting are never touched: the funds are the accountant's business, this
294
+ * only keeps the geometry honest. A price outside the frozen rail is refused,
295
+ * so a shelf/manual order can never arm the pivot at a level the grid does not
296
+ * trade.
297
+ *
298
+ * @param {Object} manager - OrderManager instance
299
+ * @param {Object} params - fill identity {orderId, pays/receives amount+asset, isPartial}
300
+ * @returns {boolean} true when the fill was attributed to the grid
301
+ */
302
+ declare function attributeUnmatchedFillToGrid(manager: OrderManagerLike, params: {
303
+ orderId?: string | null;
304
+ paysAssetId?: string | null;
305
+ paysAmountRaw?: number | null;
306
+ receivesAssetId?: string | null;
307
+ receivesAmountRaw?: number | null;
308
+ isPartial?: boolean;
309
+ }): boolean;
204
310
  /**
205
311
  * Find the live grid slot that currently owns a chain order.
206
312
  * When slotId is supplied, only that exact slot is considered; otherwise all
@@ -1455,7 +1561,7 @@ declare function collectKnownOnChainOrderIds(mgr: OrderManagerLike, placedResult
1455
1561
  createIds: string[];
1456
1562
  all: string[];
1457
1563
  };
1458
- export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, 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 };
1564
+ 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 };
1459
1565
  export type { CrawlEntry };
1460
1566
  export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
1461
1567
  //# sourceMappingURL=order.d.ts.map
@@ -326,6 +326,303 @@ function _stampCorrectionProvenance(entry, source) {
326
326
  }
327
327
  return entry;
328
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
+ }
329
626
  /**
330
627
  * Find the live grid slot that currently owns a chain order.
331
628
  * When slotId is supplied, only that exact slot is considered; otherwise all
@@ -3511,6 +3808,6 @@ function collectKnownOnChainOrderIds(mgr, placedResults, placedContexts, extraCr
3511
3808
  const all = new Set([...masterIds, ...createIds]);
3512
3809
  return { masterIds: [...masterIds], createIds: [...createIds], all: [...all] };
3513
3810
  }
3514
- export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, 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 };
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 };
3515
3812
  export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
3516
3813
  //# sourceMappingURL=order.js.map
@@ -551,10 +551,15 @@ export declare function reanchorBoundaryFromLastFill(manager: OrderManagerLike,
551
551
  * so this fallback covers only the window before that write, not the whole
552
552
  * post-rebuild lifetime.
553
553
  *
554
+ * LIFETIME: a fill reference older than GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS is
555
+ * ignored (read-time expiry, same bound the restore path applies), so a stale
556
+ * pivot cannot veto one side forever in a long-lived process. Unknown ages
557
+ * (missing timestamp) never expire.
558
+ *
554
559
  * @param {Object} manager - OrderManager instance
555
560
  * @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
556
561
  */
557
- export declare function resolveLastFillGuardReference(manager: OrderManagerLike): {
562
+ export declare function resolveLastFillGuardReference(manager: OrderManagerLike | null | undefined): {
558
563
  price: number | null;
559
564
  type: string | null;
560
565
  };
@@ -592,6 +597,53 @@ export declare function isLastFillGuardBlocked(price: number, type: unknown, las
592
597
  pivot: number | null;
593
598
  threshold?: number | null;
594
599
  };
600
+ /**
601
+ * LAST-FILL PLACEMENT GUARD — the direction rule applied to a PLACEMENT.
602
+ *
603
+ * Wraps isLastFillGuardBlocked with the same pivot resolution the runtime uses
604
+ * (live fill pivot, then the bot-scoped market-fill row) and adds the
605
+ * SAME-LEVEL refusal: a placement within half a grid step of the pivot is a
606
+ * re-place at the level that just traded, which the raw `>=`/`<=` comparison
607
+ * lets through because a slot price and its execution price differ by
608
+ * rounding (live: slot 1310.046339 filled at 1310.060435).
609
+ *
610
+ * Unlike the COW-path guard this is meant for the reconcile/startup placement
611
+ * paths (create + relocation), which previously had no last-fill check at all:
612
+ * a startup-style top-up could therefore re-create a BUY at the price the bot
613
+ * had just bought at, or place a BUY above it (the "buying later at higher
614
+ * prices" incident). Fail-open on a cold pivot (no fill yet) so a fresh grid
615
+ * still builds.
616
+ *
617
+ * @param {Object} manager - OrderManager instance (pivot + config.incrementPercent)
618
+ * @param {number} price - Target placement price
619
+ * @param {string} type - ORDER_TYPES.BUY / ORDER_TYPES.SELL
620
+ * @returns {{blocked: boolean, pivot: number|null, reason?: 'direction'|'same-level'}}
621
+ */
622
+ export declare function isLastFillPlacementBlocked(manager: OrderManagerLike | null | undefined, price: unknown, type: unknown): {
623
+ blocked: boolean;
624
+ pivot: number | null;
625
+ reason?: 'direction' | 'same-level';
626
+ };
627
+ /**
628
+ * Are fills still UNSETTLED (arrived but not yet absorbed by the grid)?
629
+ *
630
+ * While this returns true the master grid still holds filled slots as ACTIVE
631
+ * and the boundary has not crawled for them, so any geometry-derived plan
632
+ * (window top-up, startup-style reconcile) is built on the PREVIOUS book. The
633
+ * live incident: a 120s stale broadcast region deferred 12 fills, the
634
+ * post-fill reconcile saw "buy 12/20" on that stale master and re-created 8
635
+ * BUYs at the TOP of the un-crawled rail (1282.78 -> 1310.04), which filled
636
+ * within seconds (9 buy-lower violations, 23.5% of the window's BTS).
637
+ *
638
+ * Accepts a bot (its `manager` is inspected) or a bare manager.
639
+ *
640
+ * @param {Object} source - DEXBot-like or OrderManager-like instance
641
+ * @returns {{unsettled: boolean, reason: string|null}}
642
+ */
643
+ export declare function hasUnsettledFills(source: unknown): {
644
+ unsettled: boolean;
645
+ reason: string | null;
646
+ };
595
647
  /**
596
648
  * Restore the persisted bot-scoped last-market-fill reference into the
597
649
  * manager. Deliberately independent of the boundary and the genesis: this is
@@ -625,6 +677,16 @@ export declare function restoreLastMarketFill(manager: OrderManagerLike, persist
625
677
  * rewritten: an off-new-ladder value is handled by the same one-increment
626
678
  * `resolveOnGridPivot` rule every other probe uses.
627
679
  *
680
+ * The timestamp comes from the SAME row as the price (see
681
+ * resolveFillProvenancedRow). Reading `_lastFilledAt` unconditionally paired a
682
+ * market-row price with a book-seed clock: a book seed writes `_lastFilledAt`
683
+ * but never the market row, and `setLastFillPivot(..., 'fill')` then re-stamps
684
+ * `_lastMarketFillAt` with that newer time — refreshing the 24h lifetime on
685
+ * every rebuild until the row never expires.
686
+ *
687
+ * EXPIRED ROWS DO NOT RE-ARM (resolveFillProvenancedRow drops them), so the
688
+ * documented pivot lifetime holds with or without a restart.
689
+ *
628
690
  * @param {Object} manager - OrderManager instance
629
691
  * @returns {boolean} True when a pivot was re-armed
630
692
  */