dexbot 1.6.18 → 1.7.1
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 +68 -0
- package/README.md +24 -18
- package/analysis/README.md +117 -5
- 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/account_resolver.js +5 -6
- package/dist/analysis/analyze_dynamic_weight.js +2 -1
- package/dist/analysis/analyze_kalman.js +3 -2
- package/dist/analysis/analyze_liquidity.d.ts +17 -0
- package/dist/analysis/analyze_liquidity.js +336 -0
- package/dist/analysis/analyze_regime.js +3 -2
- package/dist/analysis/analyze_regime_windows.js +3 -2
- package/dist/analysis/analyze_volatility.js +3 -2
- package/dist/analysis/bot_key_utils.d.ts +44 -1
- package/dist/analysis/bot_key_utils.js +76 -7
- package/dist/analysis/fills_cache.js +2 -1
- package/dist/analysis/grid_correction_check.d.ts +1 -19
- package/dist/analysis/grid_correction_check.js +12 -30
- package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
- package/dist/analysis/liquidity/liquidity_chain.js +178 -0
- package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
- package/dist/analysis/liquidity/liquidity_chart_generator.js +693 -0
- package/dist/analysis/liquidity/liquidity_depth_model.d.ts +166 -0
- package/dist/analysis/liquidity/liquidity_depth_model.js +258 -0
- package/dist/analysis/liquidity/liquidity_view.d.ts +53 -0
- package/dist/analysis/liquidity/liquidity_view.js +66 -0
- package/dist/analysis/resolve_bot_accounts.js +7 -6
- package/dist/analysis/trade_profitability.js +4 -2
- package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
- package/dist/credential-daemon.js +13 -2
- package/dist/dexbot.js +77 -172
- package/dist/modules/account_bots.d.ts +11 -1
- package/dist/modules/account_orders.d.ts +12 -0
- package/dist/modules/account_orders.js +30 -0
- package/dist/modules/asset_lookup.d.ts +25 -0
- package/dist/modules/asset_lookup.js +75 -0
- package/dist/modules/bitshares-native/transport.js +24 -6
- package/dist/modules/bitshares_client.d.ts +24 -6
- package/dist/modules/bitshares_client.js +44 -7
- package/dist/modules/bot_settings.d.ts +2 -0
- package/dist/modules/chain_scan.d.ts +64 -0
- package/dist/modules/chain_scan.js +80 -0
- package/dist/modules/cli_colors.d.ts +5 -0
- package/dist/modules/cli_colors.js +7 -0
- package/dist/modules/cli_progress.d.ts +51 -0
- package/dist/modules/cli_progress.js +113 -0
- package/dist/modules/constants.d.ts +26 -3
- package/dist/modules/constants.js +63 -8
- package/dist/modules/dexbot_class.d.ts +1 -6
- package/dist/modules/dexbot_class.js +14 -0
- package/dist/modules/dexbot_cow_runtime.d.ts +97 -7
- package/dist/modules/dexbot_cow_runtime.js +634 -136
- package/dist/modules/dexbot_fill_runtime.js +132 -23
- package/dist/modules/dexbot_maintenance_runtime.js +242 -74
- package/dist/modules/dexbot_startup_runtime.js +32 -20
- package/dist/modules/dexbot_state_recovery.d.ts +33 -1
- package/dist/modules/dexbot_state_recovery.js +167 -5
- package/dist/modules/launcher/runtime_entry.d.ts +21 -1
- package/dist/modules/launcher/runtime_entry.js +36 -1
- package/dist/modules/liquidity_pool_ref.d.ts +32 -0
- package/dist/modules/liquidity_pool_ref.js +116 -0
- package/dist/modules/node_connect_policy.d.ts +8 -1
- package/dist/modules/node_connect_policy.js +18 -2
- package/dist/modules/node_flap_score.d.ts +87 -0
- package/dist/modules/node_flap_score.js +124 -0
- package/dist/modules/node_health_cache.d.ts +40 -3
- package/dist/modules/node_health_cache.js +66 -20
- package/dist/modules/node_manager.d.ts +101 -19
- package/dist/modules/node_manager.js +255 -65
- package/dist/modules/order/accounting.js +56 -7
- package/dist/modules/order/format.d.ts +24 -10
- package/dist/modules/order/format.js +30 -10
- package/dist/modules/order/grid.js +91 -13
- package/dist/modules/order/grid_reconcile.d.ts +5 -1
- package/dist/modules/order/grid_reconcile.js +333 -189
- package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
- package/dist/modules/order/grid_reconcile_internal.js +298 -100
- package/dist/modules/order/index.d.ts +19 -1
- package/dist/modules/order/lifecycle.d.ts +353 -0
- package/dist/modules/order/lifecycle.js +1109 -0
- package/dist/modules/order/manager.d.ts +273 -5
- package/dist/modules/order/manager.js +654 -48
- package/dist/modules/order/placement_lock.d.ts +102 -0
- package/dist/modules/order/placement_lock.js +222 -0
- package/dist/modules/order/strategy.js +13 -1
- package/dist/modules/order/sync_engine.d.ts +33 -1
- package/dist/modules/order/sync_engine.js +241 -73
- package/dist/modules/order/utils/math.d.ts +39 -1
- package/dist/modules/order/utils/math.js +83 -1
- package/dist/modules/order/utils/order.d.ts +181 -5
- package/dist/modules/order/utils/order.js +455 -9
- package/dist/modules/order/utils/system.d.ts +81 -1
- package/dist/modules/order/utils/system.js +331 -44
- package/dist/modules/order/utils/validate.d.ts +7 -1
- package/dist/modules/order/utils/validate.js +80 -3
- package/dist/modules/outcome.d.ts +54 -0
- package/dist/modules/outcome.js +51 -0
- package/dist/modules/settings_merge.d.ts +4 -0
- package/dist/modules/settings_merge.js +9 -0
- package/dist/modules/timing_policy.d.ts +82 -0
- package/dist/modules/timing_policy.js +244 -0
- package/dist/modules/types.d.ts +137 -0
- package/dist/modules/utils/asset_symbols.d.ts +13 -2
- package/dist/modules/utils/asset_symbols.js +21 -2
- package/dist/scripts/analysis_runner.d.ts +10 -0
- package/dist/scripts/analysis_runner.js +33 -0
- package/dist/scripts/analyze-credit.js +54 -17
- package/dist/scripts/analyze-orders.d.ts +4 -2
- package/dist/scripts/analyze-orders.js +115 -35
- package/dist/scripts/asset.d.ts +26 -0
- package/dist/scripts/asset.js +165 -0
- package/dist/scripts/bts_distribution.d.ts +1 -0
- package/dist/scripts/bts_distribution.js +194 -142
- package/dist/scripts/chart_command.d.ts +1 -1
- package/dist/scripts/chart_command.js +60 -86
- package/dist/scripts/chart_targets.d.ts +18 -0
- package/dist/scripts/chart_targets.js +48 -0
- package/dist/scripts/dw.js +1 -1
- package/dist/scripts/liquid.d.ts +24 -0
- package/dist/scripts/liquid.js +134 -0
- package/dist/scripts/rich_list.js +12 -16
- package/dist/scripts/test-credit-renewal.js +12 -5
- package/dist/scripts/token_distribution.d.ts +2 -0
- package/dist/scripts/token_distribution.js +132 -108
- package/dist/scripts/tv.js +1 -1
- package/dist/scripts/verify-browser-bundle.js +18 -0
- package/docs/COW_INVARIANTS.md +69 -10
- package/docs/DEXBOT_COMPARISON.md +6 -6
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/GRID_PRICE_INVARIANT.md +5 -2
- package/docs/GRID_RECONCILE.md +36 -11
- package/docs/LOGGING.md +50 -4
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +177 -27
- package/docs/README.md +23 -2
- package/docs/WORKFLOW.md +12 -4
- package/docs/architecture.md +42 -5
- package/docs/developer_guide.md +25 -8
- package/modules/README.md +8 -1
- package/package.json +3 -1
- package/scripts/README.md +39 -7
- package/scripts/pdev.sh +14 -1
- package/scripts/pmain.sh +23 -8
- package/scripts/ptest.sh +7 -0
- package/tests/README.md +30 -1
|
@@ -138,9 +138,10 @@ function batchReadOrdersSeam(mgr, orderIds, timeoutMs) {
|
|
|
138
138
|
const { BitShares } = client;
|
|
139
139
|
import { NATIVE_CLIENT } from '../constants.js';
|
|
140
140
|
const { toFiniteNumber } = Format;
|
|
141
|
-
import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, priceForSlot, priceSlotEqual, pricesOnSameLevel } from './utils/math.js';
|
|
142
|
-
import { parseChainOrder, geometryTypeForSlotIndex, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance, _filterUnmatchedChainOrders } from './utils/order.js';
|
|
141
|
+
import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, resolveGapSlots, priceForSlot, priceSlotEqual, pricesOnSameLevel } from './utils/math.js';
|
|
142
|
+
import { parseChainOrder, geometryTypeForSlotIndex, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance, _filterUnmatchedChainOrders, attributeUnmatchedFillToGrid, reviveVirtualSlotFromChain, resolveExecutionPrice } from './utils/order.js';
|
|
143
143
|
import { parseSlotIndex } from './utils/slot.js';
|
|
144
|
+
import { readSlotLifecycle } from './lifecycle.js';
|
|
144
145
|
import { resolveProcessedFillPersistenceMode } from './processed_fill_store.js';
|
|
145
146
|
import { hasGenesisLadder } from './genesis_policy.js';
|
|
146
147
|
import { getErrorMessage } from '../utils/errors.js';
|
|
@@ -497,6 +498,20 @@ async function adoptChainOrderIntoSlot(mgr, slot, chainOrder, chainOrderId, rawC
|
|
|
497
498
|
matchedGridOrderIds.delete(bestMatch.id);
|
|
498
499
|
return false;
|
|
499
500
|
}
|
|
501
|
+
// ADOPTION IS CHAIN EVIDENCE: a chain order was matched into this slot by
|
|
502
|
+
// this very snapshot, so record it as such. The write funnel can only speak
|
|
503
|
+
// for the LOCAL slot state ('local'); without this the registry would claim a
|
|
504
|
+
// purely local basis for the strongest thing we know about the order, and
|
|
505
|
+
// `observedAt` ("when did the chain last tell us anything") would never
|
|
506
|
+
// advance for adoptions.
|
|
507
|
+
try {
|
|
508
|
+
mgr._lifecycle?.markLanded?.(chainOrderId, {
|
|
509
|
+
slotId: String(bestMatch.id),
|
|
510
|
+
evidence: 'adoption',
|
|
511
|
+
phase: bestMatch.state === ORDER_STATES.PARTIAL ? 'filling' : 'landed',
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
catch { /* lifecycle bookkeeping must never break adoption */ }
|
|
500
515
|
updatedOrders.push(bestMatch);
|
|
501
516
|
chainOrderIdsOnGrid.add(chainOrderId);
|
|
502
517
|
// Adopted means matched: drop any deferred-orphan record so fund counting
|
|
@@ -781,17 +796,30 @@ class SyncEngine {
|
|
|
781
796
|
// This eliminates type confusion - each map has a single, clear purpose
|
|
782
797
|
const parsedChainOrders = new Map();
|
|
783
798
|
const rawChainOrders = new Map();
|
|
799
|
+
// Unparseable chain orders are UNKNOWN, not absent. A live order the
|
|
800
|
+
// node returned but we could not decode must never make its slot look
|
|
801
|
+
// empty: that virtualizes a real order and re-CREATEs on top of it.
|
|
802
|
+
// The id set is threaded into pass 1 so the absence decision can consult
|
|
803
|
+
// it (mirrors the accounting recovery sweep's `malformedOrderIds`).
|
|
804
|
+
const malformedChainOrderIds = new Set();
|
|
784
805
|
for (const order of chainOrders) {
|
|
785
806
|
try {
|
|
786
807
|
const parsed = parseChainOrder(order, mgr.assets);
|
|
787
|
-
if (!parsed)
|
|
808
|
+
if (!parsed) {
|
|
809
|
+
const rawId = order.id;
|
|
810
|
+
if (rawId != null)
|
|
811
|
+
malformedChainOrderIds.add(String(rawId));
|
|
788
812
|
continue;
|
|
813
|
+
}
|
|
789
814
|
// Store parsed (converted) data in parsedChainOrders
|
|
790
815
|
parsedChainOrders.set(order.id, parsed);
|
|
791
816
|
// Store raw blockchain data in separate map - clean separation of concerns
|
|
792
817
|
rawChainOrders.set(order.id, order);
|
|
793
818
|
}
|
|
794
819
|
catch (e) {
|
|
820
|
+
const rawId = order.id;
|
|
821
|
+
if (rawId != null)
|
|
822
|
+
malformedChainOrderIds.add(String(rawId));
|
|
795
823
|
mgr.logger?.log?.(`Warning: Error parsing chain order ${order.id}: ${getErrorMessage(e)}`, 'warn');
|
|
796
824
|
continue;
|
|
797
825
|
}
|
|
@@ -902,7 +930,7 @@ class SyncEngine {
|
|
|
902
930
|
const runReconciliation = async () => {
|
|
903
931
|
mgr.pauseFundRecalc();
|
|
904
932
|
try {
|
|
905
|
-
await this._performSyncFromOpenOrders(mgr, assetAPrecision, assetBPrecision, parsedChainOrders, rawChainOrders, chainOrderIdsOnGrid, matchedGridOrderIds, filledOrders, updatedOrders, ordersNeedingCorrection, unmatchedChainOrders, options);
|
|
933
|
+
await this._performSyncFromOpenOrders(mgr, assetAPrecision, assetBPrecision, parsedChainOrders, rawChainOrders, malformedChainOrderIds, chainOrderIdsOnGrid, matchedGridOrderIds, filledOrders, updatedOrders, ordersNeedingCorrection, unmatchedChainOrders, options);
|
|
906
934
|
}
|
|
907
935
|
finally {
|
|
908
936
|
await mgr.resumeFundRecalc();
|
|
@@ -924,6 +952,7 @@ class SyncEngine {
|
|
|
924
952
|
* @param {number} assetBPrecision - Asset B precision
|
|
925
953
|
* @param {Map<string, any>} parsedChainOrders - Parsed chain orders by ID
|
|
926
954
|
* @param {Map<string, Object>} rawChainOrders - Raw blockchain order objects by ID
|
|
955
|
+
* @param {Set<string>} malformedChainOrderIds - Chain order IDs that were returned but could not be parsed (UNKNOWN, not absent)
|
|
927
956
|
* @param {Set<string>} chainOrderIdsOnGrid - Output set: chain order IDs matched to grid
|
|
928
957
|
* @param {Set<string>} matchedGridOrderIds - Output set: grid order IDs matched to chain
|
|
929
958
|
* @param {Array<Object>} filledOrders - Output array: orders detected as filled
|
|
@@ -933,7 +962,7 @@ class SyncEngine {
|
|
|
933
962
|
* @param {Object} options - Sync options (skipAccounting, etc.)
|
|
934
963
|
* @returns {Promise<any>}
|
|
935
964
|
*/
|
|
936
|
-
async _performSyncFromOpenOrders(mgr, assetAPrecision, assetBPrecision, parsedChainOrders, rawChainOrders, chainOrderIdsOnGrid, matchedGridOrderIds, filledOrders, updatedOrders, ordersNeedingCorrection, unmatchedChainOrders, options) {
|
|
965
|
+
async _performSyncFromOpenOrders(mgr, assetAPrecision, assetBPrecision, parsedChainOrders, rawChainOrders, malformedChainOrderIds, chainOrderIdsOnGrid, matchedGridOrderIds, filledOrders, updatedOrders, ordersNeedingCorrection, unmatchedChainOrders, options) {
|
|
937
966
|
const skipAccounting = (options?.skipAccounting ?? true);
|
|
938
967
|
const queueCorrection = (entry) => {
|
|
939
968
|
// Provenance: classify the detector so a stale replay at drain
|
|
@@ -972,6 +1001,31 @@ class SyncEngine {
|
|
|
972
1001
|
continue;
|
|
973
1002
|
let updatedOrder = { ...gridOrder };
|
|
974
1003
|
chainOrderIdsOnGrid.add(gridOrder.orderId);
|
|
1004
|
+
// A grid order matched against this snapshot IS a chain
|
|
1005
|
+
// observation: record it with the only evidence kind that
|
|
1006
|
+
// advances `observedAt` (when did the chain last tell us).
|
|
1007
|
+
mgr._lifecycle?.markLanded?.(String(gridOrder.orderId), {
|
|
1008
|
+
slotId: String(gridOrder.id),
|
|
1009
|
+
evidence: 'chain-snapshot',
|
|
1010
|
+
phase: gridOrder.state === ORDER_STATES.PARTIAL ? 'filling' : 'landed',
|
|
1011
|
+
});
|
|
1012
|
+
// REVIVE BEFORE ANYTHING ELSE: this slot is not placed but its
|
|
1013
|
+
// chain order is still live. Leaving it VIRTUAL is the "dark
|
|
1014
|
+
// level" state — invisible to window accounting
|
|
1015
|
+
// (_countActiveOnGrid needs ACTIVE/PARTIAL) while its order is
|
|
1016
|
+
// still counted in chainCount, so the reconcile reads a
|
|
1017
|
+
// shortfall it can never repair and the planner sees a free
|
|
1018
|
+
// level that already holds an order. The revive is master-only
|
|
1019
|
+
// (no broadcast) and refuses when the chain order does not rest
|
|
1020
|
+
// at this slot's level, so a rotation source whose cancel has
|
|
1021
|
+
// not landed is NOT resurrected.
|
|
1022
|
+
if (!isOrderPlaced(gridOrder)) {
|
|
1023
|
+
const revived = await reviveVirtualSlotFromChain(mgr, gridOrder, chainOrder, rawChainOrders.get(gridOrder.orderId), 'sync-pass1-revive', { skipAccounting });
|
|
1024
|
+
if (revived) {
|
|
1025
|
+
updatedOrders.push(revived);
|
|
1026
|
+
continue;
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
975
1029
|
// Store raw blockchain data in grid slot for later update calculation.
|
|
976
1030
|
// Tag the snapshot with `fetchedAt` so the drift check in
|
|
977
1031
|
// syncFromFillHistory can distinguish a fresh chain read from a
|
|
@@ -1166,6 +1220,19 @@ class SyncEngine {
|
|
|
1166
1220
|
// divergence re-detects on the next sync.
|
|
1167
1221
|
mgr.logger?.log?.(`[SYNC] Partial-size update for ${gridOrder.id} rejected — slot keeps booked size ${gridOrder.size}`, 'warn');
|
|
1168
1222
|
}
|
|
1223
|
+
else if (chainSizeInt < currentSizeInt && gridOrder.orderId) {
|
|
1224
|
+
// Mark the fill's size/fund delta as already absorbed:
|
|
1225
|
+
// the fill-history batch that follows must not shrink
|
|
1226
|
+
// (or credit) it a second time.
|
|
1227
|
+
mgr.noteChainSizeAppliedFill?.(String(gridOrder.orderId), currentSizeInt - chainSizeInt);
|
|
1228
|
+
// The marker is persisted with the grid snapshot
|
|
1229
|
+
// (debugInputs). Force the snapshot dirty AFTER
|
|
1230
|
+
// recording it: a flush already queued by
|
|
1231
|
+
// _applyOrderUpdate may have captured the grid
|
|
1232
|
+
// without the marker, and a crash in that window
|
|
1233
|
+
// would replay the fill as a second shrink.
|
|
1234
|
+
mgr._markGridDirty?.();
|
|
1235
|
+
}
|
|
1169
1236
|
}
|
|
1170
1237
|
else {
|
|
1171
1238
|
const spreadOrder = convertToSpreadPlaceholder(gridOrder);
|
|
@@ -1187,50 +1254,83 @@ class SyncEngine {
|
|
|
1187
1254
|
}
|
|
1188
1255
|
}
|
|
1189
1256
|
}
|
|
1190
|
-
else if (gridOrder.state === ORDER_STATES.ACTIVE || gridOrder.state === ORDER_STATES.PARTIAL) {
|
|
1257
|
+
else if (gridOrder.state === ORDER_STATES.ACTIVE || gridOrder.state === ORDER_STATES.PARTIAL || hasOnChainId(gridOrder)) {
|
|
1258
|
+
// Also entered for a NON-placed slot that still carries an
|
|
1259
|
+
// orderId (virtualised while its order was live). Two outcomes
|
|
1260
|
+
// below, decided by `wasPlaced`:
|
|
1261
|
+
// * placed + absent -> a real fill/phantom (booked as before),
|
|
1262
|
+
// * virtual + absent -> the id is simply STALE: clear it so the
|
|
1263
|
+
// level becomes a normal hole again. Without this a stale id
|
|
1264
|
+
// would keep the slot looking occupied forever (blocking the
|
|
1265
|
+
// CREATE that the level needs) and would keep masking a
|
|
1266
|
+
// genuine fill on the other side.
|
|
1191
1267
|
// Don't virtualize orders placed by a successful COW commit.
|
|
1192
1268
|
// The chain snapshot may lag behind confirmed transactions,
|
|
1193
|
-
// causing correctly-placed orders to appear missing.
|
|
1194
|
-
// is
|
|
1269
|
+
// causing correctly-placed orders to appear missing. The committed
|
|
1270
|
+
// snapshot is published by every successful COW commit
|
|
1195
1271
|
// (manager.ts:_commitWorkingGrid) and is always active for all sync
|
|
1196
|
-
// paths.
|
|
1197
|
-
//
|
|
1198
|
-
// finalMap, so their IDs drop out on the next atomic rebuild.
|
|
1199
|
-
//
|
|
1200
|
-
// SAFETY: _committedOrderIds is replaced atomically (reference swap)
|
|
1201
|
-
// by _commitWorkingGrid. The sync reads has(gridOrder.orderId) against the
|
|
1202
|
-
// current reference. If a concurrent COW commit replaces the set mid-sync,
|
|
1203
|
-
// the new set is a superset (only adds entries for newly committed orders).
|
|
1204
|
-
// An order in the superset was just committed, so it is genuinely on-chain
|
|
1205
|
-
// and should not be virtualized. An order removed from the old set was
|
|
1206
|
-
// filled/virtualized, which the sync will detect independently via the
|
|
1207
|
-
// chain snapshot. Superset behavior is safe for this guard.
|
|
1272
|
+
// paths. Filled/virtualized orders are absent from the next commit's
|
|
1273
|
+
// finalMap, so their IDs drop out on the next atomic publish.
|
|
1208
1274
|
//
|
|
1209
1275
|
// ESCAPE HATCH 1 — Ghost orders (PARTIAL + size=0): These preserve the
|
|
1210
1276
|
// original orderId only to block duplicate CREATEs after a full fill
|
|
1211
|
-
// that the chain hasn't closed yet. The orderId is in
|
|
1212
|
-
// because the original order was COW-placed, but the slot is
|
|
1213
|
-
// known fill. Allow phantom detection to proceed so the ghost
|
|
1214
|
-
// up on the next sync cycle after the chain cancel succeeds.
|
|
1277
|
+
// that the chain hasn't closed yet. The orderId is in the committed
|
|
1278
|
+
// snapshot because the original order was COW-placed, but the slot is
|
|
1279
|
+
// already a known fill. Allow phantom detection to proceed so the ghost
|
|
1280
|
+
// is cleaned up on the next sync cycle after the chain cancel succeeds.
|
|
1281
|
+
//
|
|
1282
|
+
// ESCAPE HATCH 2 — Time-based: the lifecycle in-flight window is
|
|
1283
|
+
// bounded (2× the pending-broadcast TTL), so a permanently lagging
|
|
1284
|
+
// node cannot park cleanup forever; past it the committed-but-missing
|
|
1285
|
+
// order is presumed genuinely filled. This is what keeps a missed fill
|
|
1286
|
+
// event (reconnect gap, lossy subscription) from stalling the grid.
|
|
1215
1287
|
//
|
|
1216
|
-
//
|
|
1217
|
-
//
|
|
1218
|
-
//
|
|
1219
|
-
//
|
|
1220
|
-
//
|
|
1221
|
-
//
|
|
1222
|
-
//
|
|
1223
|
-
|
|
1224
|
-
|
|
1288
|
+
// ONE GUARD: the absence decision asks `isInFlight()` — the single
|
|
1289
|
+
// definition of "absence is not trustworthy yet". This site used to
|
|
1290
|
+
// consult the committed window and the fresh-assignment window
|
|
1291
|
+
// separately, while the startup reconcile and the fund recalibration
|
|
1292
|
+
// sweep asked `isInFlight()`: same order, three different answers for
|
|
1293
|
+
// the `unknown`/`broadcasting` phases (an abandoned CREATE receipt, an
|
|
1294
|
+
// unreadable chain entry). Those phases are exactly what the guard is
|
|
1295
|
+
// for, so reading a subset here re-opened the bug class it exists to
|
|
1296
|
+
// close.
|
|
1297
|
+
if (gridOrder.orderId != null) {
|
|
1298
|
+
const slotLifecycle = readSlotLifecycle(mgr, gridOrder);
|
|
1225
1299
|
const isGhost = gridOrder.size <= 0 && gridOrder.state === ORDER_STATES.PARTIAL;
|
|
1226
|
-
|
|
1300
|
+
// Guard 0: the order was returned but could not be decoded.
|
|
1301
|
+
// Absence is UNKNOWN — keep the id and let a later, readable
|
|
1302
|
+
// snapshot decide. Reading an unparseable entry as absent
|
|
1303
|
+
// virtualizes a live order and duplicates it on re-create.
|
|
1304
|
+
if (malformedChainOrderIds.has(String(gridOrder.orderId))) {
|
|
1305
|
+
mgr._lifecycle?.markUnknown?.(String(gridOrder.orderId), {
|
|
1306
|
+
slotId: String(gridOrder.id),
|
|
1307
|
+
evidence: 'chain-snapshot',
|
|
1308
|
+
});
|
|
1309
|
+
mgr.logger?.log?.(`[SYNC] ${gridOrder.id}: chain order ${gridOrder.orderId} is present but unparseable — ` +
|
|
1310
|
+
`absence is UNKNOWN (not virtualizing)`, 'warn');
|
|
1311
|
+
continue;
|
|
1312
|
+
}
|
|
1313
|
+
// Ghosts are known fills: they must pass so the cleanup runs.
|
|
1314
|
+
if (!isGhost && slotLifecycle.isInFlight()) {
|
|
1315
|
+
if (gridOrder.state === ORDER_STATES.ACTIVE || gridOrder.state === ORDER_STATES.PARTIAL) {
|
|
1316
|
+
mgr.logger?.log?.(`[SYNC] ${gridOrder.id}: chain order ${gridOrder.orderId} is absent from the snapshot but ` +
|
|
1317
|
+
`${slotLifecycle.isUnresolved
|
|
1318
|
+
? 'its lifecycle phase is unresolved'
|
|
1319
|
+
: 'it was assigned/committed recently'} — absence not yet trustworthy`, 'debug');
|
|
1320
|
+
}
|
|
1321
|
+
else {
|
|
1322
|
+
mgr.logger?.log?.(`[SYNC] Stale-id check for ${gridOrder.id} deferred: chain id ${gridOrder.orderId} was ` +
|
|
1323
|
+
`assigned recently and is not in the snapshot — absence not yet trustworthy`, 'debug');
|
|
1324
|
+
}
|
|
1227
1325
|
continue;
|
|
1228
1326
|
}
|
|
1229
1327
|
}
|
|
1230
1328
|
const currentGridOrder = mgr.orders.get(gridOrder.id) || gridOrder;
|
|
1231
1329
|
const hadOrderId = Boolean(currentGridOrder?.orderId);
|
|
1330
|
+
const wasPlaced = isOrderPlaced(currentGridOrder);
|
|
1232
1331
|
const spreadOrder = convertToSpreadPlaceholder(currentGridOrder);
|
|
1233
|
-
const
|
|
1332
|
+
const cleanupContext = wasPlaced ? 'sync-cleanup-phantom' : 'sync-clear-stale-id';
|
|
1333
|
+
const phantomApplied = await mgr._applyOrderUpdate(spreadOrder, cleanupContext, { skipAccounting: skipAccounting, fee: 0 });
|
|
1234
1334
|
if (phantomApplied === false) {
|
|
1235
1335
|
// Rejected virtualization books no phantom fill: the slot
|
|
1236
1336
|
// keeps its order and the disappearance re-detects next
|
|
@@ -1238,8 +1338,12 @@ class SyncEngine {
|
|
|
1238
1338
|
mgr.logger?.log?.(`[SYNC] Phantom cleanup for ${gridOrder.id} rejected — fill NOT booked`, 'warn');
|
|
1239
1339
|
continue;
|
|
1240
1340
|
}
|
|
1241
|
-
// Only genuine disappearances
|
|
1242
|
-
|
|
1341
|
+
// Only genuine disappearances of a PLACED order count as fills.
|
|
1342
|
+
// A virtualised slot's stale id is cleared above without booking
|
|
1343
|
+
// anything: the funds for that level were already settled when
|
|
1344
|
+
// the slot was virtualised, and inventing a fill here would arm
|
|
1345
|
+
// the pivot and crawl for a trade that never happened.
|
|
1346
|
+
if (hadOrderId && wasPlaced) {
|
|
1243
1347
|
// A SPREAD slot can carry an on-chain order (spread-correction
|
|
1244
1348
|
// activation). Resolve the real side before pushing: the fill
|
|
1245
1349
|
// drives deriveTargetBoundary, which only shifts on BUY/SELL —
|
|
@@ -1273,6 +1377,12 @@ class SyncEngine {
|
|
|
1273
1377
|
...(liveChainPrice != null ? { price: liveChainPrice } : {})
|
|
1274
1378
|
});
|
|
1275
1379
|
}
|
|
1380
|
+
else if (hadOrderId) {
|
|
1381
|
+
updatedOrders.push(spreadOrder);
|
|
1382
|
+
mgr.logger?.log?.(`[SYNC] Cleared stale chain id ${currentGridOrder?.orderId ?? ''} on ${gridOrder.id} ` +
|
|
1383
|
+
`(slot was ${currentGridOrder?.state ?? ORDER_STATES.VIRTUAL}): the order is gone from the ` +
|
|
1384
|
+
`chain read, so the level is a normal hole again — no fill booked`, 'debug');
|
|
1385
|
+
}
|
|
1276
1386
|
}
|
|
1277
1387
|
}
|
|
1278
1388
|
// ====================================================================
|
|
@@ -1335,7 +1445,11 @@ class SyncEngine {
|
|
|
1335
1445
|
continue;
|
|
1336
1446
|
}
|
|
1337
1447
|
}
|
|
1338
|
-
|
|
1448
|
+
// Unknown geometry must NOT read as gap 0 (a 0-wide band turns the
|
|
1449
|
+
// slot just above the boundary into a SELL rail slot, so an in-band
|
|
1450
|
+
// orphan could be adopted onto the wrong rail). resolveGapSlots is
|
|
1451
|
+
// the single source of truth (_gapSlots ?? config-derived).
|
|
1452
|
+
const gapSlots = genesis?.gapSlots ?? resolveGapSlots(mgr);
|
|
1339
1453
|
const boundaryIdx = mgr.boundaryIdx;
|
|
1340
1454
|
// Pre-boundary sync: gap geometry is unknown, so adoption is
|
|
1341
1455
|
// deferred entirely — touch nothing (no adopt, no cancelOnly).
|
|
@@ -1407,6 +1521,28 @@ class SyncEngine {
|
|
|
1407
1521
|
}
|
|
1408
1522
|
return null;
|
|
1409
1523
|
}
|
|
1524
|
+
/**
|
|
1525
|
+
* Absorb a fill whose order id has no ACTIVE/PARTIAL slot ("order not found
|
|
1526
|
+
* in active grid").
|
|
1527
|
+
*
|
|
1528
|
+
* Thin wrapper over the shared `attributeUnmatchedFillToGrid` helper (see
|
|
1529
|
+
* utils/order.ts for the two identities and the incident it closes). The
|
|
1530
|
+
* work lives outside this class so the orphan-credit path in
|
|
1531
|
+
* dexbot_fill_runtime.ts attributes fills with literally the same rule
|
|
1532
|
+
* instead of keeping a second, weaker copy.
|
|
1533
|
+
*
|
|
1534
|
+
* @returns {boolean} true when the fill was attributed to the grid.
|
|
1535
|
+
*/
|
|
1536
|
+
_absorbUnmatchedFill(mgr, params) {
|
|
1537
|
+
return attributeUnmatchedFillToGrid(mgr, {
|
|
1538
|
+
orderId: params?.orderId ?? null,
|
|
1539
|
+
paysAssetId: params?.paysAssetId ?? null,
|
|
1540
|
+
paysAmountRaw: params?.paysAmountRaw == null ? null : Number(params.paysAmountRaw),
|
|
1541
|
+
receivesAssetId: params?.receivesAssetId ?? null,
|
|
1542
|
+
receivesAmountRaw: params?.receivesAmountRaw == null ? null : Number(params.receivesAmountRaw),
|
|
1543
|
+
isPartial: params?.isPartial === true,
|
|
1544
|
+
});
|
|
1545
|
+
}
|
|
1410
1546
|
_computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw, receivesAssetId = null, receivesAmountRaw = null) {
|
|
1411
1547
|
const assets = mgr.assets;
|
|
1412
1548
|
if (!assets?.assetA || !assets?.assetB)
|
|
@@ -1445,32 +1581,9 @@ class SyncEngine {
|
|
|
1445
1581
|
// Execution price from the actual paid/received amounts (quote per
|
|
1446
1582
|
// base). This is the fill FACT the last-fill pivot and the re-anchor
|
|
1447
1583
|
// need; the slot price is only a grid identity and may be stale after
|
|
1448
|
-
// a refused-commit chain adoption.
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
&& Number.isFinite(Number(paysAmountRaw)) && Number(paysAmountRaw) > 0) {
|
|
1452
|
-
const A = assets.assetA;
|
|
1453
|
-
const B = assets.assetB;
|
|
1454
|
-
let baseRaw = null;
|
|
1455
|
-
let quoteRaw = null;
|
|
1456
|
-
if (paysAssetId === A.id && receivesAssetId === B.id) {
|
|
1457
|
-
baseRaw = Number(paysAmountRaw);
|
|
1458
|
-
quoteRaw = Number(receivesAmountRaw);
|
|
1459
|
-
}
|
|
1460
|
-
else if (paysAssetId === B.id && receivesAssetId === A.id) {
|
|
1461
|
-
baseRaw = Number(receivesAmountRaw);
|
|
1462
|
-
quoteRaw = Number(paysAmountRaw);
|
|
1463
|
-
}
|
|
1464
|
-
if (baseRaw !== null && quoteRaw !== null) {
|
|
1465
|
-
const base = blockchainToFloat(baseRaw, A.precision);
|
|
1466
|
-
const quote = blockchainToFloat(quoteRaw, B.precision);
|
|
1467
|
-
if (base > 0 && quote > 0) {
|
|
1468
|
-
const price = quote / base;
|
|
1469
|
-
if (Number.isFinite(price) && price > 0)
|
|
1470
|
-
fillPrice = price;
|
|
1471
|
-
}
|
|
1472
|
-
}
|
|
1473
|
-
}
|
|
1584
|
+
// a refused-commit chain adoption. Shared with the unmatched-fill
|
|
1585
|
+
// attribution so both resolve a price identically.
|
|
1586
|
+
const fillPrice = resolveExecutionPrice(assets, paysAssetId, paysAmountRaw, receivesAssetId, receivesAmountRaw);
|
|
1474
1587
|
return { orderType, currentSize, precision, filledAmount, currentSizeIntFromGrid, rawForSaleInt, driftSignal, fillPrice };
|
|
1475
1588
|
}
|
|
1476
1589
|
async _computeFillTransitionResult(mgr, params) {
|
|
@@ -1487,7 +1600,26 @@ class SyncEngine {
|
|
|
1487
1600
|
const currentSizeInt = Number.isFinite(effectiveRawForSale)
|
|
1488
1601
|
? Math.max(0, Math.round(effectiveRawForSale))
|
|
1489
1602
|
: currentSizeIntFromGrid;
|
|
1490
|
-
|
|
1603
|
+
// `rawOnChain.for_sale` may already include the part of this fill that
|
|
1604
|
+
// sync pass 1 absorbed. Subtract only the NOT-yet-applied remainder;
|
|
1605
|
+
// subtracting the whole fill (or none of it) is the double-shrink /
|
|
1606
|
+
// growth pair from the 2026-11-03 incident. Both forms are supported:
|
|
1607
|
+
// the explicit applied amount (partial coverage) and the legacy boolean.
|
|
1608
|
+
const explicitApplied = Number.isFinite(Number(params.alreadyAppliedInt))
|
|
1609
|
+
? Math.round(Number(params.alreadyAppliedInt))
|
|
1610
|
+
: 0;
|
|
1611
|
+
// The legacy boolean is a FALLBACK, never a floor: it carries no amount,
|
|
1612
|
+
// so it can only speak for the whole fill. It is honoured ONLY when the
|
|
1613
|
+
// caller supplied no explicit applied amount — otherwise a group in
|
|
1614
|
+
// which ONE entry was marked would skip the unapplied remainder of its
|
|
1615
|
+
// siblings (the aggregated batch path reads the flag off the last entry
|
|
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)));
|
|
1621
|
+
const remainingFillInt = Math.max(0, filledAmountInt - appliedInt);
|
|
1622
|
+
const newSizeInt = Math.max(0, currentSizeInt - remainingFillInt);
|
|
1491
1623
|
const newSize = blockchainToFloat(newSizeInt, precision);
|
|
1492
1624
|
if (Number.isFinite(effectiveRawForSale) && currentSizeInt !== currentSizeIntFromGrid) {
|
|
1493
1625
|
mgr.logger.log(`[SYNC] Using rawOnChain.for_sale baseline for ${matchedGridOrder.orderId}: raw=${currentSizeInt}, grid=${currentSizeIntFromGrid}` +
|
|
@@ -1564,6 +1696,18 @@ class SyncEngine {
|
|
|
1564
1696
|
}
|
|
1565
1697
|
}
|
|
1566
1698
|
}
|
|
1699
|
+
// ZERO-REMAINDER BRAKE: a fill that leaves nothing tradeable must never
|
|
1700
|
+
// produce a 0-size PARTIAL slot (invalid order state), even when the
|
|
1701
|
+
// quote-side rounding test above could not decide (a corrupt/zero slot
|
|
1702
|
+
// price makes `otherSize` non-finite, so `<= 0` is false). Deliberately
|
|
1703
|
+
// placed AFTER the residual verification: taking this brake earlier
|
|
1704
|
+
// skipped the explicit cancel of a real chain residual — the exact
|
|
1705
|
+
// stranding path `cancelResidualOrders` exists for.
|
|
1706
|
+
if (!isEffectivelyFull && newSizeInt <= 0) {
|
|
1707
|
+
isEffectivelyFull = true;
|
|
1708
|
+
mgr.logger.log(`[SYNC] Order ${matchedGridOrder.orderId} (slot ${matchedGridOrder.id}) leaves no tradeable remainder ` +
|
|
1709
|
+
`(filled=${filledAmountInt} baseline=${currentSizeInt} applied=${appliedInt}); treating as a full fill.`, 'debug');
|
|
1710
|
+
}
|
|
1567
1711
|
let fullUpdate;
|
|
1568
1712
|
let partialUpdate;
|
|
1569
1713
|
let filledOrderResult;
|
|
@@ -1592,10 +1736,10 @@ class SyncEngine {
|
|
|
1592
1736
|
const { btsFeeState, ...matchedWithoutDeferredFee } = matchedGridOrder;
|
|
1593
1737
|
let updatedOrder = { ...matchedWithoutDeferredFee, type: orderType, state: ORDER_STATES.PARTIAL };
|
|
1594
1738
|
if (updatedOrder.rawOnChain && updatedOrder.rawOnChain.for_sale !== undefined) {
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
const nextForSaleInt =
|
|
1739
|
+
// The snapshot's for_sale is the authoritative remaining size
|
|
1740
|
+
// after the not-yet-applied portion was subtracted above; it is
|
|
1741
|
+
// never decremented a second time.
|
|
1742
|
+
const nextForSaleInt = newSizeInt;
|
|
1599
1743
|
updatedOrder.rawOnChain = {
|
|
1600
1744
|
...updatedOrder.rawOnChain,
|
|
1601
1745
|
for_sale: String(nextForSaleInt),
|
|
@@ -1682,7 +1826,16 @@ class SyncEngine {
|
|
|
1682
1826
|
}
|
|
1683
1827
|
const matchedGridOrder = this._findMatchingGridOrder(mgr, orderId);
|
|
1684
1828
|
if (!matchedGridOrder) {
|
|
1685
|
-
|
|
1829
|
+
// An order that filled while its slot was already virtualised
|
|
1830
|
+
// still proves a trade: absorb the pivot + owed crawl from the
|
|
1831
|
+
// real execution price instead of dropping it (see
|
|
1832
|
+
// _absorbUnmatchedFill). Only a truly unknown order is ignored.
|
|
1833
|
+
const absorbed = this._absorbUnmatchedFill(mgr, {
|
|
1834
|
+
orderId, paysAssetId, paysAmountRaw, receivesAssetId, receivesAmountRaw,
|
|
1835
|
+
});
|
|
1836
|
+
if (!absorbed) {
|
|
1837
|
+
mgr.logger.log(`[SYNC] Fill for order ${orderId} ignored: order not found in active grid.`, 'debug');
|
|
1838
|
+
}
|
|
1686
1839
|
return { filledOrders: [], updatedOrders: [], partialFill: false };
|
|
1687
1840
|
}
|
|
1688
1841
|
const ctx = this._computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw, receivesAssetId, receivesAmountRaw);
|
|
@@ -1725,7 +1878,9 @@ class SyncEngine {
|
|
|
1725
1878
|
blockNum,
|
|
1726
1879
|
historyId,
|
|
1727
1880
|
isMaker,
|
|
1728
|
-
fillPrice: ctx.fillPrice
|
|
1881
|
+
fillPrice: ctx.fillPrice,
|
|
1882
|
+
alreadyAppliedInt: Math.max(0, Math.round(Number(fillOp.__chainSizeAppliedInt) || 0)),
|
|
1883
|
+
alreadyAppliedChainSize: Boolean(fillOp.__chainSizeAlreadyApplied)
|
|
1729
1884
|
});
|
|
1730
1885
|
const filledOrders = [];
|
|
1731
1886
|
const updatedOrders = [];
|
|
@@ -1881,7 +2036,16 @@ class SyncEngine {
|
|
|
1881
2036
|
const { orderId, paysAmountRaw, paysAssetId } = entry;
|
|
1882
2037
|
const matchedGridOrder = this._findMatchingGridOrder(mgr, orderId);
|
|
1883
2038
|
if (!matchedGridOrder) {
|
|
1884
|
-
|
|
2039
|
+
// Same absorption as the single-fill path: keep the
|
|
2040
|
+
// pivot/crawl ledger honest so the next derivation and the
|
|
2041
|
+
// LAST-FILL-GUARD see the price that actually traded.
|
|
2042
|
+
const absorbed = this._absorbUnmatchedFill(mgr, {
|
|
2043
|
+
orderId, paysAssetId, paysAmountRaw,
|
|
2044
|
+
receivesAssetId: entry.receivesAssetId, receivesAmountRaw: entry.receivesAmountRaw,
|
|
2045
|
+
});
|
|
2046
|
+
if (!absorbed) {
|
|
2047
|
+
mgr.logger.log(`[SYNC] Fill for order ${orderId} ignored: order not found in active grid.`, 'debug');
|
|
2048
|
+
}
|
|
1885
2049
|
anyRequiresSync = true;
|
|
1886
2050
|
continue;
|
|
1887
2051
|
}
|
|
@@ -1976,8 +2140,10 @@ class SyncEngine {
|
|
|
1976
2140
|
// Sum the integer filled amounts across this order's fills so
|
|
1977
2141
|
// the single transition reflects the total consumption.
|
|
1978
2142
|
let totalFilledAmountInt = 0;
|
|
2143
|
+
let totalAppliedInt = 0;
|
|
1979
2144
|
for (const ctx of group) {
|
|
1980
2145
|
totalFilledAmountInt += ctx.filledAmountInt;
|
|
2146
|
+
totalAppliedInt += Math.max(0, Math.round(Number(ctx.entry.fillOp.__chainSizeAppliedInt) || 0));
|
|
1981
2147
|
}
|
|
1982
2148
|
const totalFilledAmount = blockchainToFloat(totalFilledAmountInt, precision);
|
|
1983
2149
|
if (group.length > 1) {
|
|
@@ -2001,7 +2167,9 @@ class SyncEngine {
|
|
|
2001
2167
|
blockNum: lastCtx.entry.blockNum,
|
|
2002
2168
|
historyId: lastCtx.entry.historyId,
|
|
2003
2169
|
isMaker: lastCtx.entry.isMaker,
|
|
2004
|
-
fillPrice: lastCtx.fillPrice
|
|
2170
|
+
fillPrice: lastCtx.fillPrice,
|
|
2171
|
+
alreadyAppliedInt: Math.min(totalFilledAmountInt, Math.max(0, totalAppliedInt)),
|
|
2172
|
+
alreadyAppliedChainSize: Boolean(lastCtx.entry.fillOp.__chainSizeAlreadyApplied)
|
|
2005
2173
|
});
|
|
2006
2174
|
if (result.isFull) {
|
|
2007
2175
|
mgr.logger.log(`[SYNC] Full fill for order ${orderId} (slot ${matchedGridOrder.id}).`, 'info');
|
|
@@ -1026,6 +1026,7 @@ declare function validateBoundaryCommit(proposedBoundary: number | null | undefi
|
|
|
1026
1026
|
ok: boolean;
|
|
1027
1027
|
reason?: string;
|
|
1028
1028
|
detail?: string;
|
|
1029
|
+
inBandCount?: number;
|
|
1029
1030
|
};
|
|
1030
1031
|
/**
|
|
1031
1032
|
* Validate a boundary restored from PERSISTED state (disk snapshot) before it
|
|
@@ -1061,7 +1062,27 @@ declare function validatePersistedBoundary(proposedBoundary: number | null | und
|
|
|
1061
1062
|
ok: boolean;
|
|
1062
1063
|
reason?: string;
|
|
1063
1064
|
detail?: string;
|
|
1065
|
+
inBandCount?: number;
|
|
1064
1066
|
};
|
|
1067
|
+
/**
|
|
1068
|
+
* Whether moving a boundary from `current` to `candidate` strands FEWER placed
|
|
1069
|
+
* orders (a violation-reducing repair). Strictly fewer — an equal count is not
|
|
1070
|
+
* a repair, and a structural refusal on either side is never a repair.
|
|
1071
|
+
*
|
|
1072
|
+
* This is the one rule behind the fill re-anchor and the rail clamp accepting a
|
|
1073
|
+
* move the strict validator would refuse only for transient stranding; both
|
|
1074
|
+
* bounds stay in force (fill-anchor direction at the caller, strand count here).
|
|
1075
|
+
*
|
|
1076
|
+
* @param currentBoundary - Boundary currently committed
|
|
1077
|
+
* @param candidateBoundary - Proposed boundary
|
|
1078
|
+
* @param orders - Placed-order slots
|
|
1079
|
+
* @param gapSlots - Gap band width
|
|
1080
|
+
* @param options - Optional in-band allow-list (a fill's own partial residual)
|
|
1081
|
+
* @returns True when the candidate strands strictly fewer placed orders
|
|
1082
|
+
*/
|
|
1083
|
+
declare function boundaryMoveReducesStrands(currentBoundary: number | null | undefined, candidateBoundary: number | null | undefined, orders: Iterable<unknown>, gapSlots: number, options?: {
|
|
1084
|
+
allowInBandSlotIds?: Iterable<string>;
|
|
1085
|
+
}): boolean;
|
|
1065
1086
|
/**
|
|
1066
1087
|
* Whether a persisted-boundary rejection is the TRANSIENT kind that must not
|
|
1067
1088
|
* trigger a rebuild: stranding (`placed_order_in_band`) with no accompanying
|
|
@@ -1253,9 +1274,26 @@ declare function priceSlotEqual(a: number, b: number, precision: number): boolea
|
|
|
1253
1274
|
* one that prevents non-termination, which no caller could recover from.
|
|
1254
1275
|
*/
|
|
1255
1276
|
declare function derivePriceLevels(startPrice: number, minPrice: number, maxPrice: number, incrementPercent: number): number[];
|
|
1277
|
+
/**
|
|
1278
|
+
* True when two prices are the SAME grid step: within half an increment of
|
|
1279
|
+
* each other. Used to judge a placement against the price that just traded —
|
|
1280
|
+
* a fill's execution price and the slot level it filled at differ by rounding
|
|
1281
|
+
* (live: slot 1310.046339 filled at 1310.060435, i.e. ~1e-5), so a raw
|
|
1282
|
+
* `>=`/`<=` comparison lets a same-level re-place through.
|
|
1283
|
+
*
|
|
1284
|
+
* The half-step cap mirrors `pricesOnSameLevel`: it can never merge two
|
|
1285
|
+
* legitimately adjacent levels (a full increment apart). A missing/invalid
|
|
1286
|
+
* increment degrades to exact equality.
|
|
1287
|
+
*
|
|
1288
|
+
* @param {number} priceA - First price
|
|
1289
|
+
* @param {number} priceB - Second price
|
|
1290
|
+
* @param {number} incrementPercent - Grid step in percent (e.g. 0.3)
|
|
1291
|
+
* @returns {boolean} True when both prices sit on the same grid step
|
|
1292
|
+
*/
|
|
1293
|
+
declare function pricesWithinHalfStep(priceA: number, priceB: number, incrementPercent: number | null | undefined): boolean;
|
|
1256
1294
|
declare function buildGenesisFromPriceLevels(startPrice: number, incrementPercent: number, gapSlots: number, priceLevels: number[]): GridGenesis;
|
|
1257
1295
|
export type { FeeCacheEntry };
|
|
1258
|
-
export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
|
|
1296
|
+
export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, boundaryMoveReducesStrands, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, pricesWithinHalfStep, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
|
|
1259
1297
|
/**
|
|
1260
1298
|
* Round a value to a given factor.
|
|
1261
1299
|
* @param {number} value - Value to round
|