dexbot 1.7.1 → 1.7.2
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 +28 -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/modules/account_bots.d.ts +1 -0
- package/dist/modules/account_bots.js +7 -5
- package/dist/modules/constants.d.ts +2 -0
- package/dist/modules/constants.js +16 -2
- package/dist/modules/dexbot_class.d.ts +22 -0
- package/dist/modules/dexbot_class.js +30 -0
- package/dist/modules/dexbot_cow_runtime.d.ts +31 -1
- package/dist/modules/dexbot_cow_runtime.js +68 -56
- package/dist/modules/dexbot_maintenance_runtime.d.ts +1 -1
- package/dist/modules/dexbot_maintenance_runtime.js +33 -6
- 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 +75 -18
- package/dist/modules/order/grid.js +207 -61
- package/dist/modules/order/grid_reconcile_internal.js +16 -4
- package/dist/modules/order/index.d.ts +14 -5
- package/dist/modules/order/index.js +5 -5
- package/dist/modules/order/lifecycle.js +3 -3
- package/dist/modules/order/manager.d.ts +15 -24
- package/dist/modules/order/manager.js +40 -27
- 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 +40 -41
- package/dist/modules/order/utils/order.js +110 -84
- package/dist/modules/order/utils/system.d.ts +81 -6
- package/dist/modules/order/utils/system.js +167 -29
- package/dist/modules/timing_policy.js +2 -2
- package/dist/modules/types.d.ts +22 -27
- package/docs/COW_INVARIANTS.md +5 -1
- package/docs/DEXBOT_COMPARISON.md +4 -4
- package/docs/EVOLUTION.md +6 -5
- 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 +38 -30
- package/docs/README.md +1 -1
- package/docs/architecture.md +26 -8
- package/modules/README.md +3 -0
- package/package.json +3 -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
|
|
@@ -31,11 +35,12 @@
|
|
|
31
35
|
* - buildCreateOrderArgs(order, assetA, assetB) - Build create order arguments
|
|
32
36
|
* - getOrderTypeFromUpdatedFlags(buyUpdated, sellUpdated) - Get type from update flags
|
|
33
37
|
* - resolveConfiguredPriceBound(value, fallback, startPrice, mode) - Resolve price bounds
|
|
34
|
-
* - buildFillKey(fillOrParts) -
|
|
38
|
+
* - buildFillKey(fillOrParts) - Stable fill dedupe key (delegates to order/fill_ledger.ts)
|
|
35
39
|
* - buildCreateOpFingerprint(params) - Build fingerprint for create operations
|
|
36
40
|
*
|
|
37
|
-
* SECTION 4: STATE TRANSITIONS & PLACEHOLDERS (
|
|
41
|
+
* SECTION 4: STATE TRANSITIONS & PLACEHOLDERS (7 functions)
|
|
38
42
|
* - virtualizeOrder(order) - Convert order to VIRTUAL state
|
|
43
|
+
* - reviveVirtualSlotFromChain(...) - Re-materialise a virtualised slot from its chain order
|
|
39
44
|
* - convertToSpreadPlaceholder(order) - Convert order to SPREAD placeholder
|
|
40
45
|
* - toRailHolePlaceholder(order) - Convert to a rail-typed hole placeholder
|
|
41
46
|
* - geometryTypeForSlotIndex(...) - BUY/SELL type for a slot index
|
|
@@ -47,8 +52,9 @@
|
|
|
47
52
|
* - updateGapEvacuationStreaks(...) - Tick per-slot gap-evacuation streak counter
|
|
48
53
|
* - collectRefillSlotIds(...) - Refill-slot wire for the COW boundary hold
|
|
49
54
|
*
|
|
50
|
-
* SECTION 6: FILTERING & DRIFT DIAGNOSTICS (
|
|
55
|
+
* SECTION 6: FILTERING & DRIFT DIAGNOSTICS (12 functions)
|
|
51
56
|
* - filterOrdersByType(orders, orderType) - Filter orders by type
|
|
57
|
+
* - isStructuralRebuildStaleReason(reason) - Whether a refusal label means a structural rebuild
|
|
52
58
|
* - buildOutsideInPairGroups(items, accessors) - Outside->center pair grouping
|
|
53
59
|
* - extractBatchOperationResults(result) - Extract operation_results from chain batch result
|
|
54
60
|
* - formatUnmatchedChainOrder(order) - Format structural drift diagnostics
|
|
@@ -106,13 +112,18 @@
|
|
|
106
112
|
* - checkGridPriceInvariant(...) - The price emitted for a slot must equal its genesis price
|
|
107
113
|
* - reportGridPriceInvariant(...) - Report one GRID-PRICE-INVARIANT check
|
|
108
114
|
*
|
|
109
|
-
* SECTION 14: PERSISTED CRAWL & PLACEMENT GRACE (
|
|
115
|
+
* SECTION 14: PERSISTED CRAWL & PLACEMENT GRACE (2 functions + the CrawlEntry type)
|
|
110
116
|
* - consumePendingFillCrawls(...) - Apply recorded-but-uncommitted fill crawls to the boundary
|
|
111
|
-
* - recordOrderPlacement(...) - Record a fresh on-chain placement timestamp
|
|
112
117
|
* - isFreshlyPlacedOrder(...) - Chain order placed within the surplus-cancel grace
|
|
118
|
+
* (the stamp itself is written only by the lifecycle funnel)
|
|
119
|
+
*
|
|
120
|
+
* SECTION 15: LIVE BROADCAST & EDGE PROJECTIONS (2 functions)
|
|
121
|
+
* - getLivePendingBroadcasts(manager, options?) - Live pending-broadcast list (expired entries deleted)
|
|
122
|
+
* - collectEdgePinnedFillIds(manager, fills) - Fill ids pinned to the configured/live edge
|
|
113
123
|
*
|
|
114
124
|
* ===============================================================================
|
|
115
125
|
*/
|
|
126
|
+
import { fillKeyOf } from '../fill_ledger.js';
|
|
116
127
|
import type { PlacementLease } from '../placement_lock.js';
|
|
117
128
|
import type { OrderManagerLike, PendingPriceCorrection, ChainOrder, ParsedChainOrder, AssetPair, AssetInfo, OrderType, ManagedOrder, UnmatchedChainOrder, CowAction, ProjectedFunds } from '../../types.js';
|
|
118
129
|
import type { GridGenesis } from './math.js';
|
|
@@ -190,21 +201,6 @@ declare function duplicateOrphanLogInfo(orderId: string | null | undefined): {
|
|
|
190
201
|
suffix: string;
|
|
191
202
|
};
|
|
192
203
|
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
204
|
/**
|
|
209
205
|
* True when the chain order was placed within the surplus-cancel grace
|
|
210
206
|
* window. Surplus sweeps must skip such orders: a fill landing between two
|
|
@@ -366,11 +362,17 @@ declare function findLiveOrderOwnerByChainId(manager: OrderManagerLike, chainOrd
|
|
|
366
362
|
* replayed cancel would then destroy the freshly updated in-place order.
|
|
367
363
|
*
|
|
368
364
|
* Type-mismatch and gap-evacuation surplus decisions have their own source-
|
|
369
|
-
* specific checks. A type mismatch is actionable
|
|
370
|
-
*
|
|
371
|
-
*
|
|
372
|
-
*
|
|
373
|
-
*
|
|
365
|
+
* specific checks. A type mismatch is actionable while the same live slot
|
|
366
|
+
* still owns the id AND (its stored type OR its rail geometry — index vs
|
|
367
|
+
* boundary, including the gap band) still disagrees with the chain side. A
|
|
368
|
+
* stored type that a fill (or another in-place writer) retagged to the chain
|
|
369
|
+
* side is NOT a repair on its own: an order can carry the chain's side while
|
|
370
|
+
* sitting on the opposite rail or inside the band, and dropping the cancel
|
|
371
|
+
* there would let the residual rest on the wrong side (2026-11-04 incident).
|
|
372
|
+
* A gap evacuation is actionable only while the same live slot remains in the
|
|
373
|
+
* current gap band. Both otherwise use the old cancellation branch, so
|
|
374
|
+
* allowing either decision to replay would recreate the same stale-replay
|
|
375
|
+
* regression.
|
|
374
376
|
*
|
|
375
377
|
* @param {Object} manager - OrderManager instance (live grid + assets)
|
|
376
378
|
* @param {Object} entry - Queued correction entry
|
|
@@ -404,22 +406,18 @@ declare function parseChainOrder(chainOrder: ChainOrder | null | undefined, asse
|
|
|
404
406
|
*/
|
|
405
407
|
declare function applyChainSizeToGridOrder(manager: OrderManagerLike, gridOrder: ManagedOrder, chainSize: number | string | null | undefined): Promise<ManagedOrder | null>;
|
|
406
408
|
/**
|
|
407
|
-
* Build a stable fill dedupe key
|
|
408
|
-
*
|
|
409
|
-
*
|
|
410
|
-
*
|
|
409
|
+
* Build a stable fill dedupe key: `orderId:blockNum:historyId`.
|
|
410
|
+
*
|
|
411
|
+
* Delegates to `order/fill_ledger.ts` — the single owner of fill identity.
|
|
412
|
+
* Kept exported under this name because `dexbot_fill_runtime` resolves it
|
|
413
|
+
* through a lazy shim and the orphan path reuses it. Returns null when a
|
|
414
|
+
* required field is missing: callers skip dedup rather than operate on a
|
|
415
|
+
* degraded key.
|
|
411
416
|
*
|
|
412
417
|
* @param {Object} fillOrParts - Fill entry ({ op, block_num, id }) or { orderId, blockNum, historyId }
|
|
413
|
-
* @returns {string|null} Stable key
|
|
418
|
+
* @returns {string|null} Stable key, or null if fields are missing
|
|
414
419
|
*/
|
|
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;
|
|
420
|
+
declare const buildFillKey: typeof fillKeyOf;
|
|
423
421
|
/**
|
|
424
422
|
* Correct a single order's price on blockchain.
|
|
425
423
|
* Cancels surplus orders; updates price for others.
|
|
@@ -821,6 +819,7 @@ declare function isCrossingCheckCandidate(o: CrossingCandidate | null | undefine
|
|
|
821
819
|
*/
|
|
822
820
|
declare function getLivePendingBroadcasts(manager: OrderManagerLike | null | undefined, options?: {
|
|
823
821
|
now?: number;
|
|
822
|
+
gc?: boolean;
|
|
824
823
|
}): unknown[];
|
|
825
824
|
/**
|
|
826
825
|
* Shared candidate set for crossing-placement checks: master orders plus
|
|
@@ -1633,5 +1632,5 @@ declare function collectKnownOnChainOrderIds(mgr: OrderManagerLike, placedResult
|
|
|
1633
1632
|
};
|
|
1634
1633
|
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 };
|
|
1635
1634
|
export type { CrawlEntry };
|
|
1636
|
-
export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds,
|
|
1635
|
+
export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
|
|
1637
1636
|
//# 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
|
|
@@ -31,11 +35,12 @@
|
|
|
31
35
|
* - buildCreateOrderArgs(order, assetA, assetB) - Build create order arguments
|
|
32
36
|
* - getOrderTypeFromUpdatedFlags(buyUpdated, sellUpdated) - Get type from update flags
|
|
33
37
|
* - resolveConfiguredPriceBound(value, fallback, startPrice, mode) - Resolve price bounds
|
|
34
|
-
* - buildFillKey(fillOrParts) -
|
|
38
|
+
* - buildFillKey(fillOrParts) - Stable fill dedupe key (delegates to order/fill_ledger.ts)
|
|
35
39
|
* - buildCreateOpFingerprint(params) - Build fingerprint for create operations
|
|
36
40
|
*
|
|
37
|
-
* SECTION 4: STATE TRANSITIONS & PLACEHOLDERS (
|
|
41
|
+
* SECTION 4: STATE TRANSITIONS & PLACEHOLDERS (7 functions)
|
|
38
42
|
* - virtualizeOrder(order) - Convert order to VIRTUAL state
|
|
43
|
+
* - reviveVirtualSlotFromChain(...) - Re-materialise a virtualised slot from its chain order
|
|
39
44
|
* - convertToSpreadPlaceholder(order) - Convert order to SPREAD placeholder
|
|
40
45
|
* - toRailHolePlaceholder(order) - Convert to a rail-typed hole placeholder
|
|
41
46
|
* - geometryTypeForSlotIndex(...) - BUY/SELL type for a slot index
|
|
@@ -47,8 +52,9 @@
|
|
|
47
52
|
* - updateGapEvacuationStreaks(...) - Tick per-slot gap-evacuation streak counter
|
|
48
53
|
* - collectRefillSlotIds(...) - Refill-slot wire for the COW boundary hold
|
|
49
54
|
*
|
|
50
|
-
* SECTION 6: FILTERING & DRIFT DIAGNOSTICS (
|
|
55
|
+
* SECTION 6: FILTERING & DRIFT DIAGNOSTICS (12 functions)
|
|
51
56
|
* - filterOrdersByType(orders, orderType) - Filter orders by type
|
|
57
|
+
* - isStructuralRebuildStaleReason(reason) - Whether a refusal label means a structural rebuild
|
|
52
58
|
* - buildOutsideInPairGroups(items, accessors) - Outside->center pair grouping
|
|
53
59
|
* - extractBatchOperationResults(result) - Extract operation_results from chain batch result
|
|
54
60
|
* - formatUnmatchedChainOrder(order) - Format structural drift diagnostics
|
|
@@ -106,10 +112,14 @@
|
|
|
106
112
|
* - checkGridPriceInvariant(...) - The price emitted for a slot must equal its genesis price
|
|
107
113
|
* - reportGridPriceInvariant(...) - Report one GRID-PRICE-INVARIANT check
|
|
108
114
|
*
|
|
109
|
-
* SECTION 14: PERSISTED CRAWL & PLACEMENT GRACE (
|
|
115
|
+
* SECTION 14: PERSISTED CRAWL & PLACEMENT GRACE (2 functions + the CrawlEntry type)
|
|
110
116
|
* - consumePendingFillCrawls(...) - Apply recorded-but-uncommitted fill crawls to the boundary
|
|
111
|
-
* - recordOrderPlacement(...) - Record a fresh on-chain placement timestamp
|
|
112
117
|
* - isFreshlyPlacedOrder(...) - Chain order placed within the surplus-cancel grace
|
|
118
|
+
* (the stamp itself is written only by the lifecycle funnel)
|
|
119
|
+
*
|
|
120
|
+
* SECTION 15: LIVE BROADCAST & EDGE PROJECTIONS (2 functions)
|
|
121
|
+
* - getLivePendingBroadcasts(manager, options?) - Live pending-broadcast list (expired entries deleted)
|
|
122
|
+
* - collectEdgePinnedFillIds(manager, fills) - Fill ids pinned to the configured/live edge
|
|
113
123
|
*
|
|
114
124
|
* ===============================================================================
|
|
115
125
|
*/
|
|
@@ -121,6 +131,7 @@ import { sleep } from './system.js';
|
|
|
121
131
|
import { getErrorMessage, getErrorCode, getErrorName } from '../../utils/errors.js';
|
|
122
132
|
import { hasGenesisLadder } from '../genesis_policy.js';
|
|
123
133
|
import { parseSlotIndex } from './slot.js';
|
|
134
|
+
import { fillKeyOf, resolveTradedSide } from '../fill_ledger.js';
|
|
124
135
|
import { pendingBroadcastTtlMs } from '../lifecycle.js';
|
|
125
136
|
const { isValidNumber, toFiniteNumber } = Format;
|
|
126
137
|
const { blockchainToFloat, floatToBlockchainInt, quantizeFloat, slotIndexForPrice, priceSlotEqual } = MathUtils;
|
|
@@ -264,40 +275,6 @@ function _filterUnmatchedChainOrders(manager, chainOrderId) {
|
|
|
264
275
|
manager._lastUnmatchedChainOrders = manager._lastUnmatchedChainOrders.filter((u) => (u?.id || u?.orderId || u?.chainOrderId) !== chainOrderId);
|
|
265
276
|
}
|
|
266
277
|
}
|
|
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
278
|
/**
|
|
302
279
|
* True when the chain order was placed within the surplus-cancel grace
|
|
303
280
|
* window. Surplus sweeps must skip such orders: a fill landing between two
|
|
@@ -331,6 +308,30 @@ function isFreshlyPlacedOrder(manager, chainOrderId, graceMs) {
|
|
|
331
308
|
return false;
|
|
332
309
|
}
|
|
333
310
|
}
|
|
311
|
+
/**
|
|
312
|
+
* Whether a cancel-class correction must be held back by the fresh-placement
|
|
313
|
+
* grace window.
|
|
314
|
+
*
|
|
315
|
+
* Type mismatches are deliberately EXEMPT. The grace exists so a fill landing
|
|
316
|
+
* between two controllers' count snapshots cannot get a seconds-old placement
|
|
317
|
+
* cancelled (surplus/duplicate churn). A live order on the WRONG side is not
|
|
318
|
+
* that race: it is a known-wrong order, and the next fill is classified from
|
|
319
|
+
* the slot's (wrong) side — a sell on a slot retyped BUY produced a
|
|
320
|
+
* `filledAmount=0` phantom fill, a dust cancel and a re-buy at the fill level
|
|
321
|
+
* (2026-11-04 live incident). The 15-minute SURPLUS_CANCEL_GRACE_MS is correct
|
|
322
|
+
* for surplus churn, not for a side that can corrupt fill accounting; the
|
|
323
|
+
* entry's own `_validatePriceCorrectionEntry` gate already drops it once the
|
|
324
|
+
* slot no longer owns the order or the side was repaired.
|
|
325
|
+
*
|
|
326
|
+
* @param {Object} manager - OrderManager instance
|
|
327
|
+
* @param {Object} entry - Queued correction entry
|
|
328
|
+
* @returns {boolean} True when the cancel should stay queued for this cycle
|
|
329
|
+
*/
|
|
330
|
+
function shouldDeferFreshCancel(manager, entry) {
|
|
331
|
+
if (!entry || entry.typeMismatch === true)
|
|
332
|
+
return false;
|
|
333
|
+
return isFreshlyPlacedOrder(manager, entry.chainOrderId);
|
|
334
|
+
}
|
|
334
335
|
/**
|
|
335
336
|
* Remove a single correction entry by its full queue key
|
|
336
337
|
* (chainOrderId + surplus flag). The queue's upsert key is
|
|
@@ -576,19 +577,11 @@ function attributeUnmatchedFillToGrid(manager, params) {
|
|
|
576
577
|
}
|
|
577
578
|
}
|
|
578
579
|
}
|
|
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
|
-
}
|
|
580
|
+
// Side from the asset that was PAID (order/fill_ledger.ts): paying the
|
|
581
|
+
// quote buys the base, paying the base sells it. Independent of the slot
|
|
582
|
+
// type; a malformed fill with no pays asset falls back to the slot's type
|
|
583
|
+
// and the side is never guessed from the price.
|
|
584
|
+
const type = resolveTradedSide(input.paysAssetId, assets, slot?.type);
|
|
592
585
|
if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
|
|
593
586
|
return false;
|
|
594
587
|
const execPrice = resolveExecutionPrice(assets, input.paysAssetId, input.paysAmountRaw, input.receivesAssetId, input.receivesAmountRaw);
|
|
@@ -705,11 +698,17 @@ function findLiveOrderOwnerByChainId(manager, chainOrderId, slotId) {
|
|
|
705
698
|
* replayed cancel would then destroy the freshly updated in-place order.
|
|
706
699
|
*
|
|
707
700
|
* Type-mismatch and gap-evacuation surplus decisions have their own source-
|
|
708
|
-
* specific checks. A type mismatch is actionable
|
|
709
|
-
*
|
|
710
|
-
*
|
|
711
|
-
*
|
|
712
|
-
*
|
|
701
|
+
* specific checks. A type mismatch is actionable while the same live slot
|
|
702
|
+
* still owns the id AND (its stored type OR its rail geometry — index vs
|
|
703
|
+
* boundary, including the gap band) still disagrees with the chain side. A
|
|
704
|
+
* stored type that a fill (or another in-place writer) retagged to the chain
|
|
705
|
+
* side is NOT a repair on its own: an order can carry the chain's side while
|
|
706
|
+
* sitting on the opposite rail or inside the band, and dropping the cancel
|
|
707
|
+
* there would let the residual rest on the wrong side (2026-11-04 incident).
|
|
708
|
+
* A gap evacuation is actionable only while the same live slot remains in the
|
|
709
|
+
* current gap band. Both otherwise use the old cancellation branch, so
|
|
710
|
+
* allowing either decision to replay would recreate the same stale-replay
|
|
711
|
+
* regression.
|
|
713
712
|
*
|
|
714
713
|
* @param {Object} manager - OrderManager instance (live grid + assets)
|
|
715
714
|
* @param {Object} entry - Queued correction entry
|
|
@@ -735,10 +734,20 @@ function _validatePriceCorrectionEntry(manager, entry) {
|
|
|
735
734
|
if (!slot) {
|
|
736
735
|
return { valid: false, reason: `type-mismatch target ${slotId || '?'} no longer owns ${entry.chainOrderId}` };
|
|
737
736
|
}
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
737
|
+
// The stored type alone is not proof of a repair: a fill (or another
|
|
738
|
+
// in-place writer) may have retagged the slot to the CHAIN side while
|
|
739
|
+
// the level still belongs to the opposite rail. Only a level whose
|
|
740
|
+
// rail geometry also matches the chain side is genuinely repaired.
|
|
741
|
+
// A resolved SPREAD geometry (gap band) also contradicts a rail side:
|
|
742
|
+
// no order should rest there, so the cancel must survive. Geometry is
|
|
743
|
+
// index-vs-boundary, so an unknown boundary falls back to the
|
|
744
|
+
// stored-type check (fail-safe: never invent a rail).
|
|
745
|
+
const geometryType = geometryTypeForSlotIndex(parseSlotIndex(slot.id), manager?.boundaryIdx, manager?._gapSlots);
|
|
746
|
+
const geometryContradicts = geometryType !== null && geometryType !== targetType;
|
|
747
|
+
if (!targetType || (slot.type === targetType && !geometryContradicts)) {
|
|
748
|
+
return { valid: false, reason: `type-mismatch for ${entry.chainOrderId} was repaired (${slot.type} now matches ${targetType || 'chain type'} on the ${geometryType || 'unknown'} rail)` };
|
|
749
|
+
}
|
|
750
|
+
return { valid: true, reason: geometryContradicts ? 'type-mismatch-still-live-geometry' : 'type-mismatch-still-live' };
|
|
742
751
|
}
|
|
743
752
|
if (entry.gapEvacuation === true) {
|
|
744
753
|
const slotId = entry?.gridOrder?.id;
|
|
@@ -904,23 +913,18 @@ async function applyChainSizeToGridOrder(manager, gridOrder, chainSize) {
|
|
|
904
913
|
return updatedOrder;
|
|
905
914
|
}
|
|
906
915
|
/**
|
|
907
|
-
* Build a stable fill dedupe key
|
|
908
|
-
*
|
|
909
|
-
*
|
|
910
|
-
*
|
|
916
|
+
* Build a stable fill dedupe key: `orderId:blockNum:historyId`.
|
|
917
|
+
*
|
|
918
|
+
* Delegates to `order/fill_ledger.ts` — the single owner of fill identity.
|
|
919
|
+
* Kept exported under this name because `dexbot_fill_runtime` resolves it
|
|
920
|
+
* through a lazy shim and the orphan path reuses it. Returns null when a
|
|
921
|
+
* required field is missing: callers skip dedup rather than operate on a
|
|
922
|
+
* degraded key.
|
|
911
923
|
*
|
|
912
924
|
* @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
|
-
}
|
|
925
|
+
* @returns {string|null} Stable key, or null if fields are missing
|
|
926
|
+
*/
|
|
927
|
+
const buildFillKey = fillKeyOf;
|
|
924
928
|
function _currentCorrectionGridOrder(manager, correctionInfo) {
|
|
925
929
|
const slotId = correctionInfo?.gridOrder?.id;
|
|
926
930
|
if (!slotId || !(manager?.orders instanceof Map))
|
|
@@ -958,8 +962,10 @@ async function correctOrderPriceOnChain(manager, correctionInfo, accountName, pr
|
|
|
958
962
|
if (cancelOnly) {
|
|
959
963
|
// Surplus-cancel grace: a fill landing between two controllers' count
|
|
960
964
|
// snapshots must not get a seconds-old placement cancelled. Skip
|
|
961
|
-
// quietly; the entry stays queued and re-evaluates next cycle.
|
|
962
|
-
|
|
965
|
+
// quietly; the entry stays queued and re-evaluates next cycle. A
|
|
966
|
+
// type mismatch is exempt (see shouldDeferFreshCancel): a wrong-side
|
|
967
|
+
// order cannot wait out the grace, its next fill is misclassified.
|
|
968
|
+
if (shouldDeferFreshCancel(manager, correctionInfo)) {
|
|
963
969
|
manager.logger?.log?.(`[CORRECTION] Skipping cancel-only for freshly placed ${chainOrderId} — inside grace window`, 'info');
|
|
964
970
|
return { success: true, skipped: true };
|
|
965
971
|
}
|
|
@@ -990,7 +996,10 @@ async function correctOrderPriceOnChain(manager, correctionInfo, accountName, pr
|
|
|
990
996
|
}
|
|
991
997
|
// Surplus/type-mismatch entries need cancellation, not a price update
|
|
992
998
|
if (isSurplus) {
|
|
993
|
-
|
|
999
|
+
// Type mismatches bypass the fresh-placement grace (see
|
|
1000
|
+
// shouldDeferFreshCancel): their fill would be booked against the
|
|
1001
|
+
// wrong slot side if the order is allowed to rest.
|
|
1002
|
+
if (shouldDeferFreshCancel(manager, correctionInfo)) {
|
|
994
1003
|
manager.logger?.log?.(`[CORRECTION] Skipping surplus cancel for freshly placed ${chainOrderId} — inside grace window`, 'info');
|
|
995
1004
|
return { success: true, skipped: true };
|
|
996
1005
|
}
|
|
@@ -1462,10 +1471,12 @@ async function _correctAllPriceMismatchesLocked(manager, accountName, privateKey
|
|
|
1462
1471
|
// correctOrderPriceOnChain cannot protect the batch path, which
|
|
1463
1472
|
// bypasses it. Held-back entries are simply left in
|
|
1464
1473
|
// ordersNeedingPriceCorrection (never removed) and re-drain next cycle.
|
|
1474
|
+
// Type mismatches are exempt from the hold (shouldDeferFreshCancel):
|
|
1475
|
+
// letting a wrong-side order rest corrupts the next fill's accounting.
|
|
1465
1476
|
const cancelEntries = liveEntries.filter((c) => {
|
|
1466
1477
|
if (!(c.cancelOnly === true || c.isSurplus === true))
|
|
1467
1478
|
return false;
|
|
1468
|
-
if (
|
|
1479
|
+
if (shouldDeferFreshCancel(manager, c)) {
|
|
1469
1480
|
manager?.logger?.log?.(`[CORRECTION] Deferring cancel of freshly placed ${c.chainOrderId} — inside grace window`, 'info');
|
|
1470
1481
|
return false;
|
|
1471
1482
|
}
|
|
@@ -2055,6 +2066,9 @@ function getLivePendingBroadcasts(manager, options = {}) {
|
|
|
2055
2066
|
const map = manager?._pendingBroadcasts;
|
|
2056
2067
|
if (!(map instanceof Map))
|
|
2057
2068
|
return [];
|
|
2069
|
+
// READ-ONLY mode for predicates: the blocker resolver asks "is anything
|
|
2070
|
+
// unresolved?" from a gate that must not mutate state or emit GC log lines.
|
|
2071
|
+
const gc = options?.gc !== false;
|
|
2058
2072
|
// Single definition of the TTL and its fixture fallback (lifecycle.ts).
|
|
2059
2073
|
const ttl = pendingBroadcastTtlMs();
|
|
2060
2074
|
const now = Number.isFinite(Number(options?.now)) ? Number(options.now) : Date.now();
|
|
@@ -2070,9 +2084,21 @@ function getLivePendingBroadcasts(manager, options = {}) {
|
|
|
2070
2084
|
continue;
|
|
2071
2085
|
const syncedSinceRecord = lastSyncAt > recordedAt;
|
|
2072
2086
|
if (!syncedSinceRecord && age <= ttl * 2) {
|
|
2073
|
-
|
|
2087
|
+
if (gc) {
|
|
2088
|
+
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');
|
|
2089
|
+
}
|
|
2074
2090
|
continue;
|
|
2075
2091
|
}
|
|
2092
|
+
// READ-ONLY CALLERS KEEP THE ENTRY. This branch is reached for an entry
|
|
2093
|
+
// the write path would GC: either a caught-up sync has completed since
|
|
2094
|
+
// it was recorded (age > ttl), or it is past the hard 2x cap. The
|
|
2095
|
+
// grid-blocker predicate must not mutate the map to expire it, and
|
|
2096
|
+
// "unknown" is never "gone" (INV-LIFE-001), so the entry stays a
|
|
2097
|
+
// `broadcast-pending` blocker until a write-path GC retires it through
|
|
2098
|
+
// the lifecycle. Deliberate fail-closed; do not turn this into a
|
|
2099
|
+
// pass-through without replacing the evidence (docs/FILL_PIPELINE.md B3).
|
|
2100
|
+
if (!gc)
|
|
2101
|
+
continue;
|
|
2076
2102
|
map.delete(fingerprint);
|
|
2077
2103
|
// Abandoned, not resolved: the order may be live. Route through the
|
|
2078
2104
|
// lifecycle so the slot records `unknown` instead of becoming a clean
|
|
@@ -3958,5 +3984,5 @@ function collectKnownOnChainOrderIds(mgr, placedResults, placedContexts, extraCr
|
|
|
3958
3984
|
return { masterIds: [...masterIds], createIds: [...createIds], all: [...all] };
|
|
3959
3985
|
}
|
|
3960
3986
|
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,
|
|
3987
|
+
export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
|
|
3962
3988
|
//# sourceMappingURL=order.js.map
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Price derivation, persistence, grid correction, and UI/interactive utilities.
|
|
5
5
|
*
|
|
6
6
|
* ===============================================================================
|
|
7
|
-
* TABLE OF CONTENTS (
|
|
7
|
+
* TABLE OF CONTENTS (52 exported functions + 12 structural view types)
|
|
8
8
|
* ===============================================================================
|
|
9
9
|
*
|
|
10
10
|
* SECTION 1: PRICE DERIVATION (9 functions + 1 internal)
|
|
@@ -50,7 +50,18 @@
|
|
|
50
50
|
* - resetLastFillPivot(manager) - Clear the pivot to cold state
|
|
51
51
|
* - restoreLastFillPivot(manager) - Restore the persisted pivot into the manager
|
|
52
52
|
*
|
|
53
|
-
* SECTION 7:
|
|
53
|
+
* SECTION 7: FILL PIPELINE & LAST-FILL GUARD (9 functions)
|
|
54
|
+
* - reanchorBoundaryFromLastFill(manager, ...) - Re-anchor a rebuilt boundary to the last fill
|
|
55
|
+
* - rearmLastFillPivotFromMarketFill(manager) - Re-arm the pivot from the last market fill
|
|
56
|
+
* - isLastFillGuardBlocked(price, type, lastPrice, lastType) - LAST-FILL-GUARD predicate
|
|
57
|
+
* - isLastFillPlacementBlocked(manager, price, type) - Placement-side LAST-FILL-GUARD wrapper
|
|
58
|
+
* - readFillPipelineState(source) - Projection of the fill-pipeline state
|
|
59
|
+
* - resolveGridUpdateBlockers(source, options) - Blockers that forbid a grid update right now
|
|
60
|
+
* - noteGridUpdateBlockers(...) - Log/record the blockers for one decision
|
|
61
|
+
* - hasUnsettledFills(source) - Whether any fill is still unsettled (with a reason)
|
|
62
|
+
* - getPipelineInFlightAgeMs(source, nowMs) - Age of the oldest in-flight pipeline work
|
|
63
|
+
*
|
|
64
|
+
* SECTION 8: UI & INTERACTIVE UTILITIES (6 functions)
|
|
54
65
|
* - ensureProfilesDirectory(profilesDir) - Ensure profiles directory exists
|
|
55
66
|
* - sleep(ms) - Pause execution for specified duration
|
|
56
67
|
* - readInput(prompt, options) - Read user input from stdin
|
|
@@ -59,7 +70,7 @@
|
|
|
59
70
|
* - withBlockchainRetry(fn, label, options) - Blockchain op with timeout + retry + node failover
|
|
60
71
|
* (withTimeout lives in ./timeout)
|
|
61
72
|
*
|
|
62
|
-
* SECTION
|
|
73
|
+
* SECTION 9: GENERAL UTILITIES (7 functions)
|
|
63
74
|
* - resolveAccountRef(manager, account) - Resolve best account reference
|
|
64
75
|
* - deepFreeze(obj) - Recursively freeze object for immutability
|
|
65
76
|
* - cloneMap(map) - Create shallow clone of Map
|
|
@@ -70,8 +81,8 @@
|
|
|
70
81
|
*
|
|
71
82
|
* STRUCTURAL VIEW TYPES:
|
|
72
83
|
* AssetMeta, PoolReserve, PoolEntry, BitSharesClient, AmaCenterSnapshot,
|
|
73
|
-
* FeeCacheEntryData,
|
|
74
|
-
*
|
|
84
|
+
* FeeCacheEntryData, SpreadCorrectionReadiness, GridUpdateBlockerCode,
|
|
85
|
+
* GridUpdateBlocker, FillPipelineState, GridResizeResult, CowResult
|
|
75
86
|
*
|
|
76
87
|
* ===============================================================================
|
|
77
88
|
*/
|
|
@@ -624,9 +635,73 @@ export declare function isLastFillPlacementBlocked(manager: OrderManagerLike | n
|
|
|
624
635
|
pivot: number | null;
|
|
625
636
|
reason?: 'direction' | 'same-level';
|
|
626
637
|
};
|
|
638
|
+
/**
|
|
639
|
+
* Why a grid update was refused this cycle.
|
|
640
|
+
*
|
|
641
|
+
* These are the ONLY reasons `resolveGridUpdateBlockers` may report. The list
|
|
642
|
+
* is closed on purpose: a new reason must be added here (and to
|
|
643
|
+
* `tests/test_grid_update_blockers.ts`), so "the grid did not update" can never
|
|
644
|
+
* be explained by an unprintable string again.
|
|
645
|
+
*/
|
|
646
|
+
export type GridUpdateBlockerCode = 'fill-queued' | 'fill-deferred' | 'fill-in-flight' | 'crawl-owed' | 'broadcast-pending' | 'placement-held' | 'rebuild-active' | 'unknown-blocker';
|
|
647
|
+
export interface GridUpdateBlocker {
|
|
648
|
+
code: GridUpdateBlockerCode;
|
|
649
|
+
detail: string;
|
|
650
|
+
}
|
|
651
|
+
/** Pipeline state the fill blockers are derived from. `ok: false` means UNREADABLE, not settled. */
|
|
652
|
+
export interface FillPipelineState {
|
|
653
|
+
ok: boolean;
|
|
654
|
+
queued: number;
|
|
655
|
+
deferred: boolean;
|
|
656
|
+
inFlight: number;
|
|
657
|
+
owed: number;
|
|
658
|
+
error?: string;
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* Read the fill-pipeline counters ONCE, from a bot or a bare manager.
|
|
662
|
+
*
|
|
663
|
+
* This is the only place that peeks these fields. The previous projection
|
|
664
|
+
* (`hasUnsettledFills`) swallowed every read error and returned "settled",
|
|
665
|
+
* which is a fail-OPEN answer in a fail-closed system: an unreadable queue
|
|
666
|
+
* looked like an idle one and the grid was updated from a stale master.
|
|
667
|
+
* Unreadable is now a first-class state (`ok: false`), surfaced as
|
|
668
|
+
* `unknown-blocker`.
|
|
669
|
+
*
|
|
670
|
+
* These counters are pipeline bookkeeping, not lifecycle evidence: absence
|
|
671
|
+
* decisions still use the lifecycle registry (INV-LIFE-003), so this reader
|
|
672
|
+
* cannot become a second evidence set.
|
|
673
|
+
*/
|
|
674
|
+
export declare function readFillPipelineState(source: unknown): FillPipelineState;
|
|
675
|
+
export declare function resolveGridUpdateBlockers(source: unknown, options?: {
|
|
676
|
+
now?: number;
|
|
677
|
+
}): GridUpdateBlocker[];
|
|
678
|
+
/**
|
|
679
|
+
* Count consecutive blocked cycles and decide whether the state is STUCK.
|
|
680
|
+
*
|
|
681
|
+
* Escalation is deliberately narrow: only `unknown-blocker` (unreadable
|
|
682
|
+
* pipeline state) escalates. A busy pipeline (`fill-in-flight`,
|
|
683
|
+
* `broadcast-pending`, a held region) is normal work and must not trigger a
|
|
684
|
+
* structural resync — the placement/broadcast watchdogs own those bounds. The
|
|
685
|
+
* counter is a cycle count, not a timing window: it is NOT a `TIMING` entry and
|
|
686
|
+
* must not be classified in `modules/timing_policy.ts`.
|
|
687
|
+
*
|
|
688
|
+
* @returns `{ cycles, escalate }`; `escalate` is true exactly when the state
|
|
689
|
+
* stayed unreadable for `FILL_PROCESSING.GRID_BLOCKED_ESCALATE_CYCLES`
|
|
690
|
+
* consecutive attempts.
|
|
691
|
+
*/
|
|
692
|
+
export declare function noteGridUpdateBlockers(source: unknown, blockers: GridUpdateBlocker[] | null | undefined, options?: {
|
|
693
|
+
limit?: number;
|
|
694
|
+
}): {
|
|
695
|
+
cycles: number;
|
|
696
|
+
escalate: boolean;
|
|
697
|
+
};
|
|
627
698
|
/**
|
|
628
699
|
* Are fills still UNSETTLED (arrived but not yet absorbed by the grid)?
|
|
629
700
|
*
|
|
701
|
+
* Projection over `resolveGridUpdateBlockers` so the prose reason and the code
|
|
702
|
+
* cannot disagree. Kept as a boolean for its existing callers; new callers
|
|
703
|
+
* should ask for the codes.
|
|
704
|
+
*
|
|
630
705
|
* While this returns true the master grid still holds filled slots as ACTIVE
|
|
631
706
|
* and the boundary has not crawled for them, so any geometry-derived plan
|
|
632
707
|
* (window top-up, startup-style reconcile) is built on the PREVIOUS book. The
|
|
@@ -851,7 +926,7 @@ export declare function retryPersistenceIfNeeded(manager: OrderManagerLike): Pro
|
|
|
851
926
|
*
|
|
852
927
|
* @param {Object} manager - OrderManager instance
|
|
853
928
|
* @param {Object} accountOrders - AccountOrders data accessor
|
|
854
|
-
* @param {string}
|
|
929
|
+
* @param {string} _botKey - Unused; persistence is keyed off the manager.
|
|
855
930
|
* @param {Function} updateOrdersOnChainBatchFn - Batch update function for blockchain operations
|
|
856
931
|
* @param {Function} updateGridFromBlockchainSnapshotFn - Grid resize function (injected to avoid circular dependency with grid.ts)
|
|
857
932
|
* @returns {Promise<void>}
|