dexbot 1.7.1 → 1.7.3
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.
- package/CHANGELOG.md +52 -0
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/grid_correction_check.d.ts +60 -1
- package/dist/analysis/grid_correction_check.js +268 -18
- package/dist/analysis/pivot_timeline.d.ts +78 -0
- package/dist/analysis/pivot_timeline.js +360 -0
- package/dist/market_adapter/utils/file_lock.js +16 -4
- package/dist/modules/account_bots.d.ts +7 -0
- package/dist/modules/account_bots.js +7 -5
- package/dist/modules/bot_defaults.js +6 -1
- package/dist/modules/constants.d.ts +14 -0
- package/dist/modules/constants.js +82 -2
- package/dist/modules/dexbot_class.d.ts +39 -0
- package/dist/modules/dexbot_class.js +86 -1
- package/dist/modules/dexbot_cow_runtime.d.ts +31 -1
- package/dist/modules/dexbot_cow_runtime.js +299 -75
- package/dist/modules/dexbot_maintenance_runtime.d.ts +32 -2
- package/dist/modules/dexbot_maintenance_runtime.js +196 -16
- package/dist/modules/dexbot_state_recovery.js +15 -1
- package/dist/modules/launcher/instance_lock.d.ts +27 -0
- package/dist/modules/launcher/instance_lock.js +131 -0
- package/dist/modules/node_flap_score.d.ts +6 -6
- package/dist/modules/node_flap_score.js +6 -6
- package/dist/modules/order/accounting.d.ts +9 -4
- package/dist/modules/order/accounting.js +89 -26
- package/dist/modules/order/async_lock.d.ts +7 -1
- package/dist/modules/order/async_lock.js +7 -1
- package/dist/modules/order/export.js +25 -18
- package/dist/modules/order/fill_ledger.d.ts +99 -0
- package/dist/modules/order/fill_ledger.js +103 -0
- package/dist/modules/order/grid.d.ts +94 -18
- package/dist/modules/order/grid.js +247 -75
- package/dist/modules/order/grid_reconcile_internal.js +16 -4
- package/dist/modules/order/index.d.ts +29 -6
- package/dist/modules/order/index.js +5 -5
- package/dist/modules/order/lifecycle.js +3 -3
- package/dist/modules/order/manager.d.ts +36 -24
- package/dist/modules/order/manager.js +159 -39
- package/dist/modules/order/placement_lock.d.ts +30 -0
- package/dist/modules/order/placement_lock.js +48 -0
- package/dist/modules/order/sync_engine.d.ts +66 -118
- package/dist/modules/order/sync_engine.js +118 -162
- package/dist/modules/order/utils/math.d.ts +7 -3
- package/dist/modules/order/utils/math.js +7 -3
- package/dist/modules/order/utils/order.d.ts +79 -42
- package/dist/modules/order/utils/order.js +183 -86
- package/dist/modules/order/utils/system.d.ts +192 -8
- package/dist/modules/order/utils/system.js +534 -34
- package/dist/modules/paths.d.ts +1 -0
- package/dist/modules/paths.js +1 -0
- package/dist/modules/timing_policy.js +4 -2
- package/dist/modules/types.d.ts +49 -27
- package/dist/pm2.js +126 -0
- package/dist/unlock.js +26 -1
- package/docs/COW_INVARIANTS.md +5 -1
- package/docs/DEXBOT_COMPARISON.md +5 -5
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/GRID_RECONCILE.md +3 -3
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +192 -31
- package/docs/README.md +1 -1
- package/docs/architecture.md +26 -8
- package/modules/README.md +4 -0
- package/package.json +4 -3
|
@@ -5,10 +5,10 @@
|
|
|
5
5
|
* Includes grid indexing, order comparison, delta building, and strategy calculations.
|
|
6
6
|
*
|
|
7
7
|
* ===============================================================================
|
|
8
|
-
* TABLE OF CONTENTS (
|
|
8
|
+
* TABLE OF CONTENTS (82 exported functions)
|
|
9
9
|
* ===============================================================================
|
|
10
10
|
*
|
|
11
|
-
* SECTION 1: CHAIN ORDER MATCHING & RECONCILIATION (
|
|
11
|
+
* SECTION 1: CHAIN ORDER MATCHING & RECONCILIATION (11 functions)
|
|
12
12
|
* - parseChainOrder(chainOrder, assets) - Parse blockchain order to grid format
|
|
13
13
|
* - applyChainSizeToGridOrder(manager, gridOrder, chainSize) - Apply chain size to grid
|
|
14
14
|
* - correctOrderPriceOnChain(manager, correctionInfo, ...) - Correct order price on chain
|
|
@@ -16,6 +16,10 @@
|
|
|
16
16
|
* - _validatePriceCorrectionEntry(...) - Drain-time staleness check for a queued correction
|
|
17
17
|
* - _stampCorrectionProvenance(...) - Stamp queue provenance on a correction entry
|
|
18
18
|
* - findLiveOrderOwnerByChainId(...) - Find the live grid slot that owns a chain order
|
|
19
|
+
* - resolveLiveOrderLadderPosition(...) - Ladder position of a live chain order
|
|
20
|
+
* - resolveExecutionPrice(...) - Execution price from the paid/received amounts
|
|
21
|
+
* - resolveSlotIdForFillPrice(...) - Slot a fill price belongs to under the genesis ladder
|
|
22
|
+
* - attributeUnmatchedFillToGrid(...) - Attribute a fill whose slot was already virtualised
|
|
19
23
|
*
|
|
20
24
|
* SECTION 2: CROSSING-PLACEMENT GUARDS (8 functions)
|
|
21
25
|
* - chainOrderMatchesSlot(...) - Exact chain-order/grid-slot match
|
|
@@ -25,17 +29,19 @@
|
|
|
25
29
|
* - buildCrossingCheckCandidates(...) - Candidate set for crossing-placement checks
|
|
26
30
|
* - chainOrderUnchangedFromCache(...) - Chain order still matches cached pre-update state
|
|
27
31
|
* - detectCrossedBookPlan(...) - Pre-broadcast crossed-book assert
|
|
32
|
+
* - describeMarketCrossingActions(...) - Observe actions priced across the market floor
|
|
28
33
|
* - collectKnownOnChainOrderIds(...) - On-chain ids master must converge against
|
|
29
34
|
*
|
|
30
35
|
* SECTION 3: ORDER CONSTRUCTION (5 functions)
|
|
31
36
|
* - buildCreateOrderArgs(order, assetA, assetB) - Build create order arguments
|
|
32
37
|
* - getOrderTypeFromUpdatedFlags(buyUpdated, sellUpdated) - Get type from update flags
|
|
33
38
|
* - resolveConfiguredPriceBound(value, fallback, startPrice, mode) - Resolve price bounds
|
|
34
|
-
* - buildFillKey(fillOrParts) -
|
|
39
|
+
* - buildFillKey(fillOrParts) - Stable fill dedupe key (delegates to order/fill_ledger.ts)
|
|
35
40
|
* - buildCreateOpFingerprint(params) - Build fingerprint for create operations
|
|
36
41
|
*
|
|
37
|
-
* SECTION 4: STATE TRANSITIONS & PLACEHOLDERS (
|
|
42
|
+
* SECTION 4: STATE TRANSITIONS & PLACEHOLDERS (7 functions)
|
|
38
43
|
* - virtualizeOrder(order) - Convert order to VIRTUAL state
|
|
44
|
+
* - reviveVirtualSlotFromChain(...) - Re-materialise a virtualised slot from its chain order
|
|
39
45
|
* - convertToSpreadPlaceholder(order) - Convert order to SPREAD placeholder
|
|
40
46
|
* - toRailHolePlaceholder(order) - Convert to a rail-typed hole placeholder
|
|
41
47
|
* - geometryTypeForSlotIndex(...) - BUY/SELL type for a slot index
|
|
@@ -47,8 +53,9 @@
|
|
|
47
53
|
* - updateGapEvacuationStreaks(...) - Tick per-slot gap-evacuation streak counter
|
|
48
54
|
* - collectRefillSlotIds(...) - Refill-slot wire for the COW boundary hold
|
|
49
55
|
*
|
|
50
|
-
* SECTION 6: FILTERING & DRIFT DIAGNOSTICS (
|
|
56
|
+
* SECTION 6: FILTERING & DRIFT DIAGNOSTICS (12 functions)
|
|
51
57
|
* - filterOrdersByType(orders, orderType) - Filter orders by type
|
|
58
|
+
* - isStructuralRebuildStaleReason(reason) - Whether a refusal label means a structural rebuild
|
|
52
59
|
* - buildOutsideInPairGroups(items, accessors) - Outside->center pair grouping
|
|
53
60
|
* - extractBatchOperationResults(result) - Extract operation_results from chain batch result
|
|
54
61
|
* - formatUnmatchedChainOrder(order) - Format structural drift diagnostics
|
|
@@ -106,13 +113,18 @@
|
|
|
106
113
|
* - checkGridPriceInvariant(...) - The price emitted for a slot must equal its genesis price
|
|
107
114
|
* - reportGridPriceInvariant(...) - Report one GRID-PRICE-INVARIANT check
|
|
108
115
|
*
|
|
109
|
-
* SECTION 14: PERSISTED CRAWL & PLACEMENT GRACE (
|
|
116
|
+
* SECTION 14: PERSISTED CRAWL & PLACEMENT GRACE (2 functions + the CrawlEntry type)
|
|
110
117
|
* - consumePendingFillCrawls(...) - Apply recorded-but-uncommitted fill crawls to the boundary
|
|
111
|
-
* - recordOrderPlacement(...) - Record a fresh on-chain placement timestamp
|
|
112
118
|
* - isFreshlyPlacedOrder(...) - Chain order placed within the surplus-cancel grace
|
|
119
|
+
* (the stamp itself is written only by the lifecycle funnel)
|
|
120
|
+
*
|
|
121
|
+
* SECTION 15: LIVE BROADCAST & EDGE PROJECTIONS (2 functions)
|
|
122
|
+
* - getLivePendingBroadcasts(manager, options?) - Live pending-broadcast list (expired entries deleted)
|
|
123
|
+
* - collectEdgePinnedFillIds(manager, fills) - Fill ids pinned to the configured/live edge
|
|
113
124
|
*
|
|
114
125
|
* ===============================================================================
|
|
115
126
|
*/
|
|
127
|
+
import { fillKeyOf } from '../fill_ledger.js';
|
|
116
128
|
import type { PlacementLease } from '../placement_lock.js';
|
|
117
129
|
import type { OrderManagerLike, PendingPriceCorrection, ChainOrder, ParsedChainOrder, AssetPair, AssetInfo, OrderType, ManagedOrder, UnmatchedChainOrder, CowAction, ProjectedFunds } from '../../types.js';
|
|
118
130
|
import type { GridGenesis } from './math.js';
|
|
@@ -190,21 +202,6 @@ declare function duplicateOrphanLogInfo(orderId: string | null | undefined): {
|
|
|
190
202
|
suffix: string;
|
|
191
203
|
};
|
|
192
204
|
declare function _filterUnmatchedChainOrders(manager: OrderManagerLike, chainOrderId: string): void;
|
|
193
|
-
/**
|
|
194
|
-
* Record a fresh on-chain placement timestamp for surplus-cancel grace.
|
|
195
|
-
* Powers isFreshlyPlacedOrder below.
|
|
196
|
-
*
|
|
197
|
-
* NOTE: in production the placement stamp is written by the lifecycle write
|
|
198
|
-
* funnel (`OrderManager._syncLifecycleFromMutation` -> `markPlaced`) for every
|
|
199
|
-
* mutation, including the COW whole-map commit. This helper remains for callers
|
|
200
|
-
* that hold only a manager-shaped object (tests, fixtures) and for the `_placedAt`
|
|
201
|
-
* retention bound; it writes through the same facade, so there is still one copy
|
|
202
|
-
* of the stamp.
|
|
203
|
-
*
|
|
204
|
-
* @param {unknown} manager - OrderManager instance (owns `_placedAt`)
|
|
205
|
-
* @param {string} chainOrderId - Chain order id that was just placed
|
|
206
|
-
*/
|
|
207
|
-
declare function recordOrderPlacement(manager: OrderManagerLike, chainOrderId: string | null | undefined): void;
|
|
208
205
|
/**
|
|
209
206
|
* True when the chain order was placed within the surplus-cancel grace
|
|
210
207
|
* window. Surplus sweeps must skip such orders: a fill landing between two
|
|
@@ -366,11 +363,17 @@ declare function findLiveOrderOwnerByChainId(manager: OrderManagerLike, chainOrd
|
|
|
366
363
|
* replayed cancel would then destroy the freshly updated in-place order.
|
|
367
364
|
*
|
|
368
365
|
* Type-mismatch and gap-evacuation surplus decisions have their own source-
|
|
369
|
-
* specific checks. A type mismatch is actionable
|
|
370
|
-
*
|
|
371
|
-
*
|
|
372
|
-
*
|
|
373
|
-
*
|
|
366
|
+
* specific checks. A type mismatch is actionable while the same live slot
|
|
367
|
+
* still owns the id AND (its stored type OR its rail geometry — index vs
|
|
368
|
+
* boundary, including the gap band) still disagrees with the chain side. A
|
|
369
|
+
* stored type that a fill (or another in-place writer) retagged to the chain
|
|
370
|
+
* side is NOT a repair on its own: an order can carry the chain's side while
|
|
371
|
+
* sitting on the opposite rail or inside the band, and dropping the cancel
|
|
372
|
+
* there would let the residual rest on the wrong side (2026-11-04 incident).
|
|
373
|
+
* A gap evacuation is actionable only while the same live slot remains in the
|
|
374
|
+
* current gap band. Both otherwise use the old cancellation branch, so
|
|
375
|
+
* allowing either decision to replay would recreate the same stale-replay
|
|
376
|
+
* regression.
|
|
374
377
|
*
|
|
375
378
|
* @param {Object} manager - OrderManager instance (live grid + assets)
|
|
376
379
|
* @param {Object} entry - Queued correction entry
|
|
@@ -404,22 +407,18 @@ declare function parseChainOrder(chainOrder: ChainOrder | null | undefined, asse
|
|
|
404
407
|
*/
|
|
405
408
|
declare function applyChainSizeToGridOrder(manager: OrderManagerLike, gridOrder: ManagedOrder, chainSize: number | string | null | undefined): Promise<ManagedOrder | null>;
|
|
406
409
|
/**
|
|
407
|
-
* Build a stable fill dedupe key
|
|
408
|
-
*
|
|
409
|
-
*
|
|
410
|
-
*
|
|
410
|
+
* Build a stable fill dedupe key: `orderId:blockNum:historyId`.
|
|
411
|
+
*
|
|
412
|
+
* Delegates to `order/fill_ledger.ts` — the single owner of fill identity.
|
|
413
|
+
* Kept exported under this name because `dexbot_fill_runtime` resolves it
|
|
414
|
+
* through a lazy shim and the orphan path reuses it. Returns null when a
|
|
415
|
+
* required field is missing: callers skip dedup rather than operate on a
|
|
416
|
+
* degraded key.
|
|
411
417
|
*
|
|
412
418
|
* @param {Object} fillOrParts - Fill entry ({ op, block_num, id }) or { orderId, blockNum, historyId }
|
|
413
|
-
* @returns {string|null} Stable key
|
|
419
|
+
* @returns {string|null} Stable key, or null if fields are missing
|
|
414
420
|
*/
|
|
415
|
-
declare
|
|
416
|
-
op?: unknown[];
|
|
417
|
-
orderId?: string;
|
|
418
|
-
block_num?: number;
|
|
419
|
-
blockNum?: number;
|
|
420
|
-
id?: string;
|
|
421
|
-
historyId?: string;
|
|
422
|
-
} | null | undefined): string | null;
|
|
421
|
+
declare const buildFillKey: typeof fillKeyOf;
|
|
423
422
|
/**
|
|
424
423
|
* Correct a single order's price on blockchain.
|
|
425
424
|
* Cancels surplus orders; updates price for others.
|
|
@@ -821,6 +820,7 @@ declare function isCrossingCheckCandidate(o: CrossingCandidate | null | undefine
|
|
|
821
820
|
*/
|
|
822
821
|
declare function getLivePendingBroadcasts(manager: OrderManagerLike | null | undefined, options?: {
|
|
823
822
|
now?: number;
|
|
823
|
+
gc?: boolean;
|
|
824
824
|
}): unknown[];
|
|
825
825
|
/**
|
|
826
826
|
* Shared candidate set for crossing-placement checks: master orders plus
|
|
@@ -1592,6 +1592,43 @@ declare function chainOrderUnchangedFromCache(chainOrder: ChainOrder | null | un
|
|
|
1592
1592
|
* Detector only: any internal failure returns null (never blocks a broadcast).
|
|
1593
1593
|
*/
|
|
1594
1594
|
declare function detectCrossedBookPlan(manager: OrderManagerLike, actions: CowAction[]): string | null;
|
|
1595
|
+
/**
|
|
1596
|
+
* Describe batch actions whose result price sits on the WRONG side of the
|
|
1597
|
+
* market floor — the EVIDENCE for the crossing OBSERVATION.
|
|
1598
|
+
*
|
|
1599
|
+
* Retrospective §9.10/P4 is explicit that this class must not be a hard veto:
|
|
1600
|
+
* "a hard veto re-opens the counter-order deadlock: after a gap the counter
|
|
1601
|
+
* sits across the floor by construction and executes at the best available
|
|
1602
|
+
* price. Made visible instead." A pre-broadcast version that dropped the
|
|
1603
|
+
* actions (and refused the batch when nothing remained) re-created exactly
|
|
1604
|
+
* that deadlock live on 2026-11-15: the only repair for an out-of-spread rail
|
|
1605
|
+
* was priced above a cached mid, the batch was refused, and the grid stayed
|
|
1606
|
+
* 3.0% wide (limit 1.65%) until the mid happened to move 86 minutes later.
|
|
1607
|
+
*
|
|
1608
|
+
* Evidence: the SHARED recency-aware floor (resolveSpreadCrossingFloor — an
|
|
1609
|
+
* executed trade is fresher truth than an older book read). The rejected
|
|
1610
|
+
* implementation re-derived its own reference from manager._liveMarketPrice
|
|
1611
|
+
* behind a 15-minute window, i.e. a second answer to "where is the market?":
|
|
1612
|
+
* live, that mid was 8 minutes old, had itself been the midpoint of the bot's
|
|
1613
|
+
* own book, and the five fills in hand (all newer than the mid, the last one
|
|
1614
|
+
* 4.4% above it) had already falsified it. The same batch, at identical
|
|
1615
|
+
* prices, was accepted at the next tick once a fresher read existed.
|
|
1616
|
+
*
|
|
1617
|
+
* CANCELs are never reported: a cancel cannot cross anything. Fail-open on
|
|
1618
|
+
* every unprovable case (no floor, malformed action).
|
|
1619
|
+
*
|
|
1620
|
+
* @param {Object} manager - OrderManager instance
|
|
1621
|
+
* @param {Array} actions - COW batch actions (never mutated)
|
|
1622
|
+
* @returns {{ floor: number|null, dropped: Array<{ index: number, action: Object, reason: string }> }}
|
|
1623
|
+
*/
|
|
1624
|
+
declare function describeMarketCrossingActions(manager: OrderManagerLike, actions: CowAction[]): {
|
|
1625
|
+
floor: number | null;
|
|
1626
|
+
dropped: Array<{
|
|
1627
|
+
index: number;
|
|
1628
|
+
action: CowAction;
|
|
1629
|
+
reason: string;
|
|
1630
|
+
}>;
|
|
1631
|
+
};
|
|
1595
1632
|
/**
|
|
1596
1633
|
* Collect every on-chain order id master currently needs to converge against,
|
|
1597
1634
|
* so adoption can re-read them by id (immune to the get_full_accounts window
|
|
@@ -1631,7 +1668,7 @@ declare function collectKnownOnChainOrderIds(mgr: OrderManagerLike, placedResult
|
|
|
1631
1668
|
createIds: string[];
|
|
1632
1669
|
all: string[];
|
|
1633
1670
|
};
|
|
1634
|
-
export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, resolveExecutionPrice, resolveSlotIdForFillPrice, reviveVirtualSlotFromChain, attributeUnmatchedFillToGrid, getLivePendingBroadcasts, 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, isStructuralRebuildStaleReason, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, collectEdgePinnedFillIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
|
|
1671
|
+
export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, resolveExecutionPrice, resolveSlotIdForFillPrice, reviveVirtualSlotFromChain, attributeUnmatchedFillToGrid, getLivePendingBroadcasts, 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, isStructuralRebuildStaleReason, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, describeMarketCrossingActions, collectKnownOnChainOrderIds, collectEdgePinnedFillIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
|
|
1635
1672
|
export type { CrawlEntry };
|
|
1636
|
-
export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds,
|
|
1673
|
+
export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
|
|
1637
1674
|
//# sourceMappingURL=order.d.ts.map
|
|
@@ -5,10 +5,10 @@
|
|
|
5
5
|
* Includes grid indexing, order comparison, delta building, and strategy calculations.
|
|
6
6
|
*
|
|
7
7
|
* ===============================================================================
|
|
8
|
-
* TABLE OF CONTENTS (
|
|
8
|
+
* TABLE OF CONTENTS (82 exported functions)
|
|
9
9
|
* ===============================================================================
|
|
10
10
|
*
|
|
11
|
-
* SECTION 1: CHAIN ORDER MATCHING & RECONCILIATION (
|
|
11
|
+
* SECTION 1: CHAIN ORDER MATCHING & RECONCILIATION (11 functions)
|
|
12
12
|
* - parseChainOrder(chainOrder, assets) - Parse blockchain order to grid format
|
|
13
13
|
* - applyChainSizeToGridOrder(manager, gridOrder, chainSize) - Apply chain size to grid
|
|
14
14
|
* - correctOrderPriceOnChain(manager, correctionInfo, ...) - Correct order price on chain
|
|
@@ -16,6 +16,10 @@
|
|
|
16
16
|
* - _validatePriceCorrectionEntry(...) - Drain-time staleness check for a queued correction
|
|
17
17
|
* - _stampCorrectionProvenance(...) - Stamp queue provenance on a correction entry
|
|
18
18
|
* - findLiveOrderOwnerByChainId(...) - Find the live grid slot that owns a chain order
|
|
19
|
+
* - resolveLiveOrderLadderPosition(...) - Ladder position of a live chain order
|
|
20
|
+
* - resolveExecutionPrice(...) - Execution price from the paid/received amounts
|
|
21
|
+
* - resolveSlotIdForFillPrice(...) - Slot a fill price belongs to under the genesis ladder
|
|
22
|
+
* - attributeUnmatchedFillToGrid(...) - Attribute a fill whose slot was already virtualised
|
|
19
23
|
*
|
|
20
24
|
* SECTION 2: CROSSING-PLACEMENT GUARDS (8 functions)
|
|
21
25
|
* - chainOrderMatchesSlot(...) - Exact chain-order/grid-slot match
|
|
@@ -25,17 +29,19 @@
|
|
|
25
29
|
* - buildCrossingCheckCandidates(...) - Candidate set for crossing-placement checks
|
|
26
30
|
* - chainOrderUnchangedFromCache(...) - Chain order still matches cached pre-update state
|
|
27
31
|
* - detectCrossedBookPlan(...) - Pre-broadcast crossed-book assert
|
|
32
|
+
* - describeMarketCrossingActions(...) - Observe actions priced across the market floor
|
|
28
33
|
* - collectKnownOnChainOrderIds(...) - On-chain ids master must converge against
|
|
29
34
|
*
|
|
30
35
|
* SECTION 3: ORDER CONSTRUCTION (5 functions)
|
|
31
36
|
* - buildCreateOrderArgs(order, assetA, assetB) - Build create order arguments
|
|
32
37
|
* - getOrderTypeFromUpdatedFlags(buyUpdated, sellUpdated) - Get type from update flags
|
|
33
38
|
* - resolveConfiguredPriceBound(value, fallback, startPrice, mode) - Resolve price bounds
|
|
34
|
-
* - buildFillKey(fillOrParts) -
|
|
39
|
+
* - buildFillKey(fillOrParts) - Stable fill dedupe key (delegates to order/fill_ledger.ts)
|
|
35
40
|
* - buildCreateOpFingerprint(params) - Build fingerprint for create operations
|
|
36
41
|
*
|
|
37
|
-
* SECTION 4: STATE TRANSITIONS & PLACEHOLDERS (
|
|
42
|
+
* SECTION 4: STATE TRANSITIONS & PLACEHOLDERS (7 functions)
|
|
38
43
|
* - virtualizeOrder(order) - Convert order to VIRTUAL state
|
|
44
|
+
* - reviveVirtualSlotFromChain(...) - Re-materialise a virtualised slot from its chain order
|
|
39
45
|
* - convertToSpreadPlaceholder(order) - Convert order to SPREAD placeholder
|
|
40
46
|
* - toRailHolePlaceholder(order) - Convert to a rail-typed hole placeholder
|
|
41
47
|
* - geometryTypeForSlotIndex(...) - BUY/SELL type for a slot index
|
|
@@ -47,8 +53,9 @@
|
|
|
47
53
|
* - updateGapEvacuationStreaks(...) - Tick per-slot gap-evacuation streak counter
|
|
48
54
|
* - collectRefillSlotIds(...) - Refill-slot wire for the COW boundary hold
|
|
49
55
|
*
|
|
50
|
-
* SECTION 6: FILTERING & DRIFT DIAGNOSTICS (
|
|
56
|
+
* SECTION 6: FILTERING & DRIFT DIAGNOSTICS (12 functions)
|
|
51
57
|
* - filterOrdersByType(orders, orderType) - Filter orders by type
|
|
58
|
+
* - isStructuralRebuildStaleReason(reason) - Whether a refusal label means a structural rebuild
|
|
52
59
|
* - buildOutsideInPairGroups(items, accessors) - Outside->center pair grouping
|
|
53
60
|
* - extractBatchOperationResults(result) - Extract operation_results from chain batch result
|
|
54
61
|
* - formatUnmatchedChainOrder(order) - Format structural drift diagnostics
|
|
@@ -106,10 +113,14 @@
|
|
|
106
113
|
* - checkGridPriceInvariant(...) - The price emitted for a slot must equal its genesis price
|
|
107
114
|
* - reportGridPriceInvariant(...) - Report one GRID-PRICE-INVARIANT check
|
|
108
115
|
*
|
|
109
|
-
* SECTION 14: PERSISTED CRAWL & PLACEMENT GRACE (
|
|
116
|
+
* SECTION 14: PERSISTED CRAWL & PLACEMENT GRACE (2 functions + the CrawlEntry type)
|
|
110
117
|
* - consumePendingFillCrawls(...) - Apply recorded-but-uncommitted fill crawls to the boundary
|
|
111
|
-
* - recordOrderPlacement(...) - Record a fresh on-chain placement timestamp
|
|
112
118
|
* - isFreshlyPlacedOrder(...) - Chain order placed within the surplus-cancel grace
|
|
119
|
+
* (the stamp itself is written only by the lifecycle funnel)
|
|
120
|
+
*
|
|
121
|
+
* SECTION 15: LIVE BROADCAST & EDGE PROJECTIONS (2 functions)
|
|
122
|
+
* - getLivePendingBroadcasts(manager, options?) - Live pending-broadcast list (expired entries deleted)
|
|
123
|
+
* - collectEdgePinnedFillIds(manager, fills) - Fill ids pinned to the configured/live edge
|
|
113
124
|
*
|
|
114
125
|
* ===============================================================================
|
|
115
126
|
*/
|
|
@@ -117,10 +128,11 @@ import { ORDER_TYPES, ORDER_STATES, TIMING, FEE_PARAMETERS, GRID_LIMITS, NATIVE_
|
|
|
117
128
|
import * as Format from '../format.js';
|
|
118
129
|
import * as MathUtils from './math.js';
|
|
119
130
|
import Logger from '../../order/logger.js';
|
|
120
|
-
import { sleep } from './system.js';
|
|
131
|
+
import { sleep, resolveSpreadCrossingFloor } from './system.js';
|
|
121
132
|
import { getErrorMessage, getErrorCode, getErrorName } from '../../utils/errors.js';
|
|
122
133
|
import { hasGenesisLadder } from '../genesis_policy.js';
|
|
123
134
|
import { parseSlotIndex } from './slot.js';
|
|
135
|
+
import { fillKeyOf, resolveTradedSide } from '../fill_ledger.js';
|
|
124
136
|
import { pendingBroadcastTtlMs } from '../lifecycle.js';
|
|
125
137
|
const { isValidNumber, toFiniteNumber } = Format;
|
|
126
138
|
const { blockchainToFloat, floatToBlockchainInt, quantizeFloat, slotIndexForPrice, priceSlotEqual } = MathUtils;
|
|
@@ -264,40 +276,6 @@ function _filterUnmatchedChainOrders(manager, chainOrderId) {
|
|
|
264
276
|
manager._lastUnmatchedChainOrders = manager._lastUnmatchedChainOrders.filter((u) => (u?.id || u?.orderId || u?.chainOrderId) !== chainOrderId);
|
|
265
277
|
}
|
|
266
278
|
}
|
|
267
|
-
/**
|
|
268
|
-
* Record a fresh on-chain placement timestamp for surplus-cancel grace.
|
|
269
|
-
* Powers isFreshlyPlacedOrder below.
|
|
270
|
-
*
|
|
271
|
-
* NOTE: in production the placement stamp is written by the lifecycle write
|
|
272
|
-
* funnel (`OrderManager._syncLifecycleFromMutation` -> `markPlaced`) for every
|
|
273
|
-
* mutation, including the COW whole-map commit. This helper remains for callers
|
|
274
|
-
* that hold only a manager-shaped object (tests, fixtures) and for the `_placedAt`
|
|
275
|
-
* retention bound; it writes through the same facade, so there is still one copy
|
|
276
|
-
* of the stamp.
|
|
277
|
-
*
|
|
278
|
-
* @param {unknown} manager - OrderManager instance (owns `_placedAt`)
|
|
279
|
-
* @param {string} chainOrderId - Chain order id that was just placed
|
|
280
|
-
*/
|
|
281
|
-
function recordOrderPlacement(manager, chainOrderId) {
|
|
282
|
-
try {
|
|
283
|
-
if (!manager || chainOrderId == null || String(chainOrderId).length === 0)
|
|
284
|
-
return;
|
|
285
|
-
// Writing through the facade records `placedAt` on the lifecycle record
|
|
286
|
-
// (one clock, one owner) — no separate grace bookkeeping to keep in sync.
|
|
287
|
-
if (!(manager._placedAt instanceof Map))
|
|
288
|
-
manager._placedAt = new Map();
|
|
289
|
-
manager._placedAt.set(String(chainOrderId), Date.now());
|
|
290
|
-
// Lazy GC: placement timestamps only matter inside the grace window.
|
|
291
|
-
if (manager._placedAt.size > 500) {
|
|
292
|
-
const cutoff = Date.now() - TIMING.SURPLUS_CANCEL_GRACE_MS * 2;
|
|
293
|
-
for (const [id, ts] of manager._placedAt) {
|
|
294
|
-
if (Number(ts) < cutoff)
|
|
295
|
-
manager._placedAt.delete(id);
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
catch { /* bookkeeping must never break placement */ }
|
|
300
|
-
}
|
|
301
279
|
/**
|
|
302
280
|
* True when the chain order was placed within the surplus-cancel grace
|
|
303
281
|
* window. Surplus sweeps must skip such orders: a fill landing between two
|
|
@@ -331,6 +309,30 @@ function isFreshlyPlacedOrder(manager, chainOrderId, graceMs) {
|
|
|
331
309
|
return false;
|
|
332
310
|
}
|
|
333
311
|
}
|
|
312
|
+
/**
|
|
313
|
+
* Whether a cancel-class correction must be held back by the fresh-placement
|
|
314
|
+
* grace window.
|
|
315
|
+
*
|
|
316
|
+
* Type mismatches are deliberately EXEMPT. The grace exists so a fill landing
|
|
317
|
+
* between two controllers' count snapshots cannot get a seconds-old placement
|
|
318
|
+
* cancelled (surplus/duplicate churn). A live order on the WRONG side is not
|
|
319
|
+
* that race: it is a known-wrong order, and the next fill is classified from
|
|
320
|
+
* the slot's (wrong) side — a sell on a slot retyped BUY produced a
|
|
321
|
+
* `filledAmount=0` phantom fill, a dust cancel and a re-buy at the fill level
|
|
322
|
+
* (2026-11-04 live incident). The 15-minute SURPLUS_CANCEL_GRACE_MS is correct
|
|
323
|
+
* for surplus churn, not for a side that can corrupt fill accounting; the
|
|
324
|
+
* entry's own `_validatePriceCorrectionEntry` gate already drops it once the
|
|
325
|
+
* slot no longer owns the order or the side was repaired.
|
|
326
|
+
*
|
|
327
|
+
* @param {Object} manager - OrderManager instance
|
|
328
|
+
* @param {Object} entry - Queued correction entry
|
|
329
|
+
* @returns {boolean} True when the cancel should stay queued for this cycle
|
|
330
|
+
*/
|
|
331
|
+
function shouldDeferFreshCancel(manager, entry) {
|
|
332
|
+
if (!entry || entry.typeMismatch === true)
|
|
333
|
+
return false;
|
|
334
|
+
return isFreshlyPlacedOrder(manager, entry.chainOrderId);
|
|
335
|
+
}
|
|
334
336
|
/**
|
|
335
337
|
* Remove a single correction entry by its full queue key
|
|
336
338
|
* (chainOrderId + surplus flag). The queue's upsert key is
|
|
@@ -576,19 +578,11 @@ function attributeUnmatchedFillToGrid(manager, params) {
|
|
|
576
578
|
}
|
|
577
579
|
}
|
|
578
580
|
}
|
|
579
|
-
// Side from the asset that was PAID
|
|
580
|
-
// base, paying the base sells it. Independent of
|
|
581
|
-
// fill
|
|
582
|
-
//
|
|
583
|
-
|
|
584
|
-
if (input.paysAssetId === assets.assetB.id)
|
|
585
|
-
type = ORDER_TYPES.BUY;
|
|
586
|
-
else if (input.paysAssetId === assets.assetA.id)
|
|
587
|
-
type = ORDER_TYPES.SELL;
|
|
588
|
-
if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL && slot
|
|
589
|
-
&& (slot.type === ORDER_TYPES.BUY || slot.type === ORDER_TYPES.SELL)) {
|
|
590
|
-
type = slot.type;
|
|
591
|
-
}
|
|
581
|
+
// Side from the asset that was PAID (order/fill_ledger.ts): paying the
|
|
582
|
+
// quote buys the base, paying the base sells it. Independent of the slot
|
|
583
|
+
// type; a malformed fill with no pays asset falls back to the slot's type
|
|
584
|
+
// and the side is never guessed from the price.
|
|
585
|
+
const type = resolveTradedSide(input.paysAssetId, assets, slot?.type);
|
|
592
586
|
if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
|
|
593
587
|
return false;
|
|
594
588
|
const execPrice = resolveExecutionPrice(assets, input.paysAssetId, input.paysAmountRaw, input.receivesAssetId, input.receivesAmountRaw);
|
|
@@ -705,11 +699,17 @@ function findLiveOrderOwnerByChainId(manager, chainOrderId, slotId) {
|
|
|
705
699
|
* replayed cancel would then destroy the freshly updated in-place order.
|
|
706
700
|
*
|
|
707
701
|
* Type-mismatch and gap-evacuation surplus decisions have their own source-
|
|
708
|
-
* specific checks. A type mismatch is actionable
|
|
709
|
-
*
|
|
710
|
-
*
|
|
711
|
-
*
|
|
712
|
-
*
|
|
702
|
+
* specific checks. A type mismatch is actionable while the same live slot
|
|
703
|
+
* still owns the id AND (its stored type OR its rail geometry — index vs
|
|
704
|
+
* boundary, including the gap band) still disagrees with the chain side. A
|
|
705
|
+
* stored type that a fill (or another in-place writer) retagged to the chain
|
|
706
|
+
* side is NOT a repair on its own: an order can carry the chain's side while
|
|
707
|
+
* sitting on the opposite rail or inside the band, and dropping the cancel
|
|
708
|
+
* there would let the residual rest on the wrong side (2026-11-04 incident).
|
|
709
|
+
* A gap evacuation is actionable only while the same live slot remains in the
|
|
710
|
+
* current gap band. Both otherwise use the old cancellation branch, so
|
|
711
|
+
* allowing either decision to replay would recreate the same stale-replay
|
|
712
|
+
* regression.
|
|
713
713
|
*
|
|
714
714
|
* @param {Object} manager - OrderManager instance (live grid + assets)
|
|
715
715
|
* @param {Object} entry - Queued correction entry
|
|
@@ -735,10 +735,20 @@ function _validatePriceCorrectionEntry(manager, entry) {
|
|
|
735
735
|
if (!slot) {
|
|
736
736
|
return { valid: false, reason: `type-mismatch target ${slotId || '?'} no longer owns ${entry.chainOrderId}` };
|
|
737
737
|
}
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
738
|
+
// The stored type alone is not proof of a repair: a fill (or another
|
|
739
|
+
// in-place writer) may have retagged the slot to the CHAIN side while
|
|
740
|
+
// the level still belongs to the opposite rail. Only a level whose
|
|
741
|
+
// rail geometry also matches the chain side is genuinely repaired.
|
|
742
|
+
// A resolved SPREAD geometry (gap band) also contradicts a rail side:
|
|
743
|
+
// no order should rest there, so the cancel must survive. Geometry is
|
|
744
|
+
// index-vs-boundary, so an unknown boundary falls back to the
|
|
745
|
+
// stored-type check (fail-safe: never invent a rail).
|
|
746
|
+
const geometryType = geometryTypeForSlotIndex(parseSlotIndex(slot.id), manager?.boundaryIdx, manager?._gapSlots);
|
|
747
|
+
const geometryContradicts = geometryType !== null && geometryType !== targetType;
|
|
748
|
+
if (!targetType || (slot.type === targetType && !geometryContradicts)) {
|
|
749
|
+
return { valid: false, reason: `type-mismatch for ${entry.chainOrderId} was repaired (${slot.type} now matches ${targetType || 'chain type'} on the ${geometryType || 'unknown'} rail)` };
|
|
750
|
+
}
|
|
751
|
+
return { valid: true, reason: geometryContradicts ? 'type-mismatch-still-live-geometry' : 'type-mismatch-still-live' };
|
|
742
752
|
}
|
|
743
753
|
if (entry.gapEvacuation === true) {
|
|
744
754
|
const slotId = entry?.gridOrder?.id;
|
|
@@ -904,23 +914,18 @@ async function applyChainSizeToGridOrder(manager, gridOrder, chainSize) {
|
|
|
904
914
|
return updatedOrder;
|
|
905
915
|
}
|
|
906
916
|
/**
|
|
907
|
-
* Build a stable fill dedupe key
|
|
908
|
-
*
|
|
909
|
-
*
|
|
910
|
-
*
|
|
917
|
+
* Build a stable fill dedupe key: `orderId:blockNum:historyId`.
|
|
918
|
+
*
|
|
919
|
+
* Delegates to `order/fill_ledger.ts` — the single owner of fill identity.
|
|
920
|
+
* Kept exported under this name because `dexbot_fill_runtime` resolves it
|
|
921
|
+
* through a lazy shim and the orphan path reuses it. Returns null when a
|
|
922
|
+
* required field is missing: callers skip dedup rather than operate on a
|
|
923
|
+
* degraded key.
|
|
911
924
|
*
|
|
912
925
|
* @param {Object} fillOrParts - Fill entry ({ op, block_num, id }) or { orderId, blockNum, historyId }
|
|
913
|
-
* @returns {string|null} Stable key
|
|
914
|
-
*/
|
|
915
|
-
|
|
916
|
-
const fillOp = fillOrParts?.op?.[1];
|
|
917
|
-
const orderId = fillOp?.order_id ?? fillOrParts?.orderId;
|
|
918
|
-
const blockNum = fillOrParts?.block_num ?? fillOrParts?.blockNum;
|
|
919
|
-
const historyId = fillOrParts?.id ?? fillOrParts?.historyId;
|
|
920
|
-
if (!orderId || blockNum == null || !historyId)
|
|
921
|
-
return null;
|
|
922
|
-
return `${orderId}:${blockNum}:${historyId}`;
|
|
923
|
-
}
|
|
926
|
+
* @returns {string|null} Stable key, or null if fields are missing
|
|
927
|
+
*/
|
|
928
|
+
const buildFillKey = fillKeyOf;
|
|
924
929
|
function _currentCorrectionGridOrder(manager, correctionInfo) {
|
|
925
930
|
const slotId = correctionInfo?.gridOrder?.id;
|
|
926
931
|
if (!slotId || !(manager?.orders instanceof Map))
|
|
@@ -958,8 +963,10 @@ async function correctOrderPriceOnChain(manager, correctionInfo, accountName, pr
|
|
|
958
963
|
if (cancelOnly) {
|
|
959
964
|
// Surplus-cancel grace: a fill landing between two controllers' count
|
|
960
965
|
// snapshots must not get a seconds-old placement cancelled. Skip
|
|
961
|
-
// quietly; the entry stays queued and re-evaluates next cycle.
|
|
962
|
-
|
|
966
|
+
// quietly; the entry stays queued and re-evaluates next cycle. A
|
|
967
|
+
// type mismatch is exempt (see shouldDeferFreshCancel): a wrong-side
|
|
968
|
+
// order cannot wait out the grace, its next fill is misclassified.
|
|
969
|
+
if (shouldDeferFreshCancel(manager, correctionInfo)) {
|
|
963
970
|
manager.logger?.log?.(`[CORRECTION] Skipping cancel-only for freshly placed ${chainOrderId} — inside grace window`, 'info');
|
|
964
971
|
return { success: true, skipped: true };
|
|
965
972
|
}
|
|
@@ -990,7 +997,10 @@ async function correctOrderPriceOnChain(manager, correctionInfo, accountName, pr
|
|
|
990
997
|
}
|
|
991
998
|
// Surplus/type-mismatch entries need cancellation, not a price update
|
|
992
999
|
if (isSurplus) {
|
|
993
|
-
|
|
1000
|
+
// Type mismatches bypass the fresh-placement grace (see
|
|
1001
|
+
// shouldDeferFreshCancel): their fill would be booked against the
|
|
1002
|
+
// wrong slot side if the order is allowed to rest.
|
|
1003
|
+
if (shouldDeferFreshCancel(manager, correctionInfo)) {
|
|
994
1004
|
manager.logger?.log?.(`[CORRECTION] Skipping surplus cancel for freshly placed ${chainOrderId} — inside grace window`, 'info');
|
|
995
1005
|
return { success: true, skipped: true };
|
|
996
1006
|
}
|
|
@@ -1462,10 +1472,12 @@ async function _correctAllPriceMismatchesLocked(manager, accountName, privateKey
|
|
|
1462
1472
|
// correctOrderPriceOnChain cannot protect the batch path, which
|
|
1463
1473
|
// bypasses it. Held-back entries are simply left in
|
|
1464
1474
|
// ordersNeedingPriceCorrection (never removed) and re-drain next cycle.
|
|
1475
|
+
// Type mismatches are exempt from the hold (shouldDeferFreshCancel):
|
|
1476
|
+
// letting a wrong-side order rest corrupts the next fill's accounting.
|
|
1465
1477
|
const cancelEntries = liveEntries.filter((c) => {
|
|
1466
1478
|
if (!(c.cancelOnly === true || c.isSurplus === true))
|
|
1467
1479
|
return false;
|
|
1468
|
-
if (
|
|
1480
|
+
if (shouldDeferFreshCancel(manager, c)) {
|
|
1469
1481
|
manager?.logger?.log?.(`[CORRECTION] Deferring cancel of freshly placed ${c.chainOrderId} — inside grace window`, 'info');
|
|
1470
1482
|
return false;
|
|
1471
1483
|
}
|
|
@@ -2055,6 +2067,9 @@ function getLivePendingBroadcasts(manager, options = {}) {
|
|
|
2055
2067
|
const map = manager?._pendingBroadcasts;
|
|
2056
2068
|
if (!(map instanceof Map))
|
|
2057
2069
|
return [];
|
|
2070
|
+
// READ-ONLY mode for predicates: the blocker resolver asks "is anything
|
|
2071
|
+
// unresolved?" from a gate that must not mutate state or emit GC log lines.
|
|
2072
|
+
const gc = options?.gc !== false;
|
|
2058
2073
|
// Single definition of the TTL and its fixture fallback (lifecycle.ts).
|
|
2059
2074
|
const ttl = pendingBroadcastTtlMs();
|
|
2060
2075
|
const now = Number.isFinite(Number(options?.now)) ? Number(options.now) : Date.now();
|
|
@@ -2070,9 +2085,21 @@ function getLivePendingBroadcasts(manager, options = {}) {
|
|
|
2070
2085
|
continue;
|
|
2071
2086
|
const syncedSinceRecord = lastSyncAt > recordedAt;
|
|
2072
2087
|
if (!syncedSinceRecord && age <= ttl * 2) {
|
|
2073
|
-
|
|
2088
|
+
if (gc) {
|
|
2089
|
+
log?.(`[COW] Pending-broadcast entry ${String(fingerprint)} is ${Math.round(age / 1000)}s old but no sync has completed since it was recorded; keeping it (fail-closed) until a caught-up read`, 'debug');
|
|
2090
|
+
}
|
|
2074
2091
|
continue;
|
|
2075
2092
|
}
|
|
2093
|
+
// READ-ONLY CALLERS KEEP THE ENTRY. This branch is reached for an entry
|
|
2094
|
+
// the write path would GC: either a caught-up sync has completed since
|
|
2095
|
+
// it was recorded (age > ttl), or it is past the hard 2x cap. The
|
|
2096
|
+
// grid-blocker predicate must not mutate the map to expire it, and
|
|
2097
|
+
// "unknown" is never "gone" (INV-LIFE-001), so the entry stays a
|
|
2098
|
+
// `broadcast-pending` blocker until a write-path GC retires it through
|
|
2099
|
+
// the lifecycle. Deliberate fail-closed; do not turn this into a
|
|
2100
|
+
// pass-through without replacing the evidence (docs/FILL_PIPELINE.md B3).
|
|
2101
|
+
if (!gc)
|
|
2102
|
+
continue;
|
|
2076
2103
|
map.delete(fingerprint);
|
|
2077
2104
|
// Abandoned, not resolved: the order may be live. Route through the
|
|
2078
2105
|
// lifecycle so the slot records `unknown` instead of becoming a clean
|
|
@@ -3871,6 +3898,76 @@ function detectCrossedBookPlan(manager, actions) {
|
|
|
3871
3898
|
return null;
|
|
3872
3899
|
}
|
|
3873
3900
|
}
|
|
3901
|
+
/**
|
|
3902
|
+
* Describe batch actions whose result price sits on the WRONG side of the
|
|
3903
|
+
* market floor — the EVIDENCE for the crossing OBSERVATION.
|
|
3904
|
+
*
|
|
3905
|
+
* Retrospective §9.10/P4 is explicit that this class must not be a hard veto:
|
|
3906
|
+
* "a hard veto re-opens the counter-order deadlock: after a gap the counter
|
|
3907
|
+
* sits across the floor by construction and executes at the best available
|
|
3908
|
+
* price. Made visible instead." A pre-broadcast version that dropped the
|
|
3909
|
+
* actions (and refused the batch when nothing remained) re-created exactly
|
|
3910
|
+
* that deadlock live on 2026-11-15: the only repair for an out-of-spread rail
|
|
3911
|
+
* was priced above a cached mid, the batch was refused, and the grid stayed
|
|
3912
|
+
* 3.0% wide (limit 1.65%) until the mid happened to move 86 minutes later.
|
|
3913
|
+
*
|
|
3914
|
+
* Evidence: the SHARED recency-aware floor (resolveSpreadCrossingFloor — an
|
|
3915
|
+
* executed trade is fresher truth than an older book read). The rejected
|
|
3916
|
+
* implementation re-derived its own reference from manager._liveMarketPrice
|
|
3917
|
+
* behind a 15-minute window, i.e. a second answer to "where is the market?":
|
|
3918
|
+
* live, that mid was 8 minutes old, had itself been the midpoint of the bot's
|
|
3919
|
+
* own book, and the five fills in hand (all newer than the mid, the last one
|
|
3920
|
+
* 4.4% above it) had already falsified it. The same batch, at identical
|
|
3921
|
+
* prices, was accepted at the next tick once a fresher read existed.
|
|
3922
|
+
*
|
|
3923
|
+
* CANCELs are never reported: a cancel cannot cross anything. Fail-open on
|
|
3924
|
+
* every unprovable case (no floor, malformed action).
|
|
3925
|
+
*
|
|
3926
|
+
* @param {Object} manager - OrderManager instance
|
|
3927
|
+
* @param {Array} actions - COW batch actions (never mutated)
|
|
3928
|
+
* @returns {{ floor: number|null, dropped: Array<{ index: number, action: Object, reason: string }> }}
|
|
3929
|
+
*/
|
|
3930
|
+
function describeMarketCrossingActions(manager, actions) {
|
|
3931
|
+
const list = Array.isArray(actions) ? actions : [];
|
|
3932
|
+
let floor = null;
|
|
3933
|
+
try {
|
|
3934
|
+
floor = resolveSpreadCrossingFloor(manager);
|
|
3935
|
+
}
|
|
3936
|
+
catch {
|
|
3937
|
+
floor = null;
|
|
3938
|
+
}
|
|
3939
|
+
const usable = floor != null && Number.isFinite(Number(floor)) && Number(floor) > 0;
|
|
3940
|
+
if (!usable)
|
|
3941
|
+
return { floor: null, dropped: [] };
|
|
3942
|
+
const ref = Number(floor);
|
|
3943
|
+
const dropped = [];
|
|
3944
|
+
list.forEach((a, index) => {
|
|
3945
|
+
try {
|
|
3946
|
+
if (!a || a.type === COW_ACTIONS.CANCEL)
|
|
3947
|
+
return;
|
|
3948
|
+
const price = Number(a.type === COW_ACTIONS.UPDATE
|
|
3949
|
+
? (a.newPrice ?? a.order?.price)
|
|
3950
|
+
: a.order?.price);
|
|
3951
|
+
let type = a.order?.type;
|
|
3952
|
+
if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL) {
|
|
3953
|
+
// Same legacy convention as detectCrossedBookPlan: derive the
|
|
3954
|
+
// side from the existing book entry / order being updated.
|
|
3955
|
+
const entry = manager?.orders?.get?.(String(a.orderId ?? a.id ?? ''));
|
|
3956
|
+
type = entry?.type;
|
|
3957
|
+
}
|
|
3958
|
+
if (!Number.isFinite(price) || (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL))
|
|
3959
|
+
return;
|
|
3960
|
+
if (type === ORDER_TYPES.BUY && price > ref) {
|
|
3961
|
+
dropped.push({ index, action: a, reason: `BUY ${price} above the market floor ${ref}` });
|
|
3962
|
+
}
|
|
3963
|
+
else if (type === ORDER_TYPES.SELL && price < ref) {
|
|
3964
|
+
dropped.push({ index, action: a, reason: `SELL ${price} below the market floor ${ref}` });
|
|
3965
|
+
}
|
|
3966
|
+
}
|
|
3967
|
+
catch { /* fail-open per action */ }
|
|
3968
|
+
});
|
|
3969
|
+
return { floor: ref, dropped };
|
|
3970
|
+
}
|
|
3874
3971
|
/**
|
|
3875
3972
|
* Collect every on-chain order id master currently needs to converge against,
|
|
3876
3973
|
* so adoption can re-read them by id (immune to the get_full_accounts window
|
|
@@ -3957,6 +4054,6 @@ function collectKnownOnChainOrderIds(mgr, placedResults, placedContexts, extraCr
|
|
|
3957
4054
|
const all = new Set([...masterIds, ...createIds]);
|
|
3958
4055
|
return { masterIds: [...masterIds], createIds: [...createIds], all: [...all] };
|
|
3959
4056
|
}
|
|
3960
|
-
export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, resolveExecutionPrice, resolveSlotIdForFillPrice, reviveVirtualSlotFromChain, attributeUnmatchedFillToGrid, getLivePendingBroadcasts, 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, isStructuralRebuildStaleReason, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, collectEdgePinnedFillIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
|
|
3961
|
-
export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds,
|
|
4057
|
+
export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, resolveExecutionPrice, resolveSlotIdForFillPrice, reviveVirtualSlotFromChain, attributeUnmatchedFillToGrid, getLivePendingBroadcasts, 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, isStructuralRebuildStaleReason, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, describeMarketCrossingActions, collectKnownOnChainOrderIds, collectEdgePinnedFillIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
|
|
4058
|
+
export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
|
|
3962
4059
|
//# sourceMappingURL=order.js.map
|