dexbot 1.6.16 → 1.6.18
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 +58 -0
- package/analysis/README.md +10 -9
- package/analysis/ama_fitting/README.md +2 -2
- package/analysis/bot_fitting/README.md +3 -3
- package/analysis/tradingview/README.md +2 -2
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
- 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/ama_fitting/analyze_lambda_vs_slow.js +5 -3
- package/dist/analysis/analyze_args.d.ts +2 -1
- package/dist/analysis/fills_source.d.ts +1 -8
- package/dist/analysis/fills_source.js +1 -1
- package/dist/analysis/grid_correction_check.d.ts +9 -6
- package/dist/analysis/grid_correction_check.js +56 -64
- package/dist/analysis/math_utils.d.ts +1 -1
- package/dist/analysis/trade_profitability.d.ts +1 -1
- package/dist/analysis/tradingview/grid_reset_sim.js +1 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +7 -7
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
- package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
- package/dist/market_adapter/cli_args.d.ts +6 -1
- package/dist/market_adapter/cli_args.js +16 -2
- package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
- package/dist/market_adapter/core/kibana_candles.js +3 -1
- package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
- package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
- package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
- package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
- package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
- package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
- package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
- package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
- package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
- package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
- package/dist/market_adapter/inputs/window_cache.js +14 -1
- package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
- package/dist/market_adapter/lp_chart_runner.js +3 -1
- package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
- package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
- package/dist/market_adapter/market_adapter.d.ts +10 -2
- package/dist/market_adapter/market_adapter.js +10 -11
- package/dist/market_adapter/utils/chain.d.ts +2 -3
- package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
- package/dist/market_adapter/utils/file_json_cache.js +3 -1
- package/dist/market_adapter/utils/file_lock.js +1 -1
- package/dist/market_adapter/utils/native_history.d.ts +7 -3
- package/dist/market_adapter/utils/native_history.js +3 -1
- package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
- package/dist/modules/account_bots.d.ts +3 -0
- package/dist/modules/bots_file_lock.d.ts +2 -2
- package/dist/modules/bots_file_lock.js +2 -2
- package/dist/modules/chain_keys.d.ts +1 -1
- package/dist/modules/constants.d.ts +6 -0
- package/dist/modules/constants.js +37 -6
- package/dist/modules/credit_pricing.d.ts +20 -1
- package/dist/modules/credit_pricing.js +23 -1
- package/dist/modules/credit_runtime.js +33 -16
- package/dist/modules/dexbot_class.d.ts +11 -1
- package/dist/modules/dexbot_class.js +15 -2
- package/dist/modules/dexbot_cow_runtime.d.ts +90 -38
- package/dist/modules/dexbot_cow_runtime.js +507 -108
- package/dist/modules/dexbot_credential_client.d.ts +5 -0
- package/dist/modules/dexbot_maintenance_runtime.js +117 -12
- package/dist/modules/dexbot_startup_runtime.js +7 -1
- package/dist/modules/graceful_shutdown.d.ts +2 -2
- package/dist/modules/graceful_shutdown.js +2 -2
- package/dist/modules/launcher/credential_daemon.d.ts +14 -2
- package/dist/modules/launcher/credential_daemon.js +60 -26
- package/dist/modules/launcher/runtime_mode.d.ts +4 -3
- package/dist/modules/node_manager.d.ts +1 -1
- package/dist/modules/node_manager.js +1 -1
- package/dist/modules/order/accounting.js +2 -1
- package/dist/modules/order/export.d.ts +2 -2
- package/dist/modules/order/export.js +2 -2
- package/dist/modules/order/grid.d.ts +26 -14
- package/dist/modules/order/grid.js +416 -73
- package/dist/modules/order/grid_reconcile.js +5 -1
- package/dist/modules/order/grid_reconcile_internal.js +2 -1
- package/dist/modules/order/index.d.ts +22 -1
- package/dist/modules/order/manager.d.ts +40 -7
- package/dist/modules/order/manager.js +149 -23
- package/dist/modules/order/strategy.d.ts +5 -0
- package/dist/modules/order/strategy.js +44 -3
- package/dist/modules/order/sync_engine.d.ts +12 -1
- package/dist/modules/order/sync_engine.js +135 -20
- package/dist/modules/order/utils/math.d.ts +49 -10
- package/dist/modules/order/utils/math.js +71 -14
- package/dist/modules/order/utils/order.d.ts +65 -11
- package/dist/modules/order/utils/order.js +198 -28
- package/dist/modules/order/utils/system.d.ts +112 -2
- package/dist/modules/order/utils/system.js +338 -12
- package/dist/modules/order/utils/validate.d.ts +4 -1
- package/dist/modules/order/utils/validate.js +9 -2
- package/dist/modules/storage/index.d.ts +3 -2
- package/dist/modules/storage/index.js +3 -2
- package/dist/modules/types.d.ts +44 -2
- package/dist/scripts/analyze-credit.js +64 -23
- package/dist/scripts/bts_distribution.d.ts +66 -0
- package/dist/scripts/bts_distribution.js +2102 -0
- package/dist/scripts/token_distribution.d.ts +45 -0
- package/dist/scripts/token_distribution.js +1870 -0
- package/dist/unlock.js +42 -24
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
- package/docs/COW_INVARIANTS.md +24 -8
- package/docs/DEXBOT_COMPARISON.md +5 -5
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +13 -11
- package/docs/GRID_PRICE_INVARIANT.md +29 -3
- package/docs/GRID_RECALCULATION.md +3 -3
- package/docs/GRID_RECONCILE.md +5 -5
- package/docs/LIFECYCLE.md +11 -11
- package/docs/LOGGING.md +22 -0
- package/docs/MPA_CREDIT_USAGE.md +3 -2
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +236 -32
- package/docs/README.md +1 -1
- package/docs/architecture.md +205 -6
- package/docs/developer_guide.md +12 -0
- package/market_adapter/README.md +11 -6
- package/modules/README.md +18 -14
- package/package.json +6 -3
- package/scripts/README.md +85 -148
package/dist/unlock.js
CHANGED
|
@@ -47,7 +47,7 @@ import { setUmask } from './modules/config.js';
|
|
|
47
47
|
import fs from 'node:fs';
|
|
48
48
|
import { path } from './modules/path_api.js';
|
|
49
49
|
import { getStorage } from './modules/storage/index.js';
|
|
50
|
-
import { createCredentialDaemonController } from './modules/launcher/credential_daemon.js';
|
|
50
|
+
import { createCredentialDaemonController, clearVaultSecret } from './modules/launcher/credential_daemon.js';
|
|
51
51
|
import { buildScopedChildEnv } from './modules/launcher/child_env.js';
|
|
52
52
|
import { parseUnlockArgs } from './modules/launcher/launch_modes.js';
|
|
53
53
|
import { UPDATER, LAUNCHER } from './modules/constants.js';
|
|
@@ -954,23 +954,33 @@ async function handleControl({ cmd, target }) {
|
|
|
954
954
|
const summaryServiceNames = getControlServiceNames(effectiveCmd, summaryBotNames);
|
|
955
955
|
if (effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all') {
|
|
956
956
|
if (effectiveCmd === 'restart-all' && process.stdin.isTTY) {
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
957
|
+
// Verify the master password BEFORE stopping the live
|
|
958
|
+
// daemon. A wrong or cancelled password must leave the
|
|
959
|
+
// existing daemon (and every bot's key access) intact
|
|
960
|
+
// instead of killing it and then failing to re-unlock.
|
|
961
961
|
const daemonOpts = { detached: true };
|
|
962
|
-
const
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
if (newCredPid) {
|
|
968
|
-
try {
|
|
969
|
-
storage.writeFile(MONOLITHIC_CRED_PID_FILE, String(newCredPid), { mode: 0o600 });
|
|
962
|
+
const vaultSecret = await controller.authenticateCredential();
|
|
963
|
+
try {
|
|
964
|
+
const credResult = await stopCredentialDaemon();
|
|
965
|
+
if (credResult.signaled) {
|
|
966
|
+
console.log('Stop signal sent to credential daemon');
|
|
970
967
|
}
|
|
971
|
-
|
|
968
|
+
const unlockedNow = await controller.ensureCredentialDaemon({ ...daemonOpts, vaultSecret });
|
|
969
|
+
if (unlockedNow) {
|
|
970
|
+
console.log(statusSuccess('✓ Authentication successful'));
|
|
971
|
+
}
|
|
972
|
+
const newCredPid = controller.getManagedDaemonPid();
|
|
973
|
+
if (newCredPid) {
|
|
974
|
+
try {
|
|
975
|
+
storage.writeFile(MONOLITHIC_CRED_PID_FILE, String(newCredPid), { mode: 0o600 });
|
|
976
|
+
}
|
|
977
|
+
catch (_) { }
|
|
978
|
+
}
|
|
979
|
+
controller.releaseManagedDaemon();
|
|
980
|
+
}
|
|
981
|
+
finally {
|
|
982
|
+
clearVaultSecret(vaultSecret);
|
|
972
983
|
}
|
|
973
|
-
controller.releaseManagedDaemon();
|
|
974
984
|
}
|
|
975
985
|
// reload-all intentionally skips the credential daemon
|
|
976
986
|
// stop/re-unlock above: bots keep their key access while the
|
|
@@ -1146,17 +1156,25 @@ async function handleControl({ cmd, target }) {
|
|
|
1146
1156
|
controlCmd.bot = effectiveTarget;
|
|
1147
1157
|
// Restart credential daemon for restart-all (no target) in isolated mode
|
|
1148
1158
|
if (!effectiveTarget && effectiveCmd === 'restart-all' && process.stdin.isTTY) {
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
await stopCredentialDaemonPid(ownerPid);
|
|
1152
|
-
}
|
|
1153
|
-
cleanupCredentialRuntimeFiles();
|
|
1159
|
+
// Authenticate first: the running daemon is only stopped once the
|
|
1160
|
+
// master password is confirmed, so a failed restart keeps keys live.
|
|
1154
1161
|
const daemonOpts = { detached: true };
|
|
1155
|
-
const
|
|
1156
|
-
|
|
1157
|
-
|
|
1162
|
+
const vaultSecret = await controller.authenticateCredential();
|
|
1163
|
+
try {
|
|
1164
|
+
const ownerPid = findCredentialSocketOwnerPid();
|
|
1165
|
+
if (ownerPid > 0 && isLikelyCredentialDaemonProcess(ownerPid)) {
|
|
1166
|
+
await stopCredentialDaemonPid(ownerPid);
|
|
1167
|
+
}
|
|
1168
|
+
cleanupCredentialRuntimeFiles();
|
|
1169
|
+
const unlockedNow = await controller.ensureCredentialDaemon({ ...daemonOpts, vaultSecret });
|
|
1170
|
+
if (unlockedNow) {
|
|
1171
|
+
console.log(statusSuccess('✓ Authentication successful'));
|
|
1172
|
+
}
|
|
1173
|
+
controller.releaseManagedDaemon();
|
|
1174
|
+
}
|
|
1175
|
+
finally {
|
|
1176
|
+
clearVaultSecret(vaultSecret);
|
|
1158
1177
|
}
|
|
1159
|
-
controller.releaseManagedDaemon();
|
|
1160
1178
|
}
|
|
1161
1179
|
try {
|
|
1162
1180
|
const resp = await sendControlCommand(controlCmd);
|
|
@@ -229,7 +229,7 @@ syncFromMaster(masterGrid, orderId, masterVersion?) {
|
|
|
229
229
|
|--------|-------------|
|
|
230
230
|
| `performSafeRebalance(fills, excludeIds)` | Entry point — delegates to COW |
|
|
231
231
|
| `_applySafeRebalanceCOW(fills, excludeIds)` | Creates working grid, runs planning |
|
|
232
|
-
| `WorkingGrid.buildDelta(masterGrid)` | Delta between master and working copy (`modules/order/working_grid.ts
|
|
232
|
+
| `WorkingGrid.buildDelta(masterGrid)` | Delta between master and working copy (`modules/order/working_grid.ts`, delegating to `utils/order.ts`) |
|
|
233
233
|
| `_commitWorkingGrid(workingGrid, indexes, boundary, options = {})` | Atomic swap to master |
|
|
234
234
|
| `_setRebalanceState(state)` | Track rebalance state |
|
|
235
235
|
| `_currentWorkingGridStack` | Stack of active working-grid references during rebalance for fill sync; peek the innermost via `_peekWorkingGrid()`, managed with `_pushWorkingGridRef`/`_popWorkingGridRef`/`_releaseWorkingGridRef`/`_clearWorkingGridRef` |
|
package/docs/COW_INVARIANTS.md
CHANGED
|
@@ -57,12 +57,14 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
57
57
|
- `_clearOrderCachesLogic` must bump `_gridVersion` so an in-flight COW plan (baseVersion from the pre-swap grid) is refused at commit instead of committing over a regenerated zero-slot grid.
|
|
58
58
|
|
|
59
59
|
- `INV-COW-006` Boundary moves only on fills and same-batch spread promotion
|
|
60
|
-
- Fund changes never move the boundary. Only boundary crawl (`deriveTargetBoundary`, `order/utils/order.ts`)
|
|
60
|
+
- Fund changes never move the boundary. Only boundary crawl (`deriveTargetBoundary`, `order/utils/order.ts`), spread promotion, and the fill-driven rail clamp move it, and promotion shifts it only onto orders placed in the same atomic batch (`prepareSpreadCorrectionOrders`).
|
|
61
61
|
- Funds drive order sizing/budget allocation only; `syncBoundaryToFunds`/`calculateFundDrivenBoundary` are deleted (1.5.3).
|
|
62
|
+
- `deriveRailBoundary` (`dexbot_cow_runtime.ts`, pre-broadcast) clamps the committed boundary to the batch's resulting rails: `maxBuyIdx <= boundary <= minSellIdx - gapSlots - 1`. A fill's counter order is the rail fact, so it decides the boundary; an empty refill hole never outvotes it. Rail membership = the batch's own op destinations + master rail orders on their own side of the planned boundary (BUY at/below, SELL at/above the implied sellStart); a master order parked on the wrong side is a STRAY (refused-commit adoption, SPREAD-GUARD straggler, stranded hold) and is skipped, because clamping onto it would self-legalize the corrupt state (live: one stray sell clamped 138 → 115). Rail indices are the orders' LIVE chain price (`resolveLiveOrderLadderPosition`), not stale slot ids. A crossed/over-ceiling rail fails closed (`rail-crossed` / `rail-exceeds-grid`) and keeps the previous value instead of legalizing it; the result then passes the shared `validatePersistedBoundary` gate (with cancel/rotation sources allow-listed), so the rail clamp and the fill re-anchor end in one validator.
|
|
62
63
|
|
|
63
64
|
- `INV-COW-007` Boundary hold on guard-skipped refills
|
|
64
65
|
- When a slot on the plan's refill wire (`collectRefillSlotIds`: the plan's CREATE ids minus edge-ladder edge ids) was guard-skipped at broadcast (`skippedUpdateSlotIds` ∪ `clampedUpdateSlotIds` ∪ `skippedCreateSlotIds`), `resolveRefillBoundaryHold` keeps the COMMITTED boundary instead of committing the plan's shifted one over the stranded rail hole; the grid still commits.
|
|
65
66
|
- Edge-ladder CREATEs are excluded because reserves are static edge insurance whose fills never crawl — a skipped reserve must not pin geometry.
|
|
67
|
+
- The hold is intersected with `deriveRailBoundary`: when the batch actually placed a counter order above the committed boundary, the rail clamp advances the boundary (the hold becomes a no-op and the counter stays live). The hold still applies when nothing was placed on the promoted rail. `boundaryHeld` is `effectiveBoundary !== workingBoundary`, so crawl consumption follows the value actually committed.
|
|
66
68
|
- The hold rides to the commit as `options.boundaryHeld`, which suppresses the pending-crawl clear.
|
|
67
69
|
- `trackBoundaryHold` counts consecutive hold batches (`manager._consecutiveBoundaryHolds`, cleared on the first clean batch) with a last-hold snapshot (`manager._lastBoundaryHoldInfo`); runs of 3+ escalate visibly. It also records a hold signature (`manager._lastHeldPlanSignature`: committed boundary + guard pivot + `_lastFilledAt` + held wire) so a fill-less re-plan of an unchanged state defers instead of re-broadcasting the identical vetoed plan.
|
|
68
70
|
- Fill-driven rebalances never sleep on `_broadcastingFlag` inside `_fillProcessingLock`: `performSafeRebalance({deferIfBroadcasting:true})` returns a `deferred` result and the region-end hook schedules one no-fill rebalance (`schedulePostRecoveryRebalance`). This prevents the 20s lock-acquisition-timeout cascade when a broadcast region outlives the 30s `_awaitBroadcastIdle` wait. The stale-flag watchdog (`_clearStaleBroadcastFlag`, 120s) fires the same region-end hook when it hard-clears a leaked flag, so deferred fills are woken even when the region never ends through `stopBroadcasting()`.
|
|
@@ -71,6 +73,9 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
71
73
|
- `INV-COW-008` Owed fill crawls survive unapplied commits
|
|
72
74
|
- `order/strategy.ts` records a crawl per shift-eligible fill at intake (slot-level dedupe, capped at 500); `deriveTargetBoundary` folds still-owed `_pendingFillCrawls` into the next derivation, excluding the current batch's slots, edge slots, and window members — a window that reaches the grid edge is not an edge order, using the same window exclusion every placement picker and `countLiveEdgeOrders` apply.
|
|
73
75
|
- `_commitWorkingGrid` clears them only when the plan's boundary was actually applied — a held boundary (`boundaryHeld`), a gate-rejected boundary, and a null boundary all leave them owed.
|
|
76
|
+
- A window that lands BEHIND the newest real fill is repaired by `reanchorBoundaryFromLastFill` (called from `calculateTargetGrid` right after the derivation): the fill anchors the geometry — `SELL fill at f => boundary ≥ f − gapSlots`, `BUY fill at f => boundary ≤ f − 1` — because a ±1 crawl can never catch up. The anchor index is the current fill batch's EXTREMUM for the fill side (max slot for SELL, min slot for BUY), not the mutable last-processed pivot: a sweep processed in chunks overwrites the pivot per chunk (live: 1366 → 1349 → 1361), and anchoring on a non-extremum leaves the furthest fill's counter order in-band. Prices come from the fill record (the real execution price, `INV-COW-011`) with the slot id as a legacy fallback. Fail-closed preconditions: a pivot whose `lastFillPivotSource` is `fill` (a book seed never anchors; the bot-scoped last-market-fill row is the fallback), on-ladder price within one increment, a post-clamp target that actually puts the fill outside the window, and `validatePersistedBoundary` (a strand refuses the re-anchor). ELIGIBILITY matches the crawl: EDGE-pinned insurance fills never arm the pivot (`recordLastFilledPrices` skips them, shared classifier `collectEdgePinnedFillIds`) and so can never anchor — an edge order is static insurance, not market movement, and an absolute anchor at a rail-edge price would teleport the window there; PARTIAL fills still anchor (real trade) because the fill's OWN PARTIAL residual at the anchor slot is explicitly allow-listed (it is inside the band by construction). Startup/recovery load paths tolerate that pure in-band state (`tolerateTransientStranding`) so a restart does not rebuild the boundary before GAP-EVAC clears the residual. A successful re-anchor is absolute: it consumes the whole pending-crawl snapshot taken at plan time, so no older delta can be applied on top.
|
|
77
|
+
- Consumption is SCOPED to what the derivation applied: `deriveTargetBoundary` returns `consumedCrawlIds` (the owed records whose shift it folded, plus the records it deliberately never counts — current-batch slots, edge-classified slots, malformed records), the plan carries it (`buildSuccessResult` → `CowResult` → `_commitWorkingGrid` options), and `_consumePendingFillCrawls` drops exactly those, logging `Dropped N … kept=M`. A capped fold consumes only the entries it actually applied (same-side prefix up to the applied magnitude), so the remainder stays owed exactly once. `_clearPendingFillCrawls` remains the explicit allowed-loss path (rebuild, rejected snapshot, restart replay) and drops everything.
|
|
78
|
+
- A commit **without** the wire consumes nothing (a create-only plan never derived a boundary): clearing it would be the old silent-loss bug (2026-10-25: 7 slots 147–153 swept, every record dropped, boundary ending 7 levels behind).
|
|
74
79
|
- `consumePendingFillCrawls` applies them onto a restored finite boundary; `applyPersistedPendingCrawls` is the shared startup/recovery wrapper used before sync/reconcile; `_clearPendingFillCrawls` drops them when the boundary is re-anchored (grid rebuild via `initializeGrid`, rejected snapshot via `rejectCorruptedGridSnapshot`, persisted snapshot wipe via `AccountOrders.clearGrid`).
|
|
75
80
|
|
|
76
81
|
- `INV-COW-009` LAST-FILL-GUARD pivot survives restarts with the snapshot, and only as a fill fact
|
|
@@ -79,25 +84,36 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
79
84
|
- The row carries `{price, type, fillsAt, genesisHash}` validated by one shared gate (`normalizeLastFillPivot`) used by BOTH the `storeMasterGrid` sanitizer and the loader — the two shape checks cannot drift. `null` from the payload builder always clears the stored row (consumed pivot / cold manager / no live genesis), `undefined` stays a legacy no-op for old callers, and a malformed shape also clears.
|
|
80
85
|
- Restore ordering: `grid.loadGrid` restores the pivot right after `_restoreBoundary` — with the persisted genesis applied and the grid re-typed, BEFORE the first reconcile/broadcast — so a restart cannot re-open the cold window where evacuation stamps get applied against a boundary still being rebuilt. All `loadGrid` callers (startup resume, price-match resume, recovery reload) inherit it; there is no second restore call site to drift.
|
|
81
86
|
- Validation chain (`restoreLastFillPivot`): TTL expiry (`GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS`, 24h; the pivot is a "latest fill" fact, not a permanent ratchet; expired pivots hand over to the startup book seed) and genesis binding (mismatched hash = dead generation) erase the row through one shared drop path (`clearPersistedLastFillPivot` under the bot's persistence lock, best-effort). Off-grid refusal (`resolveOnGridPivot` — the runtime's own ladder validator, imported lazily from the restore site so ONE implementation serves both the per-probe live guard and the restore; the restorer can never accept a value the runtime would refuse per probe) is a no-op that falls back to the book seed and leaves the row for the next snapshot flush to clear (the cold in-memory pivot makes the payload builder return null). The snapped ladder level is restored, never the raw float, and the ORIGINAL `fillsAt` is preserved through `setLastFillPivot`'s `atMs` param so the TTL keeps meaning "age of the last fill", not "time since this restart".
|
|
82
|
-
- Generation invalidation mirrors the pending-crawl ledger: `initializeGrid` and `rejectCorruptedGridSnapshot` clear the in-memory pivot via `resetLastFillPivot` (exposed as `OrderManager._resetLastFillPivot`), which clears the FULL scalar family — per-side mirrors included — so `seedLastFilledPricesFromBook`'s cold gate cannot be silently suppressed by stale per-side values after a grid rebuild, and `AccountOrders.clearGrid` wipes the persisted row with the snapshot.
|
|
87
|
+
- Generation invalidation mirrors the pending-crawl ledger: `initializeGrid` and `rejectCorruptedGridSnapshot` clear the in-memory pivot via `resetLastFillPivot` (exposed as `OrderManager._resetLastFillPivot`), which clears the FULL scalar family — per-side mirrors included — so `seedLastFilledPricesFromBook`'s cold gate cannot be silently suppressed by stale per-side values after a grid rebuild, and `AccountOrders.clearGrid` wipes the persisted row with the snapshot.
|
|
88
|
+
- A rebuild then RE-ARMS explicitly (`rearmLastFillPivotFromMarketFill`) from the bot-scoped last-market-fill row, through the same writer, at the original timestamp and with provenance `'fill'`. The guard must not go cold while the account's last trade price is known (pre-1.6.14 behaviour: a rebuild let a fresh grid sell below the last sale), and the re-arm must be a logged, persisted write rather than an accident of the read-time fallback — the rebuild site's comment and the runtime behaviour were allowed to differ before this. Consequence, pinned by test: the pivot SURVIVES a rebuild (bounded by the same 24h TTL). If the market has moved away from that price, the same-side rail reads `last-fill-blocked` and only a fill (or TTL expiry) restores it; the geometry-bind watchdog therefore re-centers at most ONCE per pivot (`_lastGeometryResyncPivotKey`) — a re-center cannot move the pivot, so a second attempt would only churn the new generation — and then reports that fact instead of escalating.
|
|
89
|
+
- EDGE-PINNED fills never arm the pivot: `recordLastFilledPrices` skips the ids returned by `collectEdgePinnedFillIds` (the same window/edge classifier the placement pickers use). An edge order is static fat-finger insurance, not market movement; letting a wick on one arm the pivot at a rail-edge price would veto that whole side of the book AND, because the pivot doubles as the re-anchor's absolute geometry anchor, teleport the window to the edge.
|
|
83
90
|
|
|
84
91
|
- `INV-COW-010` Grid-layer spread-correction cycle is atomic and bounded
|
|
85
92
|
- `checkSpreadCondition` holds the refcounted broadcast region (`startBroadcasting` / `stopBroadcasting`, released in `finally`) across its whole attempt loop, so a fill-driven rebalance defers rather than committing a master-version bump between the initial plan and its broadcast. This narrows the race; the COW commit guard remains the backstop.
|
|
86
93
|
- Before broadcasting, `resolveOccupiedCorrection` re-derives a plan whose CREATE destination became a live order since planning (`getOccupiedCorrectionSlots`), or withholds it — a known-taken slot is never shipped. The COW build layer stays authoritative against a detector false positive.
|
|
87
94
|
- A transient refusal re-plans ONCE from fresh master (`replanSpreadCorrectionFromFreshMaster`, bounded by `TIMING.SPREAD_CORRECTION_MAX_ATTEMPTS`); a non-transient refusal (`commit-refused` / `update-target-missing` / `unmatched-chain-orders` / `shutdown`) is not retried and counts toward the out-of-spread stale clock.
|
|
95
|
+
- Candidates are tightening-edge-only on real grid slots (`tightensSpread` + distance-to-edge ordering + `doesNotCrossMarket`) AND last-fill consistent: the planner applies the guard's own direction rule (`passesLastFill`, same pivot, same predicate) before the quota slice, so a batch is never built from ops the broadcast guard would drop. An unplaceable side reports the geometry bind `last-fill-blocked` instead of a wasted "prepared but not executed" cycle.
|
|
96
|
+
- The budget spent by the loop is chain-truth for a known candidate set: `available = chainFree − virtualReservation` is circular when the reservation describes the very slots being funded, so an over-sized projection (rail sized from a larger balance or from inventory locked in resting orders) would read 0 forever (`planned 3, placing 0`, 84 minutes live). `deriveChainTruthFundBudget` re-derives it as `min(chainFree, min(virtualReservation, Σ candidate ideals))` when `available` is 0 **and** the reservation exceeds chain free (a zero caused by fees or an empty balance is a real constraint and is honoured); the chain stays the final arbiter.
|
|
97
|
+
- Terminal stalls are named and escalated on their own windows rather than the structural 30 minutes: rail oversubscription (`availableFund = chainFree − virtual` reads 0 while the side still holds inventory) on `SPREAD_STALE_FUND_ESCALATE_MS`, the `last-fill-blocked` geometry bind on `SPREAD_STALE_GEOMETRY_ESCALATE_MS` (capped at ONE re-center per fill pivot — `_lastGeometryResyncPivotKey` — because a re-center cannot move the pivot, and the skip is explained once instead of rebuilt every cooldown), and the persistence clock clears only after sustained tolerance (`SPREAD_STALE_IN_TOLERANCE_RESET_MS`) or a placement.
|
|
88
98
|
- This is the grid layer's counterpart to `INV-COW-003` (COW-layer pre-broadcast re-plan) and to `INV-COW-007`'s broadcast-flag deferral contract.
|
|
89
99
|
|
|
100
|
+
- `INV-COW-011` Live-price provenance for fill, gap and crossing decisions
|
|
101
|
+
- A fill record carries the chain execution price (`sync_engine._computeFillTransitionResult` / pass-1 full-fill / pass-2 adoption), computed from paid/received amounts when only the history is available; the slot's generation price is a fallback, never the first choice. The queued-fill pivot refresh (`refreshLastFillPivotFromQueue`) likewise prefers fill economics over the slot price. The slot's identity price is NOT rewritten (`GRID-PRICE-INVARIANT`); only the transient fill/pivot fact uses the chain price.
|
|
102
|
+
- Gap-evacuation geometry maps an on-chain order's LIVE price onto the genesis ladder (`resolveLiveOrderLadderPosition`) before falling back to `parseSlotIndex(slot.id)`. Detection (`detectGapEvacuationCandidates`), the drain-time validation (`_validatePriceCorrectionEntry`), and the teeth (`_processGapEvacuationTeeth`) all use it, so a refused-commit adoption that leaves an order keyed at an in-rail slot cannot hide an in-band order.
|
|
103
|
+
- A price mismatch whose live chain price maps inside the gap band queues a cancel-only `gapEvacuation` correction and drops any opposite-kind (plain re-price) entry for the same chain order. Evacuation takes precedence over correcting the order back to a stale slot price.
|
|
104
|
+
- The crossing guard's candidate set (`buildCrossingCheckCandidates`) uses the live chain price for master and pending orders, so an emission cannot print onto a live opposite-side order that was adopted at a stale slot price.
|
|
105
|
+
|
|
90
106
|
- `INV-PROJ-001` New projected orders remain virtual
|
|
91
107
|
- Orders projected into empty slots must be `VIRTUAL` with no `orderId` until chain confirmation.
|
|
92
108
|
|
|
93
109
|
- `INV-PROJ-002` Preserve on-chain PARTIAL size in projection
|
|
94
110
|
- If identity is retained (`keepOrderId=true`) and current state is `PARTIAL`, projected size must preserve current on-chain remaining size.
|
|
95
111
|
- It must not be overwritten by ideal geometric `targetSize`.
|
|
96
|
-
- Exception: a `PARTIAL` with a rotation/size-update action targeting its `orderId` does use `targetSize` (the explicit-UPDATE path
|
|
112
|
+
- Exception: a `PARTIAL` with a rotation/size-update action targeting its `orderId` does use `targetSize` (the explicit-UPDATE path in `projectTargetToWorkingGrid`, `modules/order/utils/validate.ts`).
|
|
97
113
|
- Preserve-path size must be normalized to finite, non-negative value.
|
|
98
114
|
|
|
99
115
|
- `INV-PROJ-003` ACTIVE on-chain projection preserves current size (same as PARTIAL)
|
|
100
|
-
- If identity is retained and state is `ACTIVE`, projection preserves current on-chain size via the same `shouldPreserveSize` path as `PARTIAL` (`validate.ts
|
|
116
|
+
- If identity is retained and state is `ACTIVE`, projection preserves current on-chain size via the same `shouldPreserveSize` path as `PARTIAL` (`validate.ts`, `projectTargetToWorkingGrid`).
|
|
101
117
|
- An explicit UPDATE action targeting the `orderId` is required to apply `targetSize`.
|
|
102
118
|
|
|
103
119
|
- `INV-ID-001` Order identity retention rule
|
|
@@ -116,7 +132,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
116
132
|
- `INV-ACC-003` Cross-bot fund registry invariant (INVARIANT 3)
|
|
117
133
|
- Shared-account per-bot commitment must not exceed the bot's proportional share of chain balance.
|
|
118
134
|
- Checked with widened tolerance `max(PERCENT_TOLERANCE * 3, 0.15)`.
|
|
119
|
-
- Registry failure logs an error (`order/accounting.ts
|
|
135
|
+
- Registry failure logs an error (`order/accounting.ts`, cross-bot registry invariant block), not a silent skip.
|
|
120
136
|
|
|
121
137
|
---
|
|
122
138
|
|
|
@@ -257,7 +273,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
257
273
|
|
|
258
274
|
- `INV-BATCH-001` Illegal state batch abort
|
|
259
275
|
- `executeBatch` throws `ILLEGAL_SPREAD_STATE` on an illegal grid layout (emitted at `modules/order/utils/validate.ts`, propagated via `modules/order/manager.ts` `_throwOnIllegalState`).
|
|
260
|
-
- The `_handleBatchHardAbort` catch for `ILLEGAL_ORDER_STATE` (`dexbot_class.ts
|
|
276
|
+
- The `_handleBatchHardAbort` catch for `ILLEGAL_ORDER_STATE` (`dexbot_class.ts`) is a test-only dead branch — production never emits that code; only a test stub uses it.
|
|
261
277
|
- In production, recovery + cooldown are armed on the next maintenance tick via `_abortFlowIfIllegalState` (the `INV-MAINT-002` path), returning `abortedForIllegalState: true` to the caller. The caller does not need to return immediately; the maintenance tick handles recovery.
|
|
262
278
|
- Hard abort triggers one immediate recovery sync (`_triggerStateRecoverySync`) plus arms one maintenance cooldown cycle (`_maintenanceCooldownCycles = Math.max(current, 1)`).
|
|
263
279
|
|
|
@@ -276,7 +292,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
276
292
|
- NOT virtualize the slot.
|
|
277
293
|
- Preserve `orderId` until sync reconciles it.
|
|
278
294
|
- NOT mark the order as stale-cleaned.
|
|
279
|
-
- Fast path: if the batch result indicates `ORDER_SIZE_DRIFT_TARGETED` (`dexbot_state_recovery.ts
|
|
295
|
+
- Fast path: if the batch result indicates `ORDER_SIZE_DRIFT_TARGETED` (`dexbot_state_recovery.ts`), a targeted repair applies the correction directly and skips `_triggerStateRecoverySync`.
|
|
280
296
|
|
|
281
297
|
---
|
|
282
298
|
|
|
@@ -300,7 +316,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
300
316
|
- `INV-REG-001` Cross-bot allocation ≤ proportional share
|
|
301
317
|
- Per-bot committed amounts (sum of on-chain orders) must not exceed `totalChainBalance × allocatedPercent`.
|
|
302
318
|
- Violation triggers an error-level log entry (not silent), with tolerance `max(PERCENT_TOLERANCE * 3, 0.15)`.
|
|
303
|
-
- Registry registration is pre-flight + atomic; only shared-account bots register (`dexbot.ts
|
|
319
|
+
- Registry registration is pre-flight + atomic; only shared-account bots register (`dexbot.ts` derives `sharedAccounts` where `accountGroups[a].length > 1`), and registration completes before any shared-account bot starts.
|
|
304
320
|
- Release happens in `DEXBot.shutdown`.
|
|
305
321
|
|
|
306
322
|
- `INV-REG-002` Async-locked registry writes
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# DEXBot vs DEXBot2 — Detailed Comparison Report
|
|
2
2
|
|
|
3
3
|
> **Date:** 2026-09-02 *(metrics refreshed against local source trees)*
|
|
4
|
-
> **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.6.
|
|
4
|
+
> **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.6.18).
|
|
5
5
|
> **Audience:** Developers, contributors, and operators evaluating or migrating between the two projects.
|
|
6
6
|
|
|
7
7
|
---
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
|
|
37
37
|
| Attribute | DEXBot (original) | DEXBot2 |
|
|
38
38
|
|---|---|---|
|
|
39
|
-
| **Release Track** | 1.0.0 | v1.6.
|
|
39
|
+
| **Release Track** | 1.0.0 | v1.6.18 |
|
|
40
40
|
| **Language** | Python 3.6+ | TypeScript 5.x |
|
|
41
41
|
| **Status** | Released 1.0.0, unmaintained | Active development |
|
|
42
42
|
| **Last Repo Activity** | May 23, 2020 | 2026-09-02 |
|
|
@@ -776,10 +776,10 @@ Where:
|
|
|
776
776
|
|
|
777
777
|
| Metric | DEXBot | DEXBot2 |
|
|
778
778
|
|---|---|---|
|
|
779
|
-
| **Release Track** | 1.0.0 | v1.6.
|
|
779
|
+
| **Release Track** | 1.0.0 | v1.6.18 |
|
|
780
780
|
| **Active Since** | ~2018 | December 2025 |
|
|
781
|
-
| **Last Commit** | May 23, 2020 | 2026-
|
|
782
|
-
| **Total Commits** | 2281 | 2,
|
|
781
|
+
| **Last Commit** | May 23, 2020 | 2026-11-01 |
|
|
782
|
+
| **Total Commits** | 2281 | 2,457 (current HEAD, v1.6.18 line) |
|
|
783
783
|
| **Lines of Code** | ~10,846 Python LOC in `dexbot/` | Large TypeScript runtime + adapter + Claw + analysis + tests |
|
|
784
784
|
| **Source Files** | 72 Python files in `dexbot/` | ~656 TS files across the repo |
|
|
785
785
|
| **Test Files** | 16 Python test files | 327 `test_*.ts` files (310 `tests/` + 17 `claw/tests/`, auto-discovered via `globSync`) |
|
package/docs/EVOLUTION.md
CHANGED
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
## Executive Summary
|
|
4
4
|
|
|
5
|
-
DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.6.
|
|
5
|
+
DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.6.18 release.
|
|
6
6
|
|
|
7
7
|
### Key Milestones
|
|
8
8
|
- **Project Inception**: December 2, 2025
|
|
9
|
-
- **Growth Phase**: 2,
|
|
9
|
+
- **Growth Phase**: 2,457 commits over ~9 active months
|
|
10
10
|
- **Code Maturity**: Evolution from basic utilities to a ~100,000+ LoC intelligent TypeScript system
|
|
11
|
-
- **Stability**: Progression from manual testing to a suite of
|
|
12
|
-
- **Releases**:
|
|
11
|
+
- **Stability**: Progression from manual testing to a suite of 328 automated test files
|
|
12
|
+
- **Releases**: 150 version entries in the changelog (v0.1.0 to v1.6.18)
|
|
13
13
|
|
|
14
14
|
> **Post-1.0.0 "why":** the thematic story behind the hardening releases — root cause, recurring
|
|
15
15
|
> bug families, and lessons — lives in
|
|
@@ -149,7 +149,7 @@ Evolved from a basic README to a comprehensive framework (50+ docs entries, 80%+
|
|
|
149
149
|
|
|
150
150
|
## Version History
|
|
151
151
|
|
|
152
|
-
Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-
|
|
152
|
+
Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-11-01). The 107 commits up to and including the `v0.1.0` tag are not attributed to an era, so the current totals are 2,350 (`v0.1.0..HEAD`) and 2,457 (`HEAD`); the `v1.4.x` era rows overlap slightly because `v1.4.13` is not an ancestor of `v1.4.25` in the current history. Per-release detail lives in [CHANGELOG.md](../CHANGELOG.md); the thematic post-1.0.0 story in [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md).
|
|
153
153
|
|
|
154
154
|
| Era | Commits | Theme |
|
|
155
155
|
|-----|--------:|-------|
|
|
@@ -174,11 +174,13 @@ Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` o
|
|
|
174
174
|
| v1.6.13 → v1.6.14 | 18 | Last-fill guard + live market floor for spread correction, committed-size drift resize, COW pre-broadcast guards & P2 counters, fail-closed unknown geometry, order-key rename, worker-thread test runner |
|
|
175
175
|
| v1.6.14 → v1.6.15 | 20 | Spread-correction resilience (atomic plan/retry, bounded re-plan, transient-refusal grace), price-vs-amount level identity for low-precision assets, credit-renewal free-collateral top-up, TradingView 1h/chart fixes & live data-age badge, per-asset `dexbot rich`, ~4x parallel test runner |
|
|
176
176
|
| v1.6.15 → v1.6.16 | 14 | Monolithic per-bot control routing, orientation-shared candle cache, market-profile orientation tolerance, chart log-axis hang fix + viewport-clipped draw hooks, Firefox Playwright chart suite, adapter-whitelist rename/copy sync, `dexbot rich` symbol canonicalization, doc reconciliation |
|
|
177
|
+
| v1.6.16 → v1.6.17 | 11 | Last-fill direction guard, placeable-slot spread planning with named stalls, chain-truth funding + fill-anchored boundary re-anchor, owed-crawl consumption, restart auth-before-stop with cleared vault secret, pool-priced LP-share collateral, AMA slowPeriod/slope retune, BTS & per-token supply distribution analyzers |
|
|
178
|
+
| v1.6.17 → v1.6.18 | 19 | Partial-fill re-anchor recovery (stale-evac skip, residual allow-list, crawl subsumption, rotation-only repair), rail-derived boundary + live fill/chain prices, edge-fill pivot exclusion, guard arity pinning with explicit re-arm, per-slot last-fill exclusion count, CLI `--flag=value` walker, `__test` seam guard, export-surface cleanup |
|
|
177
179
|
|
|
178
180
|
---
|
|
179
181
|
|
|
180
182
|
**Report Originally Generated**: February 19, 2026
|
|
181
|
-
**Last Updated**:
|
|
182
|
-
**Total Commits**: 2,
|
|
183
|
-
**Date Range**: December 2, 2025 –
|
|
183
|
+
**Last Updated**: November 1, 2026
|
|
184
|
+
**Total Commits**: 2,457
|
|
185
|
+
**Date Range**: December 2, 2025 – November 1, 2026
|
|
184
186
|
**Repository**: DEXBot2 (BitShares DEX Trading Bot)
|
|
@@ -27,7 +27,7 @@ $$Available = \max(0, \text{ChainFree} - \text{Virtual} - \text{FeesOwed} - \tex
|
|
|
27
27
|
**Critical Invariants:**
|
|
28
28
|
1. **Virtual represents Plan.** Orders remain in `Virtual` only while they are truly uncommitted. As soon as they move to `ACTIVE`, they move to `Committed` (Chain), even if the blockchain transaction is still in flight. This maintains the `Total = Free + Committed` invariant.
|
|
29
29
|
2. **Available Funds = True Spending Power.** This formula is the single source of truth for how much capital can be deployed immediately.
|
|
30
|
-
3. **Non-BTS pair reservation.** When neither asset is BTS, the formula adds an extra proportional deduction: any BTS fee-budget deficit (formula budget minus `funds.btsBalance.free`) is split across `buyFree` + `sellFree` proportional to each side's free balance, and the side's share is subtracted from `Available`. See `calculateAvailableFundsValue()` in `modules/order/utils/math.ts
|
|
30
|
+
3. **Non-BTS pair reservation.** When neither asset is BTS, the formula adds an extra proportional deduction: any BTS fee-budget deficit (formula budget minus `funds.btsBalance.free`) is split across `buyFree` + `sellFree` proportional to each side's free balance, and the side's share is subtracted from `Available`. See `calculateAvailableFundsValue()` in `modules/order/utils/math.ts`.
|
|
31
31
|
|
|
32
32
|
### 1.3 Capital Allocation Pipeline
|
|
33
33
|
|
|
@@ -52,7 +52,9 @@ funds.allocated → _getSizingContext() (budget for spread correction)
|
|
|
52
52
|
**Key points:**
|
|
53
53
|
- `botFunds` percentage applies to **total** capital (free + locked in orders), not just free. A bot at `"50%"` gets half of everything, not half of what's currently idle.
|
|
54
54
|
- `funds.allocated` is the ceiling for each side. Existing orders already consume part of it; the remaining free portion is available for new placements.
|
|
55
|
-
- The downstream `applyBotFundsAllocation()` (`manager.ts
|
|
55
|
+
- The downstream `applyBotFundsAllocation()` (`order/manager.ts`) also caps `funds.available` to `<= allocated` as a safety net, but the primary budget chokepoint is `getSideBudget` / `_getSizingContext` reading `allocated` directly (v1.2.6).
|
|
56
|
+
- `funds.available[side] = max(0, chainFree − virtualReservation − fees)`. When the empty rail already reserves more than the chain holds, this reads 0 while the side still holds inventory — the **rail oversubscribed** state. Spread correction names it in the log, flags it on the manager, and the out-of-spread watchdog escalates it on `TIMING.SPREAD_STALE_FUND_ESCALATE_MS`: the durable repair is re-sizing the rail from chain truth (structural re-center).
|
|
57
|
+
- For a KNOWN candidate set the reservation must not veto the placement it describes: `deriveChainTruthFundBudget` (`utils/math.ts`) re-derives `min(chainFree, min(virtualReservation, Σ candidate ideals))` when `available` reads 0, so an over-sized projection cannot deadlock placement. The chain rejects an over-commit at broadcast, so this cannot spend more than exists.
|
|
56
58
|
|
|
57
59
|
---
|
|
58
60
|
|
|
@@ -67,7 +69,7 @@ Mixed BUY/SELL batches are validated per asset using a signed-delta **peak** run
|
|
|
67
69
|
|
|
68
70
|
#### Implementation Location
|
|
69
71
|
|
|
70
|
-
File: `modules/dexbot_cow_runtime.ts` — `validateOperationFunds()
|
|
72
|
+
File: `modules/dexbot_cow_runtime.ts` — `validateOperationFunds()`, called from the COW batch broadcast path.
|
|
71
73
|
|
|
72
74
|
```javascript
|
|
73
75
|
// Per-asset peak requirement vs. quantized chain-free snapshot.
|
|
@@ -112,7 +114,7 @@ See [developer_guide.md#order-state-helper-functions](developer_guide.md#order-s
|
|
|
112
114
|
|
|
113
115
|
#### Gap-Slot Batch Fill Processing
|
|
114
116
|
|
|
115
|
-
**Mechanism**: Fill events arrive via `modules/dexbot_fill_runtime.ts` (the fill-runtime module), which pushes them into `bot._incomingFillQueue` (declared in `modules/dexbot_class.ts`). The drain loop in `dexbot_fill_runtime.ts` then chunks the queue into capped batches and calls `modules/order/manager.ts::processFilledOrders`
|
|
117
|
+
**Mechanism**: Fill events arrive via `modules/dexbot_fill_runtime.ts` (the fill-runtime module), which pushes them into `bot._incomingFillQueue` (declared in `modules/dexbot_class.ts`). The drain loop in `dexbot_fill_runtime.ts` then chunks the queue into capped batches and calls `modules/order/manager.ts::processFilledOrders` once per chunk to run the full rebalance pipeline.
|
|
116
118
|
|
|
117
119
|
**Batch Sizing Algorithm**: Batch size is derived from the grid gap-slot count + 1 (`DEXBot._getGapSlotBatchSize`): a queue depth at or below gapSlots+1 is processed as one unified batch; deeper queues are chunked into repeated batches of gapSlots+1 (the last chunk may be smaller). The same gapSlots+1 size caps order operations per broadcast transaction (oversized op batches are split into sequential broadcasts).
|
|
118
120
|
|
|
@@ -123,7 +125,7 @@ See [developer_guide.md#order-state-helper-functions](developer_guide.md#order-s
|
|
|
123
125
|
**Per-Batch Execution**:
|
|
124
126
|
|
|
125
127
|
1. **Peek & Pop**: Check `_incomingFillQueue`, pop up to N fills (batch size)
|
|
126
|
-
2. **Replay-safe Accounting Pass**: Each fill is accounted individually via `processFillAccounting(fillOp, fillKey)` with replay-safe dedup (`applyReplaySafeFillAccounting`, `dexbot_fill_runtime.ts
|
|
128
|
+
2. **Replay-safe Accounting Pass**: Each fill is accounted individually via `processFillAccounting(fillOp, fillKey)` with replay-safe dedup (`applyReplaySafeFillAccounting`, `dexbot_fill_runtime.ts`)
|
|
127
129
|
- Proceeds credited directly to `chainFree` (via `adjustTotalBalance`)
|
|
128
130
|
- Same-order fill batching (sync_engine Phase 6 cumulative transition) aggregates multiple fill transitions on one order before a single rebalance
|
|
129
131
|
- All proceeds immediately available to next rebalance cycle (not split across cycles)
|
|
@@ -137,7 +139,7 @@ See [developer_guide.md#order-state-helper-functions](developer_guide.md#order-s
|
|
|
137
139
|
|
|
138
140
|
**Result**: 29 fills now processed in ~8 broadcasts (~24s) instead of 29 broadcasts (~90s).
|
|
139
141
|
|
|
140
|
-
**Residual Dust Cancellation** (post-1.4.12): After a sub-dust fill leaves a residual order on chain (e.g. the quote-side value truncates to 0 on `bitshares-core` `maybe_cull_small_order`), the fill runtime explicitly cancels those residuals via `cancelResidualOrders()` (`dexbot_fill_runtime.ts
|
|
142
|
+
**Residual Dust Cancellation** (post-1.4.12): After a sub-dust fill leaves a residual order on chain (e.g. the quote-side value truncates to 0 on `bitshares-core` `maybe_cull_small_order`), the fill runtime explicitly cancels those residuals via `cancelResidualOrders()` (`dexbot_fill_runtime.ts`, `[RESIDUAL]` tag) so a leftover of ≥1 base unit cannot be re-adopted into a grid slot by maintenance.
|
|
141
143
|
|
|
142
144
|
#### Grid Regeneration Trigger (Available Funds Ratio — bidirectional)
|
|
143
145
|
|
|
@@ -399,7 +401,7 @@ targetSlot.orderId = newOrderId;
|
|
|
399
401
|
|
|
400
402
|
### 3.6 Orphan-Fill Deduplication & Double-Credit Prevention
|
|
401
403
|
|
|
402
|
-
**Location**: `modules/dexbot_class.ts` — constructor, `_recoverExplicitStaleOrders()
|
|
404
|
+
**Location**: `modules/dexbot_class.ts` — constructor, `_recoverExplicitStaleOrders()`; orphan-fill guard in the fill drain loop and pruning pass after each cycle now live in `modules/dexbot_fill_runtime.ts` (the orphan-fill guard and the post-cycle pruning pass).
|
|
403
405
|
|
|
404
406
|
#### Stale-Cleaned Order ID Tracking with TTL + Recycled-Slot Guard
|
|
405
407
|
|
|
@@ -556,7 +558,7 @@ These are deducted from the *proceeds* of a fill.
|
|
|
556
558
|
|
|
557
559
|
For BTS fees, the system returns a structured object (not a simple number) with multiple fields for accounting precision.
|
|
558
560
|
|
|
559
|
-
**Location**: `modules/order/utils/math.ts::getAssetFees()
|
|
561
|
+
**Location**: `modules/order/utils/math.ts::getAssetFees()`. The fee cache itself is populated by `modules/order/utils/system.ts::initializeFeeCache()`.
|
|
560
562
|
|
|
561
563
|
#### BTS Fee Object (Always Object)
|
|
562
564
|
|
|
@@ -670,7 +672,7 @@ Floating-point arithmetic drifts from true blockchain integer representations ov
|
|
|
670
672
|
|
|
671
673
|
#### 5.5.1 Core Quantization Functions
|
|
672
674
|
|
|
673
|
-
**Location**: `modules/order/utils/math.ts` (
|
|
675
|
+
**Location**: `modules/order/utils/math.ts` (`quantizeFloat`)
|
|
674
676
|
|
|
675
677
|
##### `quantizeFloat(value, precision)` - Eliminate Accumulation Errors
|
|
676
678
|
|
|
@@ -772,7 +774,7 @@ This prevents the bug where `available = chainFree + required` created a tautolo
|
|
|
772
774
|
|
|
773
775
|
## 6. Safety & Invariants
|
|
774
776
|
|
|
775
|
-
The `Accountant` enforces strict mathematical invariants to detect bugs or manual interference. Invariants are checked by `_verifyFundInvariants()` (`modules/order/accounting.ts`
|
|
777
|
+
The `Accountant` enforces strict mathematical invariants to detect bugs or manual interference. Invariants are checked by `_verifyFundInvariants()` (`modules/order/accounting.ts`) after every blockchain sync cycle. The verification reads from a snapshot captured under `_fundLock` — `actualBuy`/`actualSell` are captured at snapshot time, not read live outside the lock, closing a TOCTOU window. When a violation is detected, the system logs a `CRITICAL` error and attempts automatic recovery via `manager.accountant.recalculateFunds()` (`modules/order/accounting.ts`, delegated from `modules/order/manager.ts`) — resetting internal state to match on-chain reality. If the grid lock is held (mid-rebalance), recovery is deferred until the lock is released. The bot continues operating throughout; it does **not** halt on invariant violations.
|
|
776
778
|
|
|
777
779
|
### 6.1 The Equality Invariant
|
|
778
780
|
Total funds on chain must equal free plus committed.
|
|
@@ -803,4 +805,4 @@ To prevent "Time-of-Check to Time-of-Use" errors:
|
|
|
803
805
|
**TOCTOU protection in `processFillAccounting`.** `_buildBtsDeferredRefundAdjustment` reads `btsFeeState` from `mgr.orders` while the order lock is held — the lock is acquired before accounting runs, and the POST-RESET and BOOTSTRAP tracked-fill accounting paths follow the same locking pattern.
|
|
804
806
|
|
|
805
807
|
---
|
|
806
|
-
*Technical Reference for DEXBot2 v1.6.
|
|
808
|
+
*Technical Reference for DEXBot2 v1.6.18 release*
|
|
@@ -116,6 +116,31 @@ fixture), as is a destination hole carrying an already-corrupted price (28%).
|
|
|
116
116
|
|
|
117
117
|
### The seventh gate: final pre-broadcast pivot re-check
|
|
118
118
|
|
|
119
|
+
The per-action LAST-FILL-GUARD rule is direction-only relative to that pivot —
|
|
120
|
+
a BUY is blocked at/above it, a SELL at/below it (equal price is a re-place at
|
|
121
|
+
the just-filled level). The spread-correction planner applies the SAME predicate
|
|
122
|
+
to its candidates before planning, so a correction batch never contains an op
|
|
123
|
+
the guard would drop. The predicate takes exactly `(price, type, lastPrice,
|
|
124
|
+
lastType)`: there is no size or increment argument, because the old
|
|
125
|
+
`pivot ± increment/2` band was what blocked profitable placements.
|
|
126
|
+
|
|
127
|
+
**What may become the pivot.** Only a real WINDOW trade. EDGE-pinned insurance
|
|
128
|
+
fills (grid floor/ceiling) are skipped by `recordLastFilledPrices` via the
|
|
129
|
+
shared classifier `collectEdgePinnedFillIds`, matching the crawl's own edge
|
|
130
|
+
exclusion: an edge order is static fat-finger insurance, not market movement,
|
|
131
|
+
and the pivot is also the absolute geometry anchor for
|
|
132
|
+
`reanchorBoundaryFromLastFill` — a rail-edge pivot would teleport the window to
|
|
133
|
+
that edge. PARTIAL fills do arm it (a real trade at a real price). The pivot
|
|
134
|
+
then survives a grid rebuild: `_resetLastFillPivot` clears it with the
|
|
135
|
+
old generation and `rearmLastFillPivotFromMarketFill` re-arms it immediately
|
|
136
|
+
from the bot-scoped last-market-fill row, provenance `'fill'`.
|
|
137
|
+
|
|
138
|
+
*Operational consequence (deliberate):* after an edge fill the affected side
|
|
139
|
+
stays vetoed relative to the last WINDOW trade until a window fill (or the 24h
|
|
140
|
+
pivot TTL) re-arms it — e.g. a floor insurance BUY does not license selling that
|
|
141
|
+
inventory below the last window sale. Moving the geometry to the edge instead
|
|
142
|
+
(the pre-fix behaviour) re-typed and cancelled the whole window on a wick.
|
|
143
|
+
|
|
119
144
|
The per-action LAST-FILL-GUARD checks run against the pivot frozen at batch
|
|
120
145
|
start. A fill queued between that freeze and the broadcast passes every
|
|
121
146
|
per-action check on a stale pivot and ships (live incident: freeze at 0.745,
|
|
@@ -412,9 +437,10 @@ is divergence telemetry built on `calculateGridSideDivergenceMetric`.
|
|
|
412
437
|
|
|
413
438
|
**A grid with no price ladder is not a degraded grid — it is an undefined one.**
|
|
414
439
|
Every consumer of the invariant reads `priceForSlot(idx, genesis)`, and each one
|
|
415
|
-
silently degrades without it: nearest-slot adoption,
|
|
416
|
-
|
|
417
|
-
|
|
440
|
+
silently degrades without it: nearest-slot adoption (`sync_engine.ts`), the
|
|
441
|
+
materialize descriptor-price fallback (`sync_engine.ts`), edge anchoring via
|
|
442
|
+
`resolveLiveEdgeAnchorPrice` (`order/utils/order.ts`), and the `isSlotInRail`
|
|
443
|
+
fail-open (`order/utils/math.ts`). That degradation is the tolerance
|
|
418
444
|
matcher, which is exactly the path on which an off-grid price becomes grid
|
|
419
445
|
evidence. So the ladder is treated as a **required** part of a snapshot, not a
|
|
420
446
|
nice-to-have.
|
|
@@ -160,16 +160,16 @@ node dist/market_adapter/market_adapter.js --deltaPercent 2
|
|
|
160
160
|
"ama": {
|
|
161
161
|
"erPeriod": 781, // Efficiency Ratio lookback period (candles)
|
|
162
162
|
"fastPeriod": 5.2, // Fast smoothing period for trending markets
|
|
163
|
-
"slowPeriod": 83.
|
|
163
|
+
"slowPeriod": 83.5 // Slow smoothing period for choppy markets
|
|
164
164
|
}
|
|
165
165
|
}
|
|
166
166
|
```
|
|
167
167
|
|
|
168
168
|
> Optional. A bot-level `ama` block overrides the preset (or matched pair profile)
|
|
169
169
|
> field by field, and supplying any period marks the bot's AMA as `custom` in the
|
|
170
|
-
> adapter state. The values above are the
|
|
170
|
+
> adapter state. The values above are the built-in `AMA3` defaults
|
|
171
171
|
> (`MARKET_ADAPTER.AMAS`): `erPeriod: 781` and `fastPeriod: 5.2` are shared, while
|
|
172
|
-
> `slowPeriod` runs `62.1` (AMA1) to `
|
|
172
|
+
> `slowPeriod` runs `62.1` (AMA1) to `99.3` (AMA4).
|
|
173
173
|
|
|
174
174
|
> **`gridPrice` is the only switch.** A bot is AMA-driven when `gridPrice` says
|
|
175
175
|
> so — `usesAmaGridPrice()`, the source of truth shared by the bot, maintenance
|
package/docs/GRID_RECONCILE.md
CHANGED
|
@@ -80,14 +80,14 @@ Phase 2 and 3 both respect the `dryRun` flag: when true, no on-chain mutations a
|
|
|
80
80
|
|
|
81
81
|
**Source:** `reconcileGridOrders()` Phase 1 in `grid_reconcile.ts`.
|
|
82
82
|
|
|
83
|
-
1. **Phantom order sanitization** (
|
|
84
|
-
- **Freshly-assigned deferral** (
|
|
85
|
-
- **Ghost heuristic** (
|
|
83
|
+
1. **Phantom order sanitization** (the `isOrderPlaced()` absence pass in `reconcileGridOrders()`): For each `isOrderPlaced()` order whose `orderId` is not in the chain snapshot, reset it to VIRTUAL with `skipAccounting` to prevent fund inflation. Two absence-decision guards make this safe:
|
|
84
|
+
- **Freshly-assigned deferral** (the `_orderIdAssignedAt` freshness guard): an `orderId` assigned within `TIMING.SYNC_LOCK_TIMEOUT_MS` may be an in-flight create/adopt whose broadcast has not landed or is not yet visible to a lagging/truncated read — virtualizing it and re-creating would duplicate a real live order (the reconcile-timeout death-spiral root cause). It is skipped (deferred) rather than virtualized.
|
|
85
|
+
- **Ghost heuristic** (same absence pass): an order with `size <= 0` && `PARTIAL` (a known filled ghost) still passes through so known fills get cleaned up.
|
|
86
86
|
- Virtualization always uses `{ skipAccounting: true }` so startup cleanup never inflates `ChainFree`.
|
|
87
87
|
|
|
88
|
-
2. **Duplicate detection** (
|
|
88
|
+
2. **Duplicate detection** (the unmatched-order duplicate pass): For each unmatched chain order, find the nearest active same-side grid order. If its price equals that grid order's slot price exactly (`priceSlotEqual` at the asset precision), flag it as a suspected duplicate and queue for a Phase 2 cancel (never cancelled under lock). Non-equal neighbours are only logged with nearest-same-side diagnostics and continue into per-side reconciliation. Duplicate IDs are removed from the unmatched set so they aren't also paired for updates/creates.
|
|
89
89
|
|
|
90
|
-
3. **Per-side reconciliation** via `_reconcileStartupSide(planOnly=true)` (
|
|
90
|
+
3. **Per-side reconciliation** via `_reconcileStartupSide(planOnly=true)` (`grid_reconcile_internal.ts`):
|
|
91
91
|
- Count `matchedOnGrid` (active grid orders with `orderId`)
|
|
92
92
|
- `neededSlots = targetCount - matchedOnGrid`; pick virtual slots to activate
|
|
93
93
|
- Match sorted unmatched chain orders to virtual slots → `plannedUpdates`
|
package/docs/LIFECYCLE.md
CHANGED
|
@@ -90,7 +90,7 @@ sequenceDiagram
|
|
|
90
90
|
participant CO as chain_orders (broadcast)
|
|
91
91
|
participant STORE as Storage
|
|
92
92
|
|
|
93
|
-
CH->>Q: enqueue fill(s) (dexbot_fill_runtime.ts
|
|
93
|
+
CH->>Q: enqueue fill(s) (createFillCallback, dexbot_fill_runtime.ts)
|
|
94
94
|
FR->>FR: drain queue -> _processFillsWithBatching
|
|
95
95
|
FR->>OM: processFilledOrders() (manager.ts)
|
|
96
96
|
OM->>AC: processFillAccounting() (single call, batch)
|
|
@@ -134,10 +134,10 @@ sequenceDiagram
|
|
|
134
134
|
participant STORE as Storage
|
|
135
135
|
|
|
136
136
|
MA->>CL: AMA center snapshot updated
|
|
137
|
-
CL->>CL: _performPeriodicGridChecks() (dexbot_class.ts
|
|
138
|
-
CL->>RT: performPeriodicGridChecks() (dexbot_maintenance_runtime.ts
|
|
139
|
-
RT->>RT:
|
|
140
|
-
RT->>RT: executeMaintenanceLogic() (dexbot_maintenance_runtime.ts
|
|
137
|
+
CL->>CL: _performPeriodicGridChecks() (dexbot_class.ts)
|
|
138
|
+
CL->>RT: performPeriodicGridChecks() (dexbot_maintenance_runtime.ts)
|
|
139
|
+
RT->>RT: _runGridMaintenance('periodic') (dexbot_class.ts, called from maintenance)
|
|
140
|
+
RT->>RT: executeMaintenanceLogic() (dexbot_maintenance_runtime.ts)
|
|
141
141
|
RT->>AC: recalculate funds from balances
|
|
142
142
|
RT->>GD: promote AMA center -> grid center
|
|
143
143
|
RT->>GD: recalculateGrid() (grid.ts)
|
|
@@ -157,13 +157,13 @@ The AMA signal stack (AMA/Kalman/Hurst/PE) is *research-tuned* in `analysis/` an
|
|
|
157
157
|
the parameters.
|
|
158
158
|
|
|
159
159
|
> Note: `runMaintenance()` is a **different** subsystem — the credit/MPA debt
|
|
160
|
-
> runtime (`modules/credit_runtime.ts
|
|
161
|
-
> `_runCreditRuntimeMaintenance`
|
|
160
|
+
> runtime (`modules/credit_runtime.ts`, `runMaintenance()`), reached via
|
|
161
|
+
> `_runCreditRuntimeMaintenance` (`dexbot_class.ts`). The grid maintenance
|
|
162
162
|
> chain above is the one that matters for order/price upkeep.
|
|
163
163
|
|
|
164
|
-
References: `modules/dexbot_class.ts
|
|
165
|
-
`modules/dexbot_maintenance_runtime.ts
|
|
166
|
-
|
|
164
|
+
References: `modules/dexbot_class.ts` (`_performPeriodicGridChecks` →
|
|
165
|
+
`_runGridMaintenance`) → `modules/dexbot_maintenance_runtime.ts`
|
|
166
|
+
(`performPeriodicGridChecks` → `executeMaintenanceLogic`),
|
|
167
167
|
`docs/GRID_RECALCULATION.md`, `docs/GRID_RECONCILE.md`.
|
|
168
168
|
|
|
169
169
|
---
|
|
@@ -192,7 +192,7 @@ enforced*, not compiler-enforced — learn them or you will introduce fund bugs.
|
|
|
192
192
|
| How a fill becomes orders | `modules/dexbot_fill_runtime.ts` → `modules/order/manager.ts` |
|
|
193
193
|
| Grid math / recalculation | `modules/order/grid.ts`, `docs/GRID_RECALCULATION.md` |
|
|
194
194
|
| Funds & accounting | `modules/order/accounting.ts`, `docs/FUND_MOVEMENT_AND_ACCOUNTING.md` |
|
|
195
|
-
| Periodic loop & AMA hook | `modules/dexbot_maintenance_runtime.ts`, `modules/dexbot_class.ts
|
|
195
|
+
| Periodic loop & AMA hook | `modules/dexbot_maintenance_runtime.ts`, `modules/dexbot_class.ts` (`_performPeriodicGridChecks`, `_runGridMaintenance`) |
|
|
196
196
|
| Market signal source | `market_adapter/market_adapter.ts`, `analysis/README.md` |
|
|
197
197
|
| Startup & orchestration | `modules/dexbot_class.ts`, `docs/developer_guide.md` §"Startup Sequence" |
|
|
198
198
|
| Why COW exists | `docs/architecture.md` §"Copy-on-Write (COW) Grid Pattern", `docs/COW_INVARIANTS.md` |
|
package/docs/LOGGING.md
CHANGED
|
@@ -307,6 +307,28 @@ re-plan retries). Kept separate from the generic `refusedCommitCount`.
|
|
|
307
307
|
| `[SPREAD-CORRECTION] Plan-time dedupe: N planned slot(s) occupied since planning (...); re-planning from fresh master` | A planned CREATE destination was taken after planning; the plan is re-derived from fresh master |
|
|
308
308
|
| `[SPREAD-CORRECTION] Plan-time dedupe: ...; no re-plan candidate — refusing this cycle` | Collision detected but no fresh candidate exists; the colliding plan is withheld (never broadcast) |
|
|
309
309
|
| `[SPREAD-CORRECTION] Batch refused (cause); re-planning from fresh master (attempt 2/2)` | Transient refusal; the bounded fresh-master re-plan is in progress |
|
|
310
|
+
| `[SPREAD-CORRECTION] Excluded N candidate(s) from <side> planning: SELL must be above / BUY must be below the last fill ... (the broadcast guard would drop them)` | The planner dropped tightening-edge candidates that the LAST-FILL-GUARD would veto. They were never planned, so no batch is wasted on a guaranteed refusal. `N` counts candidate SLOTS, not pool visits — an empty in-rail slot qualifies for both the SPREAD pool and the orphan pool, and counting visits reported every vetoed slot twice (SLF-13) |
|
|
311
|
+
| `[SPREAD-CORRECTION] No placeable <side> slot: every tightening slot is at/through the last fill ...` | Honest no-op: the side cannot be tightened against the last fill (a boundary move or a new fill must restore headroom). Not a batch refusal |
|
|
312
|
+
| `[SPREAD-CORRECTION] Fund-constrained promotion on <side>: rotating N resting order(s) into the gap (...)` | Free funds could not fund every promoted gap slot; same-side ACTIVE orders are moved into the unfunded slots at their booked size (no new commitment). The action is a COW UPDATE rotation, never a CREATE. Destinations come from the post-dedupe/post-duplicate-price candidate list |
|
|
313
|
+
| `[SPREAD] No fundable side, but a rotation-only repair is available on <side>; using resting inventory (no new commitment).` | Both sides read zero free (or side selection returned no fundable side), but a promoted gap slot can be filled by rotating a resting order. Cross-asset side selection was not overridden when the market price itself was unavailable |
|
|
314
|
+
| `[LAST-FILL-GUARD] Skipping <type> UPDATE for <src> -> <dst>: stale gap-evacuation (...) — next plan re-evaluates` | A plan-build gap-evacuation stamp no longer matches the LIVE boundary/gap (or the live probe is not violation-reducing). The op is dropped instead of falling through to the direction-only last-fill guard; the next plan/reconcile owns the move |
|
|
315
|
+
| `[LAST-FILL-GUARD] Final gate dropping stale gap-evacuation ...` | The final pre-broadcast pivot gate also refuses a stamp whose live geometry went stale after op-building, even when the destination price itself is direction-legal |
|
|
316
|
+
| `[SPREAD-CORRECTION] <side> rail is OVERSUBSCRIBED: virtual reservation X exceeds chain free Y by Z — no correction can be funded until the rail is re-sized ...` | `availableFund` is `free − virtual`, so an oversubscribed rail reads 0 while the side still holds inventory. The watchdog escalates this on its short fund window |
|
|
317
|
+
| `[SPREAD-STALE] Spread out of tolerance for Nmin ... (outOfSpread=..., stall=...)` | Persistence warn with the last stall cause; the clock survives single in-tolerance readings and the terminal cases escalate early: `stall=last-fill-blocked` (sell window behind the last fill) on the 10-minute geometry window, a rail oversubscription on the 5-minute fund window |
|
|
318
|
+
| `[SPREAD-STALE] ... (sell window behind the last fill — re-centering)` | The `last-fill-blocked` geometry bind is escalating; placement cannot repair it, a re-center can |
|
|
319
|
+
| `[SPREAD-STALE] Still out of tolerance Nmin after re-centering on fill pivot P: the pivot is outside this generation's placeable side, so a re-center cannot clear it. A fill ... or pivot expiry restores the side; no further re-center will be requested for this pivot.` | Churn cap: a re-center does not move the pivot, so the same fill gets ONE re-center (`_lastGeometryResyncPivotKey`). Logged once per pivot; the same-side rail stays blocked until a fill or the 24h pivot TTL, by design |
|
|
320
|
+
| `[BOUNDARY] Re-anchored from the last fill: SELL filled at slot 153 (0.447640); boundary 146 -> 149 so the fill sits outside its own window` | The window was behind the fill and a ±1 crawl cannot catch up; the fill now anchors the geometry. The anchor is the current fill batch's extremum for that side (max SELL / min BUY), not the last-processed pivot. Refusals stay silent (cold/off-ladder/ceiling-clamped/unsafe preconditions); the fill's own PARTIAL residual is allow-listed, so a partial fill does not deadlock the repair |
|
|
321
|
+
| `[FILL-PIVOT] pivot=... buy=... sell=... n=N src=full/direct` (+ `edge-skipped=K` when present) | One line per fill batch: the LAST-FILL-GUARD pivot after the batch. `edge-skipped=K` means K edge-pinned insurance fills were ignored — they never arm the pivot, so they can never drive the re-anchor |
|
|
322
|
+
| `[FILL-PIVOT] K edge-pinned fill(s) ignored — the guard pivot and the boundary anchor stay on the last window trade` | Edge-only batch: nothing armed, which is the point |
|
|
323
|
+
| `[LAST-FILL-GUARD] Re-armed on the new generation: 0.447640(SELL) from the last real fill (age Ns) — the guard survives a rebuild by design` | A grid rebuild dropped the generation-bound pivot and re-armed it explicitly from the bot-scoped last-market-fill row (`rearmLastFillPivotFromMarketFill`). Provenance stays `fill`; the timestamp is the original fill's |
|
|
324
|
+
| `[COW-CROSS-GUARD] CREATE SELL for slot-N at P sits on the crossing side of the floor F (the planner refuses these; a generic refill does not) — it executes at the best available price, so this is a taker-fee observation, not a veto. Once per batch.` | Planner/execution asymmetry made visible: `doesNotCrossMarket` is planner-only, so a reconcile/re-fill CREATE can be a taker fill. Never blocking by design (a hard veto would re-open the counter-order deadlock) |
|
|
325
|
+
| `[COW] Boundary rail-derived: planned X, held Y -> Z (maxBuy=..., minSell=...) — keeping placed counter orders on their rails` | The batch's own rails disagree with the boundary a refill hold would commit. `deriveRailBoundary` clamps to `maxBuy <= boundary <= minSell-gap-1`, so a fill's counter order carries the boundary instead of being stranded in the band. The refill hold still applies when nothing was placed above the committed boundary. The reason suffix `(N stray rail order(s) ignored)` names master orders parked on the wrong side (refused-commit adoption / stranded hold), and `window=K` reports the grid's claimed window size |
|
|
326
|
+
| `[COW] Boundary rail-derived: unusable (rail-crossed ... / rail-exceeds-grid ...); keeping Z` | The live/placed rails already overlap or cannot fit the gap band. Fail closed: keep the previous boundary and let GAP-EVAC / the next plan resolve the offending order (never self-legalize a crossed rail) |
|
|
327
|
+
| `[COW] Boundary rail-derived: unusable (unsafe: placed_order_in_band ...); keeping Z` | The shared `validatePersistedBoundary` gate refused the clamped value (it would strand a placed order in the implied band). Same validator as the restore/commit paths and the fill re-anchor; the only get-out is the batch vacating the slot |
|
|
328
|
+
| `[SYNC] Gap-evacuation queued for <orderId> (slot <slot>): live price P maps inside the gap band (boundary B, gap G) — cancelling instead of re-pricing` | A chain price mismatch is actually an in-band placement: the live price maps between the boundary and sellStart. Queued as a cancel-only evacuation, and any plain re-price entry for the same chain order is dropped so the two cannot race |
|
|
329
|
+
| `[SPREAD-CORRECTION] sell projection exceeds chain free by 1485.41092974; funding the candidates from chain truth (2171.2 for 2171.2 of ideal size) instead of placing nothing` | The virtual reservation is the projection of these very candidates and is larger than the chain free balance; the correction funds what the chain actually holds instead of deadlocking on a circular budget |
|
|
330
|
+
| `[BOUNDARY] Dropped N owed fill crawl(s) (boundary commit): buy=B sell=S net=N±M oldest=Ns kept=M boundary X -> Y` | The commit consumed the records the derivation folded (`kept=M` = records that stayed owed — a capped fold or a re-recorded slot) |
|
|
331
|
+
| `[BOUNDARY] Kept N owed fill crawl(s) unconsumed (boundary commit)` | The commit arrived without a consumed-set (a plan that never derived a boundary) or folded nothing it could apply; the records stay owed for the next derivation |
|
|
310
332
|
| `Spread correction batch was prepared but not executed. Keeping local state unchanged. (cause=...)` | Terminal refusal; `cause` is the classified `SPREAD_CORRECTION_REFUSAL` value |
|
|
311
333
|
| `Shutdown complete. Final metrics: ... spreadCorrectionRefusals=N [cause=count, ...], spreadCorrectionRetries=M` | Refusal breakdown on shutdown; the suffix appears only when at least one refusal occurred |
|
|
312
334
|
|