dexbot 1.6.13 → 1.6.15
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 +66 -4
- package/README.md +2 -2
- package/analysis/README.md +6 -6
- package/analysis/tradingview/README.md +2 -1
- package/claw/README.md +7 -7
- package/claw/docs/AI_BOT_LIBRARY_API.md +1 -1
- package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
- package/claw/modules/claw_catalog.ts +8 -4
- package/claw/modules/dexbot_profiles.ts +59 -15
- package/claw/modules/types.ts +2 -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/claw/skills/margin-trading/SKILL.md +1 -1
- package/claw/skills/margin-trading/references/position-management.md +1 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +105 -31
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +36 -2
- package/dist/dexbot.js +23 -3
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
- package/dist/modules/account_bots.d.ts +10 -6
- package/dist/modules/account_bots.js +13 -10
- package/dist/modules/account_orders.d.ts +36 -4
- package/dist/modules/account_orders.js +76 -5
- package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
- package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
- package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
- package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
- package/dist/modules/bitshares-native/subscriptions.js +1 -1
- package/dist/modules/bot_defaults.d.ts +29 -4
- package/dist/modules/bot_defaults.js +65 -10
- package/dist/modules/bot_settings.d.ts +4 -0
- package/dist/modules/bot_settings.js +58 -21
- package/dist/modules/config.js +6 -1
- package/dist/modules/constants.d.ts +13 -5
- package/dist/modules/constants.js +36 -5
- package/dist/modules/credit_runtime.d.ts +35 -5
- package/dist/modules/credit_runtime.js +219 -38
- package/dist/modules/dexbot_class.d.ts +23 -0
- package/dist/modules/dexbot_class.js +60 -17
- package/dist/modules/dexbot_cow_runtime.d.ts +62 -174
- package/dist/modules/dexbot_cow_runtime.js +350 -64
- package/dist/modules/dexbot_credential_client.d.ts +1 -16
- package/dist/modules/dexbot_credential_client.js +1 -1
- package/dist/modules/dexbot_fill_runtime.d.ts +2 -2
- package/dist/modules/dexbot_fill_runtime.js +16 -8
- package/dist/modules/dexbot_maintenance_runtime.d.ts +24 -81
- package/dist/modules/dexbot_maintenance_runtime.js +104 -70
- package/dist/modules/dexbot_startup_runtime.js +15 -2
- package/dist/modules/dexbot_state_recovery.js +17 -1
- package/dist/modules/key_store.d.ts +0 -5
- package/dist/modules/key_store.js +1 -1
- package/dist/modules/order/accounting.js +11 -11
- package/dist/modules/order/export.js +4 -4
- package/dist/modules/order/format.d.ts +15 -1
- package/dist/modules/order/format.js +19 -1
- package/dist/modules/order/genesis_policy.d.ts +1 -1
- package/dist/modules/order/genesis_policy.js +1 -1
- package/dist/modules/order/grid.d.ts +141 -12
- package/dist/modules/order/grid.js +666 -92
- package/dist/modules/order/grid_reconcile.d.ts +1 -1
- package/dist/modules/order/grid_reconcile.js +9 -8
- package/dist/modules/order/grid_reconcile_internal.js +61 -58
- package/dist/modules/order/index.d.ts +37 -9
- package/dist/modules/order/logger.js +2 -2
- package/dist/modules/order/manager.d.ts +10 -2
- package/dist/modules/order/manager.js +56 -31
- package/dist/modules/order/strategy.d.ts +2 -2
- package/dist/modules/order/strategy.js +51 -21
- package/dist/modules/order/sync_engine.js +22 -9
- package/dist/modules/order/utils/math.d.ts +101 -29
- package/dist/modules/order/utils/math.js +215 -84
- package/dist/modules/order/utils/order.d.ts +58 -58
- package/dist/modules/order/utils/order.js +135 -106
- package/dist/modules/order/utils/system.d.ts +193 -6
- package/dist/modules/order/utils/system.js +394 -31
- package/dist/modules/order/utils/validate.d.ts +1 -1
- package/dist/modules/order/utils/validate.js +71 -59
- package/dist/modules/runtime_settings.d.ts +1 -1
- package/dist/modules/runtime_settings.js +3 -3
- package/dist/modules/types.d.ts +55 -4
- package/dist/scripts/analyze-credit.js +44 -27
- package/dist/scripts/analyze-orders.d.ts +1 -1
- package/dist/scripts/analyze-orders.js +4 -4
- package/dist/scripts/diagnose-pool-history.js +35 -30
- package/dist/scripts/divergence-calc.js +6 -6
- package/dist/scripts/pnl.js +1 -1
- package/dist/scripts/rich_list.d.ts +18 -0
- package/dist/scripts/rich_list.js +461 -0
- package/dist/scripts/run-tests.js +80 -4
- package/dist/scripts/validate_bots.d.ts +1 -1
- package/dist/scripts/validate_bots.js +3 -3
- package/dist/unlock.d.ts +2 -1
- package/dist/unlock.js +11 -5
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -2
- package/docs/COW_INVARIANTS.md +12 -6
- package/docs/DEXBOT_COMPARISON.md +7 -7
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
- package/docs/GRID_PRICE_INVARIANT.md +3 -3
- package/docs/GRID_RECALCULATION.md +4 -1
- package/docs/GRID_RECONCILE.md +4 -4
- package/docs/LIFECYCLE.md +11 -11
- package/docs/LOGGING.md +30 -1
- package/docs/MPA_CREDIT_USAGE.md +11 -6
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +170 -12
- package/docs/README.md +3 -3
- package/docs/WORKFLOW.md +1 -0
- package/docs/architecture.md +62 -8
- package/docs/developer_guide.md +12 -3
- package/market_adapter/README.md +4 -4
- package/modules/README.md +1 -1
- package/package.json +2 -1
- package/scripts/README.md +59 -32
- package/tests/README.md +12 -3
|
@@ -13,12 +13,12 @@ const { readOpenOrdersWithMetaSafe } = chainOrdersModule;
|
|
|
13
13
|
import { BroadcastUncertainError as BroadcastUncertainErrorBinding } from './dexbot_credential_client.js';
|
|
14
14
|
const BroadcastUncertainError = BroadcastUncertainErrorBinding;
|
|
15
15
|
import * as orderUtils from './order/utils/order.js';
|
|
16
|
-
import { sleep, setLastFillPivot, fireStructuralResync } from './order/utils/system.js';
|
|
16
|
+
import { sleep, setLastFillPivot, fireStructuralResync, evaluateSpreadCorrectionReadiness, resolveLastFillGuardReference } from './order/utils/system.js';
|
|
17
17
|
const { buildCreateOrderArgs, buildCreateOpFingerprint, extractBatchOperationResults, formatUnmatchedChainOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, buildOutsideInPairGroups, isOrderPlaced, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, } = orderUtils;
|
|
18
18
|
import * as validate from './order/utils/validate.js';
|
|
19
19
|
const { validateCreateTargetSlots, evaluateCommit, hasExecutableActions, stampGapEvacuationRotation } = validate;
|
|
20
20
|
import * as math from './order/utils/math.js';
|
|
21
|
-
const { validateOrderSize, findCrossedOrder,
|
|
21
|
+
const { validateOrderSize, findCrossedOrder, sameGridLevel, isEvacuationRotationAllowed, isEvacuationSizeStillValid, getSellStartIdx, getPrecisionByOrderType, isSlotIndexInGapBand, getAssetFeesSafe, blockchainToFloat, floatToBlockchainInt, quantizeFloat } = math;
|
|
22
22
|
import { parseSlotIndex } from './order/utils/slot.js';
|
|
23
23
|
/**
|
|
24
24
|
* Re-verify a B-stamped gap-evacuation rotation against the LIVE committed
|
|
@@ -31,10 +31,20 @@ import { parseSlotIndex } from './order/utils/slot.js';
|
|
|
31
31
|
* keeps the plan-build authority (fail-open to the stamp, never to the guard).
|
|
32
32
|
*/
|
|
33
33
|
export function isEvacuationStampStillValid(liveBoundary, liveGapSlots, sourceId, destId, orderType) {
|
|
34
|
-
const b = Number(liveBoundary);
|
|
35
|
-
const g = Number(liveGapSlots);
|
|
36
34
|
if (orderType !== ORDER_TYPES.BUY && orderType !== ORDER_TYPES.SELL)
|
|
37
35
|
return false;
|
|
36
|
+
// Explicit null/undefined/'' guard BEFORE Number(): Number(null) === 0 and
|
|
37
|
+
// Number('') === 0 are finite and would read an unknown live geometry as
|
|
38
|
+
// boundary 0, falsely DISPROVING the stamp and downgrading the rotation to
|
|
39
|
+
// the live guard — the opposite of the documented "non-finite geometry
|
|
40
|
+
// keeps plan-build authority" contract (undefined already fails open via
|
|
41
|
+
// NaN). Same Number(null)===0 trap guarded elsewhere in the COW runtime.
|
|
42
|
+
if (liveBoundary === null || liveBoundary === undefined || liveBoundary === '')
|
|
43
|
+
return true;
|
|
44
|
+
if (liveGapSlots === null || liveGapSlots === undefined || liveGapSlots === '')
|
|
45
|
+
return true;
|
|
46
|
+
const b = Number(liveBoundary);
|
|
47
|
+
const g = Number(liveGapSlots);
|
|
38
48
|
if (!Number.isFinite(b) || !Number.isFinite(g) || g < 0)
|
|
39
49
|
return true;
|
|
40
50
|
const srcIdx = parseSlotIndex(sourceId);
|
|
@@ -49,7 +59,7 @@ export function isEvacuationStampStillValid(liveBoundary, liveGapSlots, sourceId
|
|
|
49
59
|
const dstInRail = orderType === ORDER_TYPES.SELL ? Number(dstIdx) >= sellStartIdx : Number(dstIdx) <= b;
|
|
50
60
|
return dstInRail;
|
|
51
61
|
}
|
|
52
|
-
function hasSlotPriceCollision(items, targetPrice,
|
|
62
|
+
function hasSlotPriceCollision(items, targetPrice, genesis, excludeId, predicate) {
|
|
53
63
|
for (const it of items) {
|
|
54
64
|
if (predicate && !predicate(it))
|
|
55
65
|
continue;
|
|
@@ -58,14 +68,11 @@ function hasSlotPriceCollision(items, targetPrice, precision, excludeId, predica
|
|
|
58
68
|
const p = it.order ? it.order.price : it.price;
|
|
59
69
|
if (p == null)
|
|
60
70
|
continue;
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
if (p === targetPrice)
|
|
67
|
-
return it;
|
|
68
|
-
}
|
|
71
|
+
// Grid-vs-grid: resolve both prices to their frozen ladder level (a
|
|
72
|
+
// low-precision asset must not collapse adjacent levels, and a price
|
|
73
|
+
// rounded a quantum off its level still resolves back).
|
|
74
|
+
if (sameGridLevel(Number(p), targetPrice, genesis))
|
|
75
|
+
return it;
|
|
69
76
|
}
|
|
70
77
|
return null;
|
|
71
78
|
}
|
|
@@ -451,7 +458,7 @@ async function deferUncertainBroadcastRead(bot, detail, suffix, resyncReason, re
|
|
|
451
458
|
// Fix #6 (docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md §2): an ambiguous/truncated chain read is
|
|
452
459
|
// node lag, not a missing order — the broadcast already succeeded. Previously every
|
|
453
460
|
// such read requested a structural resync, piling pending broadcasts (up to 14) and
|
|
454
|
-
// forcing a resync mid-broadcast (the
|
|
461
|
+
// forcing a resync mid-broadcast (the <bot> 06:43Z thrash). The pending-broadcast
|
|
455
462
|
// protection already prevents double-creates on the next cycle, so we keep it and
|
|
456
463
|
// only escalate to a structural resync once per cooldown window. The next clean
|
|
457
464
|
// read adopts any landed orders without the churn.
|
|
@@ -1750,10 +1757,115 @@ function logGridPriceInvariantSummary(bot, stats, site) {
|
|
|
1750
1757
|
}
|
|
1751
1758
|
catch { /* summary is best-effort */ }
|
|
1752
1759
|
}
|
|
1760
|
+
/**
|
|
1761
|
+
* P2 observability (advisory, never blocks): count a BUY emitted at or above
|
|
1762
|
+
* the last filled BUY pivot.
|
|
1763
|
+
*
|
|
1764
|
+
* This is the "re-stamp a just-filled BUY above the anchor" shape the
|
|
1765
|
+
* LAST-FILL-GUARD exists to block (`BUY > pivot*(1-half)`), so a counted
|
|
1766
|
+
* emission means the guard was bypassed (spread correction / stamped gap
|
|
1767
|
+
* evacuation) or the pivot was unjudgeable and the probe failed open. The
|
|
1768
|
+
* counter makes a bypass leak visible without changing placement policy —
|
|
1769
|
+
* the guard already owns enforcement, and turning this into a second gate
|
|
1770
|
+
* would re-introduce the reverted placement-guard class.
|
|
1771
|
+
*
|
|
1772
|
+
* Warns at most once per batch (keyed on `_currentCycleId`). Never throws.
|
|
1773
|
+
*
|
|
1774
|
+
* @returns {boolean} true when the emission was counted
|
|
1775
|
+
*/
|
|
1776
|
+
function recordRestampBuyAboveAnchor(bot, price, type) {
|
|
1777
|
+
try {
|
|
1778
|
+
if (type !== ORDER_TYPES.BUY)
|
|
1779
|
+
return false;
|
|
1780
|
+
if (bot?.manager?._lastFilledType !== ORDER_TYPES.BUY)
|
|
1781
|
+
return false;
|
|
1782
|
+
const pivot = Number(bot?.manager?._lastFilledPrice);
|
|
1783
|
+
const p = Number(price);
|
|
1784
|
+
if (!Number.isFinite(pivot) || pivot <= 0 || !Number.isFinite(p) || p <= 0)
|
|
1785
|
+
return false;
|
|
1786
|
+
// At or above the pivot is the re-stamp shape; a lower BUY is the
|
|
1787
|
+
// legitimate rotation target (I3) and is not counted.
|
|
1788
|
+
if (p < pivot)
|
|
1789
|
+
return false;
|
|
1790
|
+
if (bot._metrics)
|
|
1791
|
+
bot._metrics.restampBuyAboveAnchorCount = (bot._metrics.restampBuyAboveAnchorCount || 0) + 1;
|
|
1792
|
+
// Warn at most once per batch. Stored as a single scalar (not a
|
|
1793
|
+
// per-cycle map key) so the flag cannot accumulate unbounded keys on
|
|
1794
|
+
// the bot across cycles.
|
|
1795
|
+
const cycleId = bot?._currentCycleId ?? 'na';
|
|
1796
|
+
const botRecord = bot;
|
|
1797
|
+
if (botRecord._lastRestampWarnCycleId !== cycleId) {
|
|
1798
|
+
botRecord._lastRestampWarnCycleId = cycleId;
|
|
1799
|
+
bot?.manager?.logger?.log?.(`[RESTAMP-BUY] BUY emitted at ${Format.formatPrice6(p)} at/above the last filled BUY ` +
|
|
1800
|
+
`${Format.formatPrice6(pivot)} (guard bypass or unjudgeable pivot); counted, not blocked. ` +
|
|
1801
|
+
`(reported once per batch)`, 'warn');
|
|
1802
|
+
}
|
|
1803
|
+
return true;
|
|
1804
|
+
}
|
|
1805
|
+
catch {
|
|
1806
|
+
return false;
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
/**
|
|
1810
|
+
* Collect non-spread-correction CREATE/UPDATE destinations that sit inside
|
|
1811
|
+
* the plan's gap band.
|
|
1812
|
+
*
|
|
1813
|
+
* Mode C(a) SHADOW: the gap band is not unconditionally illegal — spread
|
|
1814
|
+
* correction legitimately places INTO it (the LAST-FILL-GUARD bypass exists
|
|
1815
|
+
* for exactly that) and gap evacuation moves an order OUT of it. Excluding
|
|
1816
|
+
* those origins leaves the genuinely suspicious set: a rail placement whose
|
|
1817
|
+
* destination geometry IS the spread. The result is counted/warned, never
|
|
1818
|
+
* blocked (see the guard call site for the revert-history rationale).
|
|
1819
|
+
*
|
|
1820
|
+
* Pure and never throws. A non-finite boundary/gap selects the empty set.
|
|
1821
|
+
*
|
|
1822
|
+
* @param {Array<Object>|null} actions - COW actions
|
|
1823
|
+
* @param {unknown} boundary - The PLAN's boundary (workingBoundary), not the committed one
|
|
1824
|
+
* @param {unknown} gapSlots - Gap slot count
|
|
1825
|
+
* @returns {string[]} destinations inside the gap band
|
|
1826
|
+
*/
|
|
1827
|
+
function collectGapBandPlacementShadowSlots(actions, boundary, gapSlots) {
|
|
1828
|
+
try {
|
|
1829
|
+
// Explicit null/empty guard BEFORE Number(): Number(null) === 0 and
|
|
1830
|
+
// Number('') === 0 would otherwise read an unknown boundary as slot 0
|
|
1831
|
+
// and select a real gap band around it (same trap that
|
|
1832
|
+
// buildCowResultFromPlan guards for workingBoundary).
|
|
1833
|
+
if (boundary === null || boundary === undefined || boundary === '')
|
|
1834
|
+
return [];
|
|
1835
|
+
if (gapSlots === null || gapSlots === undefined || gapSlots === '')
|
|
1836
|
+
return [];
|
|
1837
|
+
const b = Number(boundary);
|
|
1838
|
+
const g = Number(gapSlots);
|
|
1839
|
+
if (!Number.isFinite(b) || !Number.isFinite(g) || !Array.isArray(actions))
|
|
1840
|
+
return [];
|
|
1841
|
+
const out = [];
|
|
1842
|
+
for (const action of actions) {
|
|
1843
|
+
if (action?.type !== COW_ACTIONS.CREATE && action?.type !== COW_ACTIONS.UPDATE)
|
|
1844
|
+
continue;
|
|
1845
|
+
const origin = action?.origin;
|
|
1846
|
+
if (origin === COW_ORIGINS.SPREAD_CORRECTION || origin === COW_ORIGINS.GAP_EVACUATION)
|
|
1847
|
+
continue;
|
|
1848
|
+
const destId = String(action?.newGridId || action?.id || action?.order?.id || '');
|
|
1849
|
+
if (!destId)
|
|
1850
|
+
continue;
|
|
1851
|
+
const idx = parseSlotIndex(destId);
|
|
1852
|
+
if (idx === null || idx === undefined)
|
|
1853
|
+
continue;
|
|
1854
|
+
if (!isSlotIndexInGapBand(idx, b, g))
|
|
1855
|
+
continue;
|
|
1856
|
+
out.push(destId);
|
|
1857
|
+
}
|
|
1858
|
+
return out;
|
|
1859
|
+
}
|
|
1860
|
+
catch {
|
|
1861
|
+
return [];
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1753
1864
|
/**
|
|
1754
1865
|
* LAST-FILL-GUARD helper — pivot ± halfIncrement (replaces price-tolerance).
|
|
1755
|
-
* last fill @x with increment i
|
|
1756
|
-
*
|
|
1866
|
+
* last fill @x with increment i (blocked shapes): BUY > x*(1 - i/2/100),
|
|
1867
|
+
* SELL < x*(1 + i/2/100)
|
|
1868
|
+
* e.g. x=1000, i=0.5% => BUY > 997.5 and SELL < 1002.5 are blocked
|
|
1757
1869
|
* Cold (pivot null or lastType null) => disabled. Spread-correction CREATES
|
|
1758
1870
|
* bypass per-action (see broadcast sites); gap-evacuation rotation UPDATEs
|
|
1759
1871
|
* bypass only via the violation-reducing allowance (origin='gap-evacuation',
|
|
@@ -1794,6 +1906,44 @@ function isLastFillGuardBlocked(price, _size, type, lastPrice, lastType, increme
|
|
|
1794
1906
|
return { blocked: true, pivot, halfInc, threshold: sellThreshold };
|
|
1795
1907
|
return { blocked: false, pivot: null, halfInc, threshold: null };
|
|
1796
1908
|
}
|
|
1909
|
+
/**
|
|
1910
|
+
* Whether a spread-correction CREATE may bypass the LAST-FILL-GUARD.
|
|
1911
|
+
*
|
|
1912
|
+
* The bypass exists so gap repair can close even after a recent fill (the
|
|
1913
|
+
* correction is tightening the spread, not chasing it). It must not become a
|
|
1914
|
+
* licence to place THROUGH the market the bot last traded at:
|
|
1915
|
+
*
|
|
1916
|
+
* 1. A real fill pivot (`lastFillPivotSource === 'fill'`) is always honored —
|
|
1917
|
+
* no bypass. A sell below the last fill (or a buy above it) is the
|
|
1918
|
+
* issue-#31 adverse fill.
|
|
1919
|
+
* 2. A cold/book pivot is a heuristic (book seed) or absent, so the historical
|
|
1920
|
+
* fail-open bypass is kept — but only while the LOCAL snapshot is fresh.
|
|
1921
|
+
* A stale snapshot (known-unmatched chain orders, or an old sync) can hide
|
|
1922
|
+
* the real window edge, so the bypass is withheld and the guard applies.
|
|
1923
|
+
*
|
|
1924
|
+
* Exported for tests.
|
|
1925
|
+
* @param {Object} bot
|
|
1926
|
+
* @returns {boolean} True when the bypass may be used
|
|
1927
|
+
*/
|
|
1928
|
+
function isSpreadCorrectionBypassAllowed(bot) {
|
|
1929
|
+
const mgr = bot?.manager;
|
|
1930
|
+
if (!mgr)
|
|
1931
|
+
return true; // no manager state ⇒ nothing for the guard to protect
|
|
1932
|
+
// ONE verdict with the planner (evaluateSpreadCorrectionReadiness): the
|
|
1933
|
+
// bypass is licensed only when the snapshot is trusted AND no real FILL
|
|
1934
|
+
// reference exists. The LAST-FILL-GUARD is fill-based, so a live market
|
|
1935
|
+
// price (which only strengthens the planner's crossing floor) must not
|
|
1936
|
+
// change this decision. A real fill denies it; a stale or known-unmatched
|
|
1937
|
+
// snapshot denies it too (the guard applies instead). Fail-closed (deny
|
|
1938
|
+
// bypass) if the gate throws — never less safe than applying the guard.
|
|
1939
|
+
try {
|
|
1940
|
+
const readiness = evaluateSpreadCorrectionReadiness(mgr);
|
|
1941
|
+
return readiness.snapshotTrusted && readiness.fillMarketRef == null;
|
|
1942
|
+
}
|
|
1943
|
+
catch {
|
|
1944
|
+
return false;
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1797
1947
|
/**
|
|
1798
1948
|
* Refresh the LAST-FILL guard pivot from fills that arrived while the current
|
|
1799
1949
|
* batch was being planned or broadcast but have not been ingested yet.
|
|
@@ -2062,7 +2212,8 @@ function buildCowResultFromPlan(bot, plan) {
|
|
|
2062
2212
|
// Guard null/undefined explicitly: Number(null) === 0 would be treated as a
|
|
2063
2213
|
// valid finite boundary (index 0), silently biasing role classification.
|
|
2064
2214
|
const rawBoundary = plan?.boundaryIdx;
|
|
2065
|
-
|
|
2215
|
+
// Absent-aware: null/undefined/'' are unknown (NaN), never boundary 0.
|
|
2216
|
+
const requestedBoundary = Format.toKnownNumber(rawBoundary);
|
|
2066
2217
|
const workingBoundary = Number.isFinite(requestedBoundary)
|
|
2067
2218
|
? requestedBoundary
|
|
2068
2219
|
: bot.manager.boundaryIdx;
|
|
@@ -2074,8 +2225,16 @@ function buildCowResultFromPlan(bot, plan) {
|
|
|
2074
2225
|
const toWorkingHole = (slot) => {
|
|
2075
2226
|
try {
|
|
2076
2227
|
const idx = parseSlotIndex(slot?.id);
|
|
2077
|
-
|
|
2078
|
-
|
|
2228
|
+
// Explicit null/'' guard: the workingBoundary fallback (manager.boundaryIdx)
|
|
2229
|
+
// can be null, and Number(null) === 0 would misclassify slot 0 as a BUY
|
|
2230
|
+
// rail hole (same trap guarded for plan.boundaryIdx above).
|
|
2231
|
+
const b = (workingBoundary === null || workingBoundary === undefined || workingBoundary === '')
|
|
2232
|
+
? NaN
|
|
2233
|
+
: Number(workingBoundary);
|
|
2234
|
+
const rawGapSlots = bot?.manager?._gapSlots;
|
|
2235
|
+
const gapSlots = (rawGapSlots === null || rawGapSlots === undefined || rawGapSlots === '')
|
|
2236
|
+
? NaN
|
|
2237
|
+
: Number(rawGapSlots);
|
|
2079
2238
|
if (idx !== null && idx !== undefined && Number.isFinite(b) && Number.isFinite(gapSlots) && gapSlots >= 0) {
|
|
2080
2239
|
if (Number(idx) <= b)
|
|
2081
2240
|
return toRailHolePlaceholder(slot, ORDER_TYPES.BUY);
|
|
@@ -2585,10 +2744,16 @@ async function waitForCowBroadcastSingleFlight(bot, label) {
|
|
|
2585
2744
|
return false;
|
|
2586
2745
|
bot.manager.logger.log(`[COW] ${label}: a COW broadcast is already in flight; deferring this batch until it settles (prevents overlapping-broadcast commit collision).`, 'warn');
|
|
2587
2746
|
const waitDeadline = Date.now() + SINGLE_FLIGHT_MAX_WAIT_MS;
|
|
2747
|
+
// Test seam: a caller may shorten the poll cadence via
|
|
2748
|
+
// bot._cowSingleFlightPollMs. Production leaves it unset and keeps the
|
|
2749
|
+
// 250 ms rung, but tests that release the in-flight batch immediately must
|
|
2750
|
+
// not pay a full poll interval after the slot clears.
|
|
2751
|
+
const configuredPollMs = Number(bot._cowSingleFlightPollMs);
|
|
2752
|
+
const pollMs = Number.isFinite(configuredPollMs) && configuredPollMs > 0 ? configuredPollMs : 250;
|
|
2588
2753
|
while (bot._cowBroadcastInFlight) {
|
|
2589
2754
|
if (bot._shuttingDown || Date.now() > waitDeadline)
|
|
2590
2755
|
break;
|
|
2591
|
-
await sleep(
|
|
2756
|
+
await sleep(pollMs);
|
|
2592
2757
|
}
|
|
2593
2758
|
if (bot._shuttingDown) {
|
|
2594
2759
|
bot.manager.logger.log(`[COW] ${label}: shutdown began while waiting for the in-flight broadcast; aborting this batch.`, 'warn');
|
|
@@ -2667,7 +2832,7 @@ async function runPreBroadcastGuards(bot, cowResult) {
|
|
|
2667
2832
|
const chainOrderCandidates = Array.isArray(bot.manager?._lastUnmatchedChainOrders)
|
|
2668
2833
|
? bot.manager._lastUnmatchedChainOrders
|
|
2669
2834
|
: [];
|
|
2670
|
-
const createSlotValidation = validateCreateTargetSlots(actions, bot.manager?.orders, bot.manager?.assets, chainOrderCandidates);
|
|
2835
|
+
const createSlotValidation = validateCreateTargetSlots(actions, bot.manager?.orders, bot.manager?.assets, chainOrderCandidates, bot.manager?.config?.incrementPercent ?? null);
|
|
2671
2836
|
if (!createSlotValidation.isValid) {
|
|
2672
2837
|
for (const violation of createSlotValidation.violations) {
|
|
2673
2838
|
let reason;
|
|
@@ -2860,6 +3025,112 @@ async function runPreBroadcastGuards(bot, cowResult) {
|
|
|
2860
3025
|
}
|
|
2861
3026
|
};
|
|
2862
3027
|
}
|
|
3028
|
+
// MODE C(b) — pre-broadcast UPDATE-target existence check off the
|
|
3029
|
+
// slot->orderId map. A tracked order that is already gone on chain makes a
|
|
3030
|
+
// limit_order_update abort the broadcast chunk ("Order does not exist …
|
|
3031
|
+
// cannot update") and leaves a partially-applied grid. Re-reading the
|
|
3032
|
+
// referenced ids right before broadcast turns that into a clean
|
|
3033
|
+
// pre-broadcast refusal + structural resync, so nothing is half-applied.
|
|
3034
|
+
const updateTargetIds = new Set();
|
|
3035
|
+
for (const action of actions) {
|
|
3036
|
+
if (action?.type === COW_ACTIONS.UPDATE && action.orderId)
|
|
3037
|
+
updateTargetIds.add(String(action.orderId));
|
|
3038
|
+
}
|
|
3039
|
+
if (updateTargetIds.size > 0 && typeof chainOrders.batchReadOrders === 'function') {
|
|
3040
|
+
try {
|
|
3041
|
+
const readResult = await chainOrders.batchReadOrders([...updateTargetIds], 3000);
|
|
3042
|
+
const readMap = readResult;
|
|
3043
|
+
// Fail OPEN on a non-Map result (tests/other accessors): only an
|
|
3044
|
+
// authoritative map can prove an order gone.
|
|
3045
|
+
if (readMap && typeof readMap.get === 'function') {
|
|
3046
|
+
const missing = [];
|
|
3047
|
+
for (const id of updateTargetIds) {
|
|
3048
|
+
if (!readMap.get(id))
|
|
3049
|
+
missing.push(id);
|
|
3050
|
+
}
|
|
3051
|
+
if (missing.length > 0 && typeof chainOrders.readSingleOrder === 'function') {
|
|
3052
|
+
// Second, independent read before an absence decision: a
|
|
3053
|
+
// node that has not yet seen a freshly created order can
|
|
3054
|
+
// return null from the batch read. Re-reading each candidate
|
|
3055
|
+
// individually cancels the absence when the order is found;
|
|
3056
|
+
// a failed re-read must not manufacture an absence (fail
|
|
3057
|
+
// open), so only a read that returns an explicit null is
|
|
3058
|
+
// treated as confirming the gap.
|
|
3059
|
+
const stillMissing = [];
|
|
3060
|
+
for (const id of missing) {
|
|
3061
|
+
let present = true;
|
|
3062
|
+
try {
|
|
3063
|
+
present = Boolean(await chainOrders.readSingleOrder(id, 3000));
|
|
3064
|
+
}
|
|
3065
|
+
catch { /* failed re-verify must not manufacture an absence */ }
|
|
3066
|
+
if (!present)
|
|
3067
|
+
stillMissing.push(id);
|
|
3068
|
+
}
|
|
3069
|
+
missing.length = 0;
|
|
3070
|
+
missing.push(...stillMissing);
|
|
3071
|
+
}
|
|
3072
|
+
if (missing.length > 0) {
|
|
3073
|
+
bot.manager.logger.log(`[COW] Rejecting UPDATE batch pre-broadcast: ${missing.length} target(s) missing on chain ` +
|
|
3074
|
+
`(${missing.slice(0, 8).join(', ')}${missing.length > 8 ? ', …' : ''}); ` +
|
|
3075
|
+
`grid/chain existence divergence — structural resync required`, 'error');
|
|
3076
|
+
popPushedWorkingGrid(bot, cowResult);
|
|
3077
|
+
await requestStructuralResync(bot, 'pre-broadcast update target missing on chain', { missingUpdateOrderIds: missing });
|
|
3078
|
+
return {
|
|
3079
|
+
proceed: false,
|
|
3080
|
+
result: {
|
|
3081
|
+
executed: false,
|
|
3082
|
+
aborted: true,
|
|
3083
|
+
reason: 'UPDATE_TARGET_MISSING',
|
|
3084
|
+
missingUpdateOrderIds: missing,
|
|
3085
|
+
hadRotation: false
|
|
3086
|
+
}
|
|
3087
|
+
};
|
|
3088
|
+
}
|
|
3089
|
+
}
|
|
3090
|
+
}
|
|
3091
|
+
catch (existenceErr) {
|
|
3092
|
+
// A failed/foreign read must never block a legitimate broadcast;
|
|
3093
|
+
// the chain's own rejection remains the backstop.
|
|
3094
|
+
bot.manager.logger.log(`[COW] Pre-broadcast UPDATE existence check failed (${getErrorMessage(existenceErr)}); ` +
|
|
3095
|
+
`proceeding (chain rejection remains the backstop)`, 'debug');
|
|
3096
|
+
}
|
|
3097
|
+
}
|
|
3098
|
+
// MODE C(a) — gap-band placement SHADOW check (observability + summary,
|
|
3099
|
+
// no placement change). A non-spread-correction CREATE/UPDATE whose
|
|
3100
|
+
// destination sits inside the plan's gap band is the Mode-C geometry that
|
|
3101
|
+
// the reverted P1/P2 cancellation nets used to mop up; enforcement is
|
|
3102
|
+
// deliberately NOT done here because spread correction legitimately places
|
|
3103
|
+
// INTO the band (the LAST-FILL-GUARD bypass exists for exactly that) and a
|
|
3104
|
+
// hard reject would re-open the P1-e2898e51 regression class. Count + warn
|
|
3105
|
+
// so the leak is measurable before any policy change.
|
|
3106
|
+
try {
|
|
3107
|
+
const planBoundaryValue = cowResult?.workingBoundary;
|
|
3108
|
+
const planBoundaryRaw = (planBoundaryValue === null || planBoundaryValue === undefined || planBoundaryValue === '')
|
|
3109
|
+
? NaN
|
|
3110
|
+
: Number(planBoundaryValue);
|
|
3111
|
+
// Fall back to the committed boundary only when it is itself known:
|
|
3112
|
+
// Number(null) === 0 and Number('') === 0 must not silently become
|
|
3113
|
+
// slot 0 (same trap the helper guards).
|
|
3114
|
+
const managerBoundaryRaw = bot.manager?.boundaryIdx;
|
|
3115
|
+
const shadowBoundary = Number.isFinite(planBoundaryRaw)
|
|
3116
|
+
? planBoundaryRaw
|
|
3117
|
+
: (managerBoundaryRaw != null && managerBoundaryRaw !== '' ? Number(managerBoundaryRaw) : NaN);
|
|
3118
|
+
// Absent-aware gap: Number(null) === 0 would defeat the helper's own
|
|
3119
|
+
// null guard by passing a collapsed 0 band before the helper sees it.
|
|
3120
|
+
const shadowGapSlots = Format.toKnownNumber(bot.manager?._gapSlots);
|
|
3121
|
+
const shadowSlots = collectGapBandPlacementShadowSlots(actions, shadowBoundary, shadowGapSlots);
|
|
3122
|
+
if (shadowSlots.length > 0) {
|
|
3123
|
+
if (bot._metrics) {
|
|
3124
|
+
bot._metrics.gapBandPlacementShadowCount =
|
|
3125
|
+
(bot._metrics.gapBandPlacementShadowCount || 0) + shadowSlots.length;
|
|
3126
|
+
}
|
|
3127
|
+
bot.manager.logger.log(`[COW-GAP-BAND] shadow: ${shadowSlots.length} non-spread-correction placement(s) ` +
|
|
3128
|
+
`inside the plan's gap band (boundary ${shadowBoundary}, gap ${shadowGapSlots}): ` +
|
|
3129
|
+
`${shadowSlots.slice(0, 8).join(', ')}${shadowSlots.length > 8 ? ', …' : ''} ` +
|
|
3130
|
+
`— counted for observability, NOT blocked`, 'warn');
|
|
3131
|
+
}
|
|
3132
|
+
}
|
|
3133
|
+
catch { /* shadow check must never break a batch */ }
|
|
2863
3134
|
// Crossing-check candidate set (master + pending-broadcast + unmatched
|
|
2864
3135
|
// chain orders). Built after the batch-level pending/unmatched guards so
|
|
2865
3136
|
// it reflects any sync they triggered.
|
|
@@ -3112,8 +3383,12 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3112
3383
|
// whose freeze picked up a pre-freeze queued fill look "moved" at the
|
|
3113
3384
|
// gate — a spurious warn plus a redundant full re-check against the
|
|
3114
3385
|
// identical pivot.
|
|
3115
|
-
|
|
3116
|
-
|
|
3386
|
+
// Same effective reference the per-action guard judges against (live
|
|
3387
|
+
// pivot, else the bot-scoped market fill) so the freeze cannot run cold
|
|
3388
|
+
// while the guard still blocks.
|
|
3389
|
+
const frozenRef = resolveLastFillGuardReference(bot.manager);
|
|
3390
|
+
const frozenPivotAtBatchStart = frozenRef.price;
|
|
3391
|
+
const frozenTypeAtBatchStart = frozenRef.type;
|
|
3117
3392
|
for (const action of actions) {
|
|
3118
3393
|
if (action.type === COW_ACTIONS.CANCEL) {
|
|
3119
3394
|
try {
|
|
@@ -3167,8 +3442,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3167
3442
|
`emitting planned price (live slot price is derived from genesis and is not authoritative).`, 'warn');
|
|
3168
3443
|
}
|
|
3169
3444
|
const createPrice = effectiveOrder.price;
|
|
3170
|
-
const
|
|
3171
|
-
const batchCollision = hasSlotPriceCollision(opContexts, createPrice, precision, order.id, (ctx) => ctx.kind === 'create' && ctx.order?.price != null);
|
|
3445
|
+
const batchCollision = hasSlotPriceCollision(opContexts, createPrice, bot.manager._genesis, order.id, (ctx) => ctx.kind === 'create' && ctx.order?.price != null);
|
|
3172
3446
|
if (batchCollision) {
|
|
3173
3447
|
bot.manager.logger.log(`[COW] Skipping CREATE for ${order.id} at ${Format.formatPrice6(createPrice)}: ` +
|
|
3174
3448
|
`same-batch CREATE ${batchCollision.id} already at ` +
|
|
@@ -3206,8 +3480,9 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3206
3480
|
try {
|
|
3207
3481
|
const actionOrigin = action?.origin;
|
|
3208
3482
|
const batchOrigin = cowResult?.origin;
|
|
3209
|
-
const isCorrectionCreate = actionOrigin === COW_ORIGINS.SPREAD_CORRECTION
|
|
3210
|
-
|| (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION)
|
|
3483
|
+
const isCorrectionCreate = (actionOrigin === COW_ORIGINS.SPREAD_CORRECTION
|
|
3484
|
+
|| (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION))
|
|
3485
|
+
&& isSpreadCorrectionBypassAllowed(bot);
|
|
3211
3486
|
if (!isCorrectionCreate) {
|
|
3212
3487
|
const { check, refreshed } = runLastFillGuardCheck(bot, createPrice, order.size, order.type, lastFillGuardStats, true);
|
|
3213
3488
|
if (refreshed)
|
|
@@ -3238,6 +3513,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3238
3513
|
skippedCreateSlotIds.add(order.id);
|
|
3239
3514
|
continue;
|
|
3240
3515
|
}
|
|
3516
|
+
recordRestampBuyAboveAnchor(bot, createPrice, order.type);
|
|
3241
3517
|
const buildResult = await chainOrders.buildCreateOrderOp(bot.account, args.amountToSell, args.sellAssetId, args.minToReceive, args.receiveAssetId, null);
|
|
3242
3518
|
if (!buildResult) {
|
|
3243
3519
|
bot.manager.logger.log(`Skipping create op for ${action.id}: amounts would round to 0 on blockchain`, 'warn');
|
|
@@ -3379,8 +3655,10 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3379
3655
|
let bypassedEvacuation = false;
|
|
3380
3656
|
const rotationOrigin = action?.origin;
|
|
3381
3657
|
if (rotationOrigin === COW_ORIGINS.GAP_EVACUATION) {
|
|
3382
|
-
|
|
3383
|
-
|
|
3658
|
+
// Absent-aware: a legacy stamp carrying null/''
|
|
3659
|
+
// geometry must not read as boundary 0 / gap 0.
|
|
3660
|
+
const frozenB = Format.toKnownNumber(action?.evacBoundary);
|
|
3661
|
+
const frozenG = Format.toKnownNumber(action?.evacGapSlots);
|
|
3384
3662
|
let stampUsable = Number.isFinite(frozenB) && Number.isFinite(frozenG);
|
|
3385
3663
|
if (stampUsable) {
|
|
3386
3664
|
// Stale-stamp check: the stamp froze PLAN-BUILD
|
|
@@ -3509,6 +3787,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3509
3787
|
skippedUpdateSlotIds.add(action.newGridId);
|
|
3510
3788
|
continue;
|
|
3511
3789
|
}
|
|
3790
|
+
recordRestampBuyAboveAnchor(bot, newPrice, orderType);
|
|
3512
3791
|
const buildResult = await chainOrders.buildUpdateOrderOp(bot.account, action.orderId, { amountToSell, minToReceive, newPrice, orderType }, masterOrder.rawOnChain || null);
|
|
3513
3792
|
if (!buildResult) {
|
|
3514
3793
|
skippedUpdateCount++;
|
|
@@ -3590,15 +3869,14 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3590
3869
|
bot.manager.logger.log(`[COW] CREATE fallback for ${action.id} rejected by size validation: ${sizeCheck.reason}`, 'warn');
|
|
3591
3870
|
}
|
|
3592
3871
|
else if (fbType && fbSize > 0 && fbPrice > 0) {
|
|
3593
|
-
const
|
|
3594
|
-
const fbCollision = hasSlotPriceCollision([...bot.manager.orders.values()], fbPrice, fbPrecision, targetSlotId, isOrderPlaced);
|
|
3872
|
+
const fbCollision = hasSlotPriceCollision([...bot.manager.orders.values()], fbPrice, bot.manager._genesis, targetSlotId, isOrderPlaced);
|
|
3595
3873
|
if (fbCollision) {
|
|
3596
3874
|
bot.manager.logger.log(`[COW] Skipping CREATE fallback for ${targetSlotId} at ${Format.formatPrice6(fbPrice)}: ` +
|
|
3597
3875
|
`existing placed order ${fbCollision.id} (${fbCollision.orderId}) ` +
|
|
3598
3876
|
`already at price ${Format.formatPrice6(Number(fbCollision.price))}.`, 'warn');
|
|
3599
3877
|
continue;
|
|
3600
3878
|
}
|
|
3601
|
-
const fbBatchCollision = hasSlotPriceCollision(opContexts, fbPrice,
|
|
3879
|
+
const fbBatchCollision = hasSlotPriceCollision(opContexts, fbPrice, bot.manager._genesis, targetSlotId, (ctx) => ctx.kind === 'create');
|
|
3602
3880
|
if (fbBatchCollision) {
|
|
3603
3881
|
bot.manager.logger.log(`[COW] Skipping CREATE fallback for ${targetSlotId} at ${Format.formatPrice6(fbPrice)}: ` +
|
|
3604
3882
|
`same-batch CREATE ${fbBatchCollision.id} already at ` +
|
|
@@ -3644,6 +3922,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3644
3922
|
if (!recordGridPriceInvariantCheck(bot, targetSlotId, fbPrice, gridPriceInvariantStats, 'CREATE-FALLBACK')) {
|
|
3645
3923
|
continue;
|
|
3646
3924
|
}
|
|
3925
|
+
recordRestampBuyAboveAnchor(bot, fbPrice, fbType);
|
|
3647
3926
|
const fbResult = await chainOrders.buildCreateOrderOp(bot.account, fbArgs.amountToSell, fbArgs.sellAssetId, fbArgs.minToReceive, fbArgs.receiveAssetId, null);
|
|
3648
3927
|
if (fbResult) {
|
|
3649
3928
|
operations.push(fbResult.op);
|
|
@@ -3764,8 +4043,12 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3764
4043
|
const gateGuarded = finalGateStats.checked + finalGateStats.bypassed;
|
|
3765
4044
|
const totalGuarded = lastFillGuardStats.checked + lastFillGuardStats.bypassed + gateGuarded;
|
|
3766
4045
|
if (totalGuarded > 0) {
|
|
3767
|
-
|
|
3768
|
-
|
|
4046
|
+
// Same effective reference the guard judged against (live pivot
|
|
4047
|
+
// else the bot-scoped market fill) so the summary cannot report
|
|
4048
|
+
// disabled(cold) while placements were actually blocked.
|
|
4049
|
+
const sumRef = resolveLastFillGuardReference(bot.manager);
|
|
4050
|
+
const sumPivotRaw = sumRef.price;
|
|
4051
|
+
const sumType = sumRef.type;
|
|
3769
4052
|
const sumInc = resolveLastFillGuardIncrement(bot);
|
|
3770
4053
|
const cold = sumPivotRaw == null || !Number.isFinite(Number(sumPivotRaw)) || sumType == null;
|
|
3771
4054
|
const batchOrigin = cowResult?.origin;
|
|
@@ -4183,6 +4466,10 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
4183
4466
|
// balance reflects the on-chain cost (shared with the
|
|
4184
4467
|
// refused-commit paths via recoverRefusedCommit).
|
|
4185
4468
|
return await recoverRefusedCommit(bot, chainOrders, '[COW][UNCERTAIN]', { placedContexts: opContexts, polledCreateIds: confirmation.confirmedChainIds }, opContexts, effectiveBoundary, {
|
|
4469
|
+
// Poll-confirmed SUCCESS: the commit was accepted;
|
|
4470
|
+
// this funnel is only reused for chain adoption +
|
|
4471
|
+
// fee deduction, so it must not count as a refusal.
|
|
4472
|
+
refusedCommit: false,
|
|
4186
4473
|
extraReturn: { commitRefused: false },
|
|
4187
4474
|
successReturn: { executed: true, hadRotation: false, uncertainResolved: true },
|
|
4188
4475
|
failureResyncReason: 'poll-confirmed commit (chain adoption unavailable)',
|
|
@@ -4475,6 +4762,18 @@ async function persistGridAndClearPendingBroadcasts(bot, logPrefix) {
|
|
|
4475
4762
|
* @returns {Promise<Object>} The commit-refused return object
|
|
4476
4763
|
*/
|
|
4477
4764
|
async function recoverRefusedCommit(bot, chainOrders, logPrefix, adoptOpts, contexts, workingBoundary, opts = {}) {
|
|
4765
|
+
// P2 observability: count genuine commit refusals at this single funnel (so
|
|
4766
|
+
// the three call sites cannot double-count). This function is ALSO the
|
|
4767
|
+
// shared funnel for the poll-confirmed SUCCESS path (chain adoption + fee
|
|
4768
|
+
// deduction), which passes `refusedCommit: false` because the commit was
|
|
4769
|
+
// accepted — counting it would overstate the refusal signal. Never gates
|
|
4770
|
+
// behavior.
|
|
4771
|
+
try {
|
|
4772
|
+
if (opts.refusedCommit !== false && bot._metrics) {
|
|
4773
|
+
bot._metrics.refusedCommitCount = (bot._metrics.refusedCommitCount || 0) + 1;
|
|
4774
|
+
}
|
|
4775
|
+
}
|
|
4776
|
+
catch { /* metrics are best-effort */ }
|
|
4478
4777
|
const extraReturn = (opts.extraReturn ?? {});
|
|
4479
4778
|
const successReturn = opts.successReturn;
|
|
4480
4779
|
const failureResyncReason = (opts.failureResyncReason ?? 'commit refused after broadcast (chain adoption unavailable)');
|
|
@@ -4590,8 +4889,12 @@ function runLastFillGuardCheck(bot, price, size, type, stats, skipRefresh = fals
|
|
|
4590
4889
|
}
|
|
4591
4890
|
catch { /* best-effort */ }
|
|
4592
4891
|
}
|
|
4593
|
-
|
|
4594
|
-
|
|
4892
|
+
// Effective reference: the live pivot when armed, else the bot-scoped
|
|
4893
|
+
// market fill that survives a grid regeneration. Without the fallback a
|
|
4894
|
+
// rebuild un-arms the guard until the next fill.
|
|
4895
|
+
const lastRef = resolveLastFillGuardReference(bot.manager);
|
|
4896
|
+
const lastPrice = lastRef.price;
|
|
4897
|
+
const lastType = lastRef.type;
|
|
4595
4898
|
const inc = resolveLastFillGuardIncrement(bot);
|
|
4596
4899
|
// Validate the pivot onto the ladder before use (see resolveOnGridPivot).
|
|
4597
4900
|
// Reported once per probe at warn when the raw pivot was NOT a grid level:
|
|
@@ -4718,8 +5021,9 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
4718
5021
|
const queueDepthAfter = Array.isArray(bot?._incomingFillQueue)
|
|
4719
5022
|
? bot._incomingFillQueue.length
|
|
4720
5023
|
: null;
|
|
4721
|
-
const
|
|
4722
|
-
const
|
|
5024
|
+
const liveRef = resolveLastFillGuardReference(bot.manager);
|
|
5025
|
+
const livePivot = Number(liveRef.price);
|
|
5026
|
+
const liveType = liveRef.type;
|
|
4723
5027
|
const liveCold = !Number.isFinite(livePivot) || liveType == null;
|
|
4724
5028
|
// No-op fast path: pivot unchanged (or uncomparable) since the freeze.
|
|
4725
5029
|
// frozenCold + liveCold: guard stayed disabled — nothing to re-check.
|
|
@@ -4760,7 +5064,7 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
4760
5064
|
const dropIdx = new Set();
|
|
4761
5065
|
const dropped = [];
|
|
4762
5066
|
const inc = resolveLastFillGuardIncrement(bot);
|
|
4763
|
-
const onGrid = resolveOnGridPivot(bot.manager,
|
|
5067
|
+
const onGrid = resolveOnGridPivot(bot.manager, liveRef.price);
|
|
4764
5068
|
for (let i = 0; i < opContexts.length; i++) {
|
|
4765
5069
|
const ctx = opContexts[i];
|
|
4766
5070
|
if (!ctx || ctx.kind === 'cancel' || ctx.kind === 'size-update')
|
|
@@ -4779,8 +5083,9 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
4779
5083
|
// Spread-correction CREATE bypass (mirrors the build loop:
|
|
4780
5084
|
// per-action origin, batch origin as back-compat fallback).
|
|
4781
5085
|
const actionOrigin = action?.origin;
|
|
4782
|
-
if (actionOrigin === COW_ORIGINS.SPREAD_CORRECTION
|
|
4783
|
-
|| (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION))
|
|
5086
|
+
if ((actionOrigin === COW_ORIGINS.SPREAD_CORRECTION
|
|
5087
|
+
|| (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION))
|
|
5088
|
+
&& isSpreadCorrectionBypassAllowed(bot)) {
|
|
4784
5089
|
if (stats)
|
|
4785
5090
|
stats.bypassed = (Number(stats.bypassed) || 0) + 1;
|
|
4786
5091
|
continue;
|
|
@@ -4833,8 +5138,8 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
4833
5138
|
// especially not on an op the build loop already allowed.
|
|
4834
5139
|
const rotOrigin = action?.origin;
|
|
4835
5140
|
if (rotOrigin === COW_ORIGINS.GAP_EVACUATION
|
|
4836
|
-
&& Number.isFinite(
|
|
4837
|
-
&& Number.isFinite(
|
|
5141
|
+
&& Number.isFinite(Format.toKnownNumber(action?.evacBoundary))
|
|
5142
|
+
&& Number.isFinite(Format.toKnownNumber(action?.evacGapSlots))) {
|
|
4838
5143
|
if (stats)
|
|
4839
5144
|
stats.bypassed = (Number(stats.bypassed) || 0) + 1;
|
|
4840
5145
|
continue;
|
|
@@ -5222,43 +5527,24 @@ async function processBatchResults(bot, result, opContexts) {
|
|
|
5222
5527
|
updateOperationCount
|
|
5223
5528
|
};
|
|
5224
5529
|
}
|
|
5225
|
-
export { isLastFillGuardBlocked, resolveOnGridPivot, checkGridPriceInvariant, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast,
|
|
5530
|
+
export { isSpreadCorrectionBypassAllowed, isLastFillGuardBlocked, resolveOnGridPivot, checkGridPriceInvariant, recordRestampBuyAboveAnchor, collectGapBandPlacementShadowSlots, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast, executeWithRetryOnUncertain, executeChunkedWithRetryOnUncertain, formatPartialBroadcastSummary, buildActionsFromPlan, buildCowResultFromPlan, applyRotationTransitionsToWorkingGrid, updateOrdersOnChainBatchCOW, processBatchResults, adoptPlacedBatchFromChain, resolveRefillBoundaryHold, toRefillSlotIdSet, trackBoundaryHold };
|
|
5226
5531
|
// Exported for regression tests (issue #23 sibling): the uncertain-broadcast
|
|
5227
5532
|
// discard path must never drop a placement silently when master lost the slot.
|
|
5228
5533
|
export { restoreDiscardedCreates };
|
|
5229
5534
|
export default {
|
|
5230
5535
|
buildOutsideInPairGroupsForOrders,
|
|
5231
5536
|
buildOutsideInPairGroupsForCreateEntries,
|
|
5232
|
-
extractOperationResults,
|
|
5233
|
-
findMissingCreateResultContexts,
|
|
5234
5537
|
markMissingCreateResultsAsStructuralBlocker,
|
|
5235
5538
|
formatUnmatchedChainOrderForLog,
|
|
5236
5539
|
recordPendingBroadcast,
|
|
5237
5540
|
clearPendingBroadcasts,
|
|
5238
|
-
clearPendingBroadcastsForSlots,
|
|
5239
|
-
popPushedWorkingGrid,
|
|
5240
|
-
buildChainOrderFingerprint,
|
|
5241
|
-
normalizeChainOrderForPendingMatch,
|
|
5242
5541
|
findChainOrderForSlot,
|
|
5243
5542
|
reconcileAfterUncertainBroadcast,
|
|
5244
|
-
reconcileAfterUncertainBroadcastImpl,
|
|
5245
|
-
shouldExecuteCreatePairMode,
|
|
5246
5543
|
executeWithRetryOnUncertain,
|
|
5247
5544
|
executeChunkedWithRetryOnUncertain,
|
|
5248
|
-
|
|
5249
|
-
validateOperationFunds,
|
|
5250
|
-
resolveIdealSizeForValidation,
|
|
5251
|
-
validateOrderSizeForExecution,
|
|
5252
|
-
buildActionsFromPlan,
|
|
5545
|
+
popPushedWorkingGrid,
|
|
5253
5546
|
buildCowResultFromPlan,
|
|
5254
|
-
restoreSkippedUpdateSlotsInWorkingGrid,
|
|
5255
|
-
resolveRefillBoundaryHold,
|
|
5256
|
-
toRefillSlotIdSet,
|
|
5257
|
-
trackBoundaryHold,
|
|
5258
|
-
applyRotationTransitionsToWorkingGrid,
|
|
5259
|
-
pollChainForConfirmation,
|
|
5260
5547
|
updateOrdersOnChainBatchCOW,
|
|
5261
5548
|
processBatchResults,
|
|
5262
|
-
runFinalPivotGate,
|
|
5263
5549
|
};
|
|
5264
5550
|
//# sourceMappingURL=dexbot_cow_runtime.js.map
|