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
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* Uses AsyncLock to prevent concurrent sync operations (defense-in-depth locking).
|
|
16
16
|
*
|
|
17
17
|
* ===============================================================================
|
|
18
|
-
* TABLE OF CONTENTS - SyncEngine Class (
|
|
18
|
+
* TABLE OF CONTENTS - SyncEngine Class (14 methods) + module-level helpers
|
|
19
19
|
* ===============================================================================
|
|
20
20
|
*
|
|
21
21
|
* MODULE-LEVEL HELPERS (internal, not exported):
|
|
@@ -42,42 +42,46 @@
|
|
|
42
42
|
* 4. _performSyncFromOpenOrders(mgr, precA, precB, parsedChain, rawChain, options) - Core sync logic (internal)
|
|
43
43
|
* Performs actual two-pass reconciliation without locking
|
|
44
44
|
* Pass 1: Match grid orders to chain (known grid → chain, includes orphan cleanup)
|
|
45
|
-
* Pass 2:
|
|
45
|
+
* Pass 2: Bind unmatched chain orders to their genesis-ladder slot (chain → grid)
|
|
46
46
|
*
|
|
47
|
-
* FILL PROCESSING (
|
|
47
|
+
* FILL PROCESSING (6 methods)
|
|
48
48
|
* 5. _findMatchingGridOrder(mgr, orderId) - Look up the grid slot owning a chain order (internal)
|
|
49
49
|
*
|
|
50
|
-
* 6. _computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw
|
|
51
|
-
* Resolve the asset/side context for
|
|
50
|
+
* 6. _computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw,
|
|
51
|
+
* receivesAssetId, receivesAmountRaw) - Resolve the asset/side context for
|
|
52
|
+
* a fill (internal)
|
|
52
53
|
*
|
|
53
54
|
* 7. _computeFillTransitionResult(mgr, params) - Compute the post-fill slot
|
|
54
55
|
* transition and fund deltas without mutating state (internal, async)
|
|
55
56
|
*
|
|
56
|
-
* 8.
|
|
57
|
+
* 8. _absorbUnmatchedFill(mgr, params) - Attribute a fill whose slot was
|
|
58
|
+
* already virtualised (thin wrapper over utils/order.ts) (internal, async)
|
|
59
|
+
*
|
|
60
|
+
* 9. syncFromFillHistory(fill) - Process single fill event synchronously
|
|
57
61
|
* Updates grid order state based on fill data
|
|
58
62
|
* Updates fund state and accounting
|
|
59
63
|
* Handles both maker and taker fills
|
|
60
64
|
*
|
|
61
|
-
*
|
|
65
|
+
* 10. syncFromFillHistoryBatch(fills) - Process multiple fill events in batch
|
|
62
66
|
* Acquires _gridLock once for all fills in block group
|
|
63
67
|
* Batches drift refetch into one get_objects RPC call
|
|
64
68
|
* Applies all grid mutations in a single applyGridUpdateBatch
|
|
65
69
|
*
|
|
66
70
|
* FULL SYNCHRONIZATION (2 methods - async)
|
|
67
|
-
*
|
|
71
|
+
* 11. _assertGenesisInvariant(mgr) - Fail-closed check that a snapshot has a genesis ladder (internal)
|
|
68
72
|
*
|
|
69
|
-
*
|
|
73
|
+
* 12. synchronizeWithChain(chainData, source) - Full sync (fetch + sync) (async)
|
|
70
74
|
* Fetches fresh account balances
|
|
71
75
|
* Calls syncFromOpenOrders() with chain data
|
|
72
76
|
* Source: event type that triggered sync (fill, poll, broadcast, etc.)
|
|
73
77
|
*
|
|
74
78
|
* ACCOUNT STATE (2 methods - async)
|
|
75
|
-
*
|
|
79
|
+
* 13. fetchAccountBalancesAndSetTotals() - Fetch account totals (async)
|
|
76
80
|
* Retrieves BUY/SELL totals and free balances from blockchain
|
|
77
81
|
* Sets manager.accountTotals
|
|
78
82
|
* Triggers fund recalculation
|
|
79
83
|
*
|
|
80
|
-
*
|
|
84
|
+
* 14. initializeAssets() - Initialize asset metadata (async)
|
|
81
85
|
* Fetches asset precision and other metadata
|
|
82
86
|
* Sets manager.assets
|
|
83
87
|
* Called once at bot startup
|
|
@@ -101,10 +105,16 @@
|
|
|
101
105
|
* - Update sizes and mark as filled if needed
|
|
102
106
|
* - Downgrade to VIRTUAL if not found on-chain
|
|
103
107
|
*
|
|
104
|
-
* PASS 2: Chain → Grid
|
|
105
|
-
* - For each chain order not matched
|
|
106
|
-
*
|
|
107
|
-
* -
|
|
108
|
+
* PASS 2: Chain → Grid (genesis-frozen nearest-slot adoption)
|
|
109
|
+
* - For each chain order not matched in pass 1, resolve its slot from the
|
|
110
|
+
* frozen price ladder (`slotIndexForPrice`) and adopt it there
|
|
111
|
+
* - No tolerance matcher remains: without a ladder the E2 gate refuses the
|
|
112
|
+
* sync, and a ladder-less grid defers every orphan instead of matching it
|
|
113
|
+
* - A price outside the grid range is HELD/deferred (nearest slot is only
|
|
114
|
+
* reported as a hint) — it is never adopted into a rail slot
|
|
115
|
+
* - An order whose price cannot be resolved to a slot is queued for a
|
|
116
|
+
* cancel-only correction; the deferred (no-ladder / out-of-grid) cases are
|
|
117
|
+
* logged and held, never dropped silently
|
|
108
118
|
*
|
|
109
119
|
* ===============================================================================
|
|
110
120
|
*/
|
|
@@ -142,6 +152,7 @@ import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slot
|
|
|
142
152
|
import { parseChainOrder, geometryTypeForSlotIndex, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance, _filterUnmatchedChainOrders, attributeUnmatchedFillToGrid, reviveVirtualSlotFromChain, resolveExecutionPrice } from './utils/order.js';
|
|
143
153
|
import { parseSlotIndex } from './utils/slot.js';
|
|
144
154
|
import { readSlotLifecycle } from './lifecycle.js';
|
|
155
|
+
import { resolveTradedSide } from './fill_ledger.js';
|
|
145
156
|
import { resolveProcessedFillPersistenceMode } from './processed_fill_store.js';
|
|
146
157
|
import { hasGenesisLadder } from './genesis_policy.js';
|
|
147
158
|
import { getErrorMessage } from '../utils/errors.js';
|
|
@@ -531,72 +542,15 @@ class SyncEngine {
|
|
|
531
542
|
this.manager = manager;
|
|
532
543
|
}
|
|
533
544
|
/**
|
|
534
|
-
* Reconcile grid orders against fresh blockchain open
|
|
535
|
-
* This is the MAIN SYNCHRONIZATION MECHANISM
|
|
536
|
-
*
|
|
537
|
-
*
|
|
538
|
-
*
|
|
539
|
-
* full-sync operation runs at a time. WITHIN that lock, per-order locks prevent
|
|
540
|
-
* concurrent createOrder/cancelOrder races.
|
|
541
|
-
*
|
|
542
|
-
* LOCK HIERARCHY:
|
|
543
|
-
* 1. _syncLock (AsyncLock): Ensures only one full-sync at a time
|
|
544
|
-
* 2. Per-order locks (shadowOrderIds): Protect specific orders during sync
|
|
545
|
-
* 3. Lock refresh mechanism: Prevents timeout during long reconciliation
|
|
546
|
-
*
|
|
547
|
-
* RECONCILIATION FLOW:
|
|
548
|
-
* ========================================================================
|
|
549
|
-
* This method performs a two-pass reconciliation:
|
|
550
|
-
*
|
|
551
|
-
* PASS 1: Match grid orders to chain orders (known grid → chain lookup)
|
|
552
|
-
* - For each grid order with an orderId, find the matching chain order
|
|
553
|
-
* - Detect partial fills: if chain size < grid size, downgrade to PARTIAL state
|
|
554
|
-
* - Detect full fills: if order no longer exists on chain, convert to SPREAD
|
|
555
|
-
* - Detect price slippage: flag orders for price correction if needed
|
|
556
|
-
* - Update grid order sizes to match chain reality
|
|
545
|
+
* Reconcile grid orders against a fresh blockchain open-orders snapshot.
|
|
546
|
+
* This is the MAIN SYNCHRONIZATION MECHANISM: it corrects the grid when the
|
|
547
|
+
* chain state diverges from local expectations. The two-pass structure, the
|
|
548
|
+
* lock hierarchy and the per-pass rules live in the module header; the
|
|
549
|
+
* fail-closed genesis gate (E2) runs before anything is touched.
|
|
557
550
|
*
|
|
558
|
-
* PASS 2: Orphan chain orders (chain → grid lookup)
|
|
559
|
-
* - For chain orders not matched in Pass 1, find best grid slot match
|
|
560
|
-
* - This handles cases where an order was placed but grid lost track (race condition)
|
|
561
|
-
* - Uses price tolerance and geometric proximity to find the best match
|
|
562
|
-
* - Once matched, retroactively assign orderId and synchronize state
|
|
563
|
-
*
|
|
564
|
-
* CRITICAL RULES:
|
|
565
|
-
* 1. ACTIVE orders can only stay ACTIVE if size matches chain exactly
|
|
566
|
-
* If chain size < grid size → must transition to PARTIAL
|
|
567
|
-
* 2. If an ACTIVE order is not found on chain → it filled → convert to SPREAD
|
|
568
|
-
* 3. Precision matters: Use blockchain integer arithmetic to compare sizes
|
|
569
|
-
* Floating point comparisons can give false positives for partial fills
|
|
570
|
-
* 4. Size updates are applied via applyChainSizeToGridOrder() which handles
|
|
571
|
-
* precision conversion and may adjust sizes slightly for blockchain granularity
|
|
572
|
-
*
|
|
573
|
-
* PRICE TOLERANCE CALCULATION:
|
|
574
|
-
* calculatePriceTolerance() can return null in these cases:
|
|
575
|
-
* 1. assets parameter is null/missing
|
|
576
|
-
* 2. gridPrice is 0 or null (invalid price)
|
|
577
|
-
* 3. orderSize is 0 or null (invalid size - orders should not sync with 0 size)
|
|
578
|
-
* 4. assetA or assetB precision is undefined (asset metadata not loaded)
|
|
579
|
-
* When tolerance is null, we treat it as 0 (strict: any price difference flagged).
|
|
580
|
-
* This is safe because null signals a configuration/data issue, not a real order.
|
|
581
|
-
*
|
|
582
|
-
* RETURNS: { filledOrders, updatedOrders, ordersNeedingCorrection }
|
|
583
|
-
* - filledOrders: Orders that completed (now SPREAD placeholders)
|
|
584
|
-
* - updatedOrders: All orders modified during sync (state changes, size updates)
|
|
585
|
-
* - ordersNeedingCorrection: Orders with price slippage requiring correction
|
|
586
|
-
*
|
|
587
|
-
* EDGE CASES HANDLED:
|
|
588
|
-
* - Orphan chain orders (placed but grid lost track due to race condition)
|
|
589
|
-
* - Partial fills (size reduced on chain)
|
|
590
|
-
* - Full fills (order removed from chain completely)
|
|
591
|
-
* - Price tolerance (small slippage acceptable, large slippage flagged)
|
|
592
|
-
* - Precision mismatches (blockchain integer precision vs float grid)
|
|
593
|
-
* - Double spending prevention (each chain order matched to at most one grid order)
|
|
594
|
-
*/
|
|
595
|
-
/**
|
|
596
|
-
* Synchronize grid orders with blockchain open orders snapshot.
|
|
597
551
|
* @param {Array|null} chainOrders - Array of blockchain order objects
|
|
598
552
|
* @param {Object} [options={}] - Sync options (e.g., { skipAccounting: true })
|
|
599
|
-
* @returns {Promise<
|
|
553
|
+
* @returns {Promise<SyncResult>} filledOrders, updatedOrders, ordersNeedingCorrection
|
|
600
554
|
*/
|
|
601
555
|
async syncFromOpenOrders(chainOrders, options = {}) {
|
|
602
556
|
const mgr = this.manager;
|
|
@@ -1547,31 +1501,34 @@ class SyncEngine {
|
|
|
1547
1501
|
const assets = mgr.assets;
|
|
1548
1502
|
if (!assets?.assetA || !assets?.assetB)
|
|
1549
1503
|
throw new Error('assets required for fill context');
|
|
1550
|
-
//
|
|
1551
|
-
//
|
|
1552
|
-
//
|
|
1553
|
-
//
|
|
1554
|
-
//
|
|
1555
|
-
// the
|
|
1556
|
-
//
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1504
|
+
// The fill's paid asset is the ground truth for the order side. The
|
|
1505
|
+
// slot type is only a grid identity and can be retyped (BUY<->SELL)
|
|
1506
|
+
// before the resting chain order is corrected; trusting it classified
|
|
1507
|
+
// a real SELL fill as a BUY (filledAmount=0 because the paid asset did
|
|
1508
|
+
// not match the slot's expected quote side) and the phantom fill was
|
|
1509
|
+
// re-bought at the fill level. Resolving the side from `paysAssetId`
|
|
1510
|
+
// also selects the correct size asset (BUY sizes are quote, SELL
|
|
1511
|
+
// sizes are base), so `filledAmount`/`precision` stay dimensionally
|
|
1512
|
+
// consistent with the resting order's size.
|
|
1513
|
+
// One resolver for "which side did this trade" (order/fill_ledger.ts):
|
|
1514
|
+
// the paid asset is chain truth, the slot type is only the fallback.
|
|
1515
|
+
// A SPREAD slot carries no rail side, so it is resolved from the
|
|
1516
|
+
// price-vs-startPrice convention without leaking SPREAD into the
|
|
1517
|
+
// transition (validateOrder treats an on-chain SPREAD state as fatal
|
|
1518
|
+
// ILLEGAL_SPREAD_STATE).
|
|
1519
|
+
const fallbackSide = matchedGridOrder.type === ORDER_TYPES.SPREAD
|
|
1520
|
+
? resolveSpreadOrderSide(matchedGridOrder.price, mgr.config.startPrice)
|
|
1521
|
+
: matchedGridOrder.type;
|
|
1522
|
+
const orderType = (resolveTradedSide(paysAssetId, assets, fallbackSide) ?? matchedGridOrder.type);
|
|
1566
1523
|
const currentSize = toFiniteNumber(matchedGridOrder.size);
|
|
1567
1524
|
const precision = (orderType === ORDER_TYPES.SELL) ? assets.assetA.precision : assets.assetB.precision;
|
|
1568
1525
|
let filledAmount = 0;
|
|
1569
1526
|
if (orderType === ORDER_TYPES.SELL) {
|
|
1570
|
-
if (paysAssetId === assets.assetA.id)
|
|
1527
|
+
if (paysAssetId != null && paysAssetId === assets.assetA.id)
|
|
1571
1528
|
filledAmount = blockchainToFloat(paysAmountRaw, precision);
|
|
1572
1529
|
}
|
|
1573
1530
|
else {
|
|
1574
|
-
if (paysAssetId === assets.assetB.id)
|
|
1531
|
+
if (paysAssetId != null && paysAssetId === assets.assetB.id)
|
|
1575
1532
|
filledAmount = blockchainToFloat(paysAmountRaw, precision);
|
|
1576
1533
|
}
|
|
1577
1534
|
const currentSizeIntFromGrid = floatToBlockchainInt(currentSize, precision);
|
|
@@ -1603,21 +1560,16 @@ class SyncEngine {
|
|
|
1603
1560
|
// `rawOnChain.for_sale` may already include the part of this fill that
|
|
1604
1561
|
// sync pass 1 absorbed. Subtract only the NOT-yet-applied remainder;
|
|
1605
1562
|
// subtracting the whole fill (or none of it) is the double-shrink /
|
|
1606
|
-
// growth pair from the 2026-11-03 incident.
|
|
1607
|
-
//
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
//
|
|
1612
|
-
//
|
|
1613
|
-
//
|
|
1614
|
-
//
|
|
1615
|
-
|
|
1616
|
-
// only, so the explicit sum must win).
|
|
1617
|
-
const hasExplicitApplied = params.alreadyAppliedInt != null
|
|
1618
|
-
&& Number.isFinite(Number(params.alreadyAppliedInt));
|
|
1619
|
-
const appliedFromBoolean = !hasExplicitApplied && params.alreadyAppliedChainSize ? filledAmountInt : 0;
|
|
1620
|
-
const appliedInt = Math.max(0, Math.min(filledAmountInt, Math.max(explicitApplied, appliedFromBoolean)));
|
|
1563
|
+
// growth pair from the 2026-11-03 incident.
|
|
1564
|
+
//
|
|
1565
|
+
// ONE channel: the applied AMOUNT. The pre-P2 `alreadyAppliedChainSize`
|
|
1566
|
+
// boolean is gone — it carried the same fact without a number, so it
|
|
1567
|
+
// could disagree with the amount, and the aggregated path read it off
|
|
1568
|
+
// the LAST group entry only (a group with one marked entry collapsed the
|
|
1569
|
+
// unapplied remainder of its siblings to 0). `processFillAccounting`
|
|
1570
|
+
// writes `__chainSizeAppliedInt` on every marker it consumes, so the
|
|
1571
|
+
// amount is total.
|
|
1572
|
+
const appliedInt = Math.max(0, Math.min(filledAmountInt, Math.round(Number(params.alreadyAppliedInt)) || 0));
|
|
1621
1573
|
const remainingFillInt = Math.max(0, filledAmountInt - appliedInt);
|
|
1622
1574
|
const newSizeInt = Math.max(0, currentSizeInt - remainingFillInt);
|
|
1623
1575
|
const newSize = blockchainToFloat(newSizeInt, precision);
|
|
@@ -1734,6 +1686,12 @@ class SyncEngine {
|
|
|
1734
1686
|
isMaker
|
|
1735
1687
|
};
|
|
1736
1688
|
const { btsFeeState, ...matchedWithoutDeferredFee } = matchedGridOrder;
|
|
1689
|
+
// Store the TRADED side, not the slot's old label: `size` below is
|
|
1690
|
+
// in that side's units, and accounting/recalculateFunds resolve
|
|
1691
|
+
// dimensions from order.type. This does NOT launder a queued
|
|
1692
|
+
// typeMismatch cancel — its drain-time validator compares the
|
|
1693
|
+
// level's rail geometry, not just slot.type (see
|
|
1694
|
+
// _validatePriceCorrectionEntry).
|
|
1737
1695
|
let updatedOrder = { ...matchedWithoutDeferredFee, type: orderType, state: ORDER_STATES.PARTIAL };
|
|
1738
1696
|
if (updatedOrder.rawOnChain && updatedOrder.rawOnChain.for_sale !== undefined) {
|
|
1739
1697
|
// The snapshot's for_sale is the authoritative remaining size
|
|
@@ -1880,7 +1838,6 @@ class SyncEngine {
|
|
|
1880
1838
|
isMaker,
|
|
1881
1839
|
fillPrice: ctx.fillPrice,
|
|
1882
1840
|
alreadyAppliedInt: Math.max(0, Math.round(Number(fillOp.__chainSizeAppliedInt) || 0)),
|
|
1883
|
-
alreadyAppliedChainSize: Boolean(fillOp.__chainSizeAlreadyApplied)
|
|
1884
1841
|
});
|
|
1885
1842
|
const filledOrders = [];
|
|
1886
1843
|
const updatedOrders = [];
|
|
@@ -2169,7 +2126,6 @@ class SyncEngine {
|
|
|
2169
2126
|
isMaker: lastCtx.entry.isMaker,
|
|
2170
2127
|
fillPrice: lastCtx.fillPrice,
|
|
2171
2128
|
alreadyAppliedInt: Math.min(totalFilledAmountInt, Math.max(0, totalAppliedInt)),
|
|
2172
|
-
alreadyAppliedChainSize: Boolean(lastCtx.entry.fillOp.__chainSizeAlreadyApplied)
|
|
2173
2129
|
});
|
|
2174
2130
|
if (result.isFull) {
|
|
2175
2131
|
mgr.logger.log(`[SYNC] Full fill for order ${orderId} (slot ${matchedGridOrder.id}).`, 'info');
|
|
@@ -2229,55 +2185,6 @@ class SyncEngine {
|
|
|
2229
2185
|
mgr._fillBatchInFlight--;
|
|
2230
2186
|
}
|
|
2231
2187
|
}
|
|
2232
|
-
/**
|
|
2233
|
-
* High-level dispatcher for different blockchain synchronization sources.
|
|
2234
|
-
* Routes to the appropriate sync strategy based on the data source.
|
|
2235
|
-
*
|
|
2236
|
-
* SOURCES AND STRATEGIES:
|
|
2237
|
-
* ========================================================================
|
|
2238
|
-
* source: 'createOrder'
|
|
2239
|
-
* Purpose: Grid order was successfully placed on-chain
|
|
2240
|
-
* Data: { gridOrderId, chainOrderId, isPartialPlacement, fee }
|
|
2241
|
-
* Action:
|
|
2242
|
-
* 1. Look up grid order by gridOrderId
|
|
2243
|
-
* 2. Assign the returned chainOrderId (so we can find it later)
|
|
2244
|
-
* 3. Transition state based on isPartialPlacement:
|
|
2245
|
-
* - false → ACTIVE (full order placed)
|
|
2246
|
-
* - true → PARTIAL (placed as partial, likely due to insufficient funds)
|
|
2247
|
-
* 4. Update optimistic chainFree balance (deduct fees if BTS pair)
|
|
2248
|
-
* Fund Impact: Funds transition from free → locked/committed
|
|
2249
|
-
*
|
|
2250
|
-
* source: 'cancelOrder'
|
|
2251
|
-
* Purpose: Grid order was successfully cancelled on-chain
|
|
2252
|
-
* Data: The chainOrderId to cancel
|
|
2253
|
-
* Action:
|
|
2254
|
-
* 1. Find grid order by orderId (reverse lookup)
|
|
2255
|
-
* 2. Transition to VIRTUAL (order no longer on-chain)
|
|
2256
|
-
* 3. Clear orderId so it can be re-used
|
|
2257
|
-
* 4. Update optimistic chainFree balance (add funds back as free)
|
|
2258
|
-
* Fund Impact: Funds transition from locked → free
|
|
2259
|
-
* Note: This is used for direct cancellations (not rotation/consolidation)
|
|
2260
|
-
*
|
|
2261
|
-
* source: 'readOpenOrders' or 'periodicBlockchainFetch'
|
|
2262
|
-
* Purpose: Full snapshot sync of all open orders from blockchain
|
|
2263
|
-
* Data: Array of chain orders from blockchain API
|
|
2264
|
-
* Action: Delegates to syncFromOpenOrders() for full reconciliation
|
|
2265
|
-
* Use Case: Periodic health check or startup initialization
|
|
2266
|
-
*
|
|
2267
|
-
* FUND TRACKING:
|
|
2268
|
-
* Both 'createOrder' and 'cancelOrder' call updateOptimisticFreeBalance() to
|
|
2269
|
-
* keep the optimistic chainFree balance in sync with actual on-chain state.
|
|
2270
|
-
* This prevents fund leaks where placed orders weren't deducted or cancelled
|
|
2271
|
-
* orders weren't released.
|
|
2272
|
-
*
|
|
2273
|
-
* RETURNS: { newOrders, ordersNeedingCorrection }
|
|
2274
|
-
* Most callers use ordersNeedingCorrection to flag price corrections needed.
|
|
2275
|
-
* Only syncFromOpenOrders() populates ordersNeedingCorrection.
|
|
2276
|
-
*
|
|
2277
|
-
* @param {Object} chainData - Chain event data
|
|
2278
|
-
* @param {string} source - Source identifier ('createOrder', 'cancelOrder', 'readOpenOrders', etc.)
|
|
2279
|
-
* @returns {Promise<Object>} { newOrders, ordersNeedingCorrection }
|
|
2280
|
-
*/
|
|
2281
2188
|
/**
|
|
2282
2189
|
* E2 invariant assert: a manager holding grid slots but no price ladder is
|
|
2283
2190
|
* in the undefined state the grid-price invariant forbids (INV-GRID-004).
|
|
@@ -2328,6 +2235,55 @@ class SyncEngine {
|
|
|
2328
2235
|
return false;
|
|
2329
2236
|
}
|
|
2330
2237
|
}
|
|
2238
|
+
/**
|
|
2239
|
+
* High-level dispatcher for the different blockchain synchronization
|
|
2240
|
+
* sources. Routes each source to its strategy and returns a uniform result
|
|
2241
|
+
* shape.
|
|
2242
|
+
*
|
|
2243
|
+
* SOURCES AND STRATEGIES:
|
|
2244
|
+
* ========================================================================
|
|
2245
|
+
* source: 'createOrder'
|
|
2246
|
+
* Purpose: Grid order was successfully placed on-chain
|
|
2247
|
+
* Data: { gridOrderId, chainOrderId, isPartialPlacement, expectedType, fee, order? }
|
|
2248
|
+
* Action:
|
|
2249
|
+
* 1. Look up grid order by gridOrderId
|
|
2250
|
+
* 2. Assign the returned chainOrderId (so we can find it later)
|
|
2251
|
+
* 3. Transition state based on isPartialPlacement:
|
|
2252
|
+
* - false → ACTIVE (full order placed)
|
|
2253
|
+
* - true → PARTIAL (placed as partial, likely due to insufficient funds)
|
|
2254
|
+
* 4. Apply the transition through _applyOrderUpdate (skipAccounting:
|
|
2255
|
+
* false), which owns the optimistic chainFree update and the BTS fee
|
|
2256
|
+
* Fund Impact: Funds transition from free → locked/committed
|
|
2257
|
+
*
|
|
2258
|
+
* source: 'cancelOrder'
|
|
2259
|
+
* Purpose: Grid order was successfully cancelled on-chain
|
|
2260
|
+
* Data: The chainOrderId to cancel
|
|
2261
|
+
* Action:
|
|
2262
|
+
* 1. Find grid order by orderId (reverse lookup)
|
|
2263
|
+
* 2. Transition to VIRTUAL (order no longer on-chain)
|
|
2264
|
+
* 3. Clear orderId so it can be re-used
|
|
2265
|
+
* 4. Apply the transition through _applyOrderUpdate
|
|
2266
|
+
* Fund Impact: Funds transition from locked → free
|
|
2267
|
+
* Note: This is used for direct cancellations (not rotation/consolidation).
|
|
2268
|
+
* A cancel whose slot vanished still deducts its fee from the totals
|
|
2269
|
+
* via adjustTotalBalance, so the books cannot drift.
|
|
2270
|
+
*
|
|
2271
|
+
* source: 'readOpenOrders' or 'periodicBlockchainFetch'
|
|
2272
|
+
* Purpose: Full snapshot sync of all open orders from blockchain
|
|
2273
|
+
* Data: Array of chain orders from blockchain API
|
|
2274
|
+
* Action: Delegates to syncFromOpenOrders() for full reconciliation
|
|
2275
|
+
* Use Case: Periodic health check or startup initialization
|
|
2276
|
+
*
|
|
2277
|
+
* FUND TRACKING:
|
|
2278
|
+
* The two event sources move funds through _applyOrderUpdate (and, for an
|
|
2279
|
+
* unmatched cancel, adjustTotalBalance), so the optimistic chainFree balance
|
|
2280
|
+
* cannot be bypassed by an event path. This prevents fund leaks where placed
|
|
2281
|
+
* orders weren't deducted or cancelled orders weren't released.
|
|
2282
|
+
*
|
|
2283
|
+
* @param {Object} chainData - Chain event data
|
|
2284
|
+
* @param {string} source - Source identifier ('createOrder', 'cancelOrder', 'readOpenOrders', 'periodicBlockchainFetch')
|
|
2285
|
+
* @returns {Promise<Object>} { newOrders, filledOrders, updatedOrders, ordersNeedingCorrection }
|
|
2286
|
+
*/
|
|
2331
2287
|
async synchronizeWithChain(chainData, source) {
|
|
2332
2288
|
const mgr = this.manager;
|
|
2333
2289
|
if (!mgr.assets)
|
|
@@ -4,10 +4,10 @@
|
|
|
4
4
|
* Pure numeric calculations, blockchain conversions, fee math, and fund allocation.
|
|
5
5
|
*
|
|
6
6
|
* ===============================================================================
|
|
7
|
-
* TABLE OF CONTENTS (
|
|
7
|
+
* TABLE OF CONTENTS (80 exports + the GridGenesis and FeeCacheEntry types)
|
|
8
8
|
* ===============================================================================
|
|
9
9
|
*
|
|
10
|
-
* SECTION 1: GENESIS LADDER & RAIL GEOMETRY (
|
|
10
|
+
* SECTION 1: GENESIS LADDER & RAIL GEOMETRY (29 exports + the GridGenesis type)
|
|
11
11
|
* - GridGenesis - Genesis ladder type: start price, increment, gap slots,
|
|
12
12
|
* price levels and their hash
|
|
13
13
|
* - priceLevelsForGenesis(genesis) - Extract the frozen price ladder from a genesis
|
|
@@ -36,6 +36,8 @@
|
|
|
36
36
|
* - isEvacuationSizeStillValid(...) - Re-proof a stamped evacuation size against live geometry
|
|
37
37
|
* - validateBoundaryCommit(...) - Validate a proposed boundary commit against geometry
|
|
38
38
|
* - validatePersistedBoundary(...) - Validate a boundary restored from disk
|
|
39
|
+
* - boundaryMoveReducesStrands(...) - Whether a boundary move reduces stranded rail slots
|
|
40
|
+
* - pricesWithinHalfStep(a, b, ...) - Same ladder level within half a grid step
|
|
39
41
|
* - isTransientInBandRejection(reason) - Whether a persisted-boundary rejection is transient
|
|
40
42
|
* - BOUNDARY_REJECT_PLACED_IN_BAND - Rejection reason: target slot holds an in-band order
|
|
41
43
|
*
|
|
@@ -51,9 +53,10 @@
|
|
|
51
53
|
* - resolveRelativePrice(value, startPrice, mode) - Resolve relative price values
|
|
52
54
|
* - validateGridPriceBounds(min, max, center) - Reject bounds not bracketing center
|
|
53
55
|
*
|
|
54
|
-
* SECTION 3: FUND CALCULATIONS (
|
|
56
|
+
* SECTION 3: FUND CALCULATIONS (9 functions)
|
|
55
57
|
* - computeChainFundTotals(accountTotals, committedChain) - Compute total funds
|
|
56
58
|
* - calculateAvailableFundsValue(side, accountTotals, funds, ...) - Calculate available funds
|
|
59
|
+
* - deriveChainTruthFundBudget(...) - Side budget derived from chain-truth totals
|
|
57
60
|
* - adjustBudgetForBtsFees(budget, btsFeeData, ...) - Reserve BTS fees from a side budget
|
|
58
61
|
* - getGridBestPrices(manager) - Best (highest) buy and best (lowest) sell price
|
|
59
62
|
* - calculateSpreadFromOrders(activeBuys, activeSells) - Calculate spread percentage
|
|
@@ -89,6 +92,7 @@
|
|
|
89
92
|
* - getAssetFees(assetSymbol, assetAmount, isMaker) - Get fee info for asset
|
|
90
93
|
* - getAssetFeesSafe(assetSymbol, assetAmount, isMaker) - Fee info without throwing
|
|
91
94
|
* - _setFeeCache(cache) - Set internal fee cache (internal)
|
|
95
|
+
* - FeeCacheEntry - Per-asset fee-cache row type consumed by _setFeeCache
|
|
92
96
|
*
|
|
93
97
|
* SECTION 8: FUND ALLOCATION (6 functions)
|
|
94
98
|
* - allocateFundsByWeights(available, targetCount) - Allocate funds by weight
|
|
@@ -4,10 +4,10 @@
|
|
|
4
4
|
* Pure numeric calculations, blockchain conversions, fee math, and fund allocation.
|
|
5
5
|
*
|
|
6
6
|
* ===============================================================================
|
|
7
|
-
* TABLE OF CONTENTS (
|
|
7
|
+
* TABLE OF CONTENTS (80 exports + the GridGenesis and FeeCacheEntry types)
|
|
8
8
|
* ===============================================================================
|
|
9
9
|
*
|
|
10
|
-
* SECTION 1: GENESIS LADDER & RAIL GEOMETRY (
|
|
10
|
+
* SECTION 1: GENESIS LADDER & RAIL GEOMETRY (29 exports + the GridGenesis type)
|
|
11
11
|
* - GridGenesis - Genesis ladder type: start price, increment, gap slots,
|
|
12
12
|
* price levels and their hash
|
|
13
13
|
* - priceLevelsForGenesis(genesis) - Extract the frozen price ladder from a genesis
|
|
@@ -36,6 +36,8 @@
|
|
|
36
36
|
* - isEvacuationSizeStillValid(...) - Re-proof a stamped evacuation size against live geometry
|
|
37
37
|
* - validateBoundaryCommit(...) - Validate a proposed boundary commit against geometry
|
|
38
38
|
* - validatePersistedBoundary(...) - Validate a boundary restored from disk
|
|
39
|
+
* - boundaryMoveReducesStrands(...) - Whether a boundary move reduces stranded rail slots
|
|
40
|
+
* - pricesWithinHalfStep(a, b, ...) - Same ladder level within half a grid step
|
|
39
41
|
* - isTransientInBandRejection(reason) - Whether a persisted-boundary rejection is transient
|
|
40
42
|
* - BOUNDARY_REJECT_PLACED_IN_BAND - Rejection reason: target slot holds an in-band order
|
|
41
43
|
*
|
|
@@ -51,9 +53,10 @@
|
|
|
51
53
|
* - resolveRelativePrice(value, startPrice, mode) - Resolve relative price values
|
|
52
54
|
* - validateGridPriceBounds(min, max, center) - Reject bounds not bracketing center
|
|
53
55
|
*
|
|
54
|
-
* SECTION 3: FUND CALCULATIONS (
|
|
56
|
+
* SECTION 3: FUND CALCULATIONS (9 functions)
|
|
55
57
|
* - computeChainFundTotals(accountTotals, committedChain) - Compute total funds
|
|
56
58
|
* - calculateAvailableFundsValue(side, accountTotals, funds, ...) - Calculate available funds
|
|
59
|
+
* - deriveChainTruthFundBudget(...) - Side budget derived from chain-truth totals
|
|
57
60
|
* - adjustBudgetForBtsFees(budget, btsFeeData, ...) - Reserve BTS fees from a side budget
|
|
58
61
|
* - getGridBestPrices(manager) - Best (highest) buy and best (lowest) sell price
|
|
59
62
|
* - calculateSpreadFromOrders(activeBuys, activeSells) - Calculate spread percentage
|
|
@@ -89,6 +92,7 @@
|
|
|
89
92
|
* - getAssetFees(assetSymbol, assetAmount, isMaker) - Get fee info for asset
|
|
90
93
|
* - getAssetFeesSafe(assetSymbol, assetAmount, isMaker) - Fee info without throwing
|
|
91
94
|
* - _setFeeCache(cache) - Set internal fee cache (internal)
|
|
95
|
+
* - FeeCacheEntry - Per-asset fee-cache row type consumed by _setFeeCache
|
|
92
96
|
*
|
|
93
97
|
* SECTION 8: FUND ALLOCATION (6 functions)
|
|
94
98
|
* - allocateFundsByWeights(available, targetCount) - Allocate funds by weight
|