dexbot 1.6.13 → 1.6.14
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 +32 -0
- package/README.md +2 -2
- 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 +25 -25
- package/dist/modules/account_bots.d.ts +7 -6
- package/dist/modules/account_bots.js +10 -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/bot_defaults.d.ts +16 -2
- package/dist/modules/bot_defaults.js +34 -8
- package/dist/modules/bot_settings.d.ts +4 -0
- package/dist/modules/bot_settings.js +55 -21
- package/dist/modules/config.js +6 -1
- package/dist/modules/constants.d.ts +7 -5
- package/dist/modules/constants.js +12 -5
- package/dist/modules/dexbot_class.d.ts +5 -0
- package/dist/modules/dexbot_class.js +8 -3
- package/dist/modules/dexbot_cow_runtime.d.ts +62 -174
- package/dist/modules/dexbot_cow_runtime.js +331 -46
- 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 +1 -1
- package/dist/modules/dexbot_fill_runtime.js +12 -1
- package/dist/modules/dexbot_maintenance_runtime.d.ts +18 -80
- package/dist/modules/dexbot_maintenance_runtime.js +57 -68
- package/dist/modules/dexbot_startup_runtime.js +12 -0
- package/dist/modules/dexbot_state_recovery.js +16 -0
- 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 +2 -2
- 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 +23 -11
- package/dist/modules/order/grid.js +383 -51
- package/dist/modules/order/grid_reconcile.d.ts +1 -1
- package/dist/modules/order/grid_reconcile.js +5 -5
- package/dist/modules/order/grid_reconcile_internal.js +48 -40
- package/dist/modules/order/index.d.ts +34 -8
- package/dist/modules/order/logger.js +2 -2
- package/dist/modules/order/manager.d.ts +9 -2
- package/dist/modules/order/manager.js +58 -24
- package/dist/modules/order/strategy.d.ts +2 -2
- package/dist/modules/order/strategy.js +51 -21
- package/dist/modules/order/sync_engine.js +4 -0
- package/dist/modules/order/utils/math.d.ts +3 -3
- package/dist/modules/order/utils/math.js +38 -27
- package/dist/modules/order/utils/order.d.ts +58 -58
- package/dist/modules/order/utils/order.js +119 -102
- package/dist/modules/order/utils/system.d.ts +193 -6
- package/dist/modules/order/utils/system.js +392 -29
- package/dist/modules/order/utils/validate.js +26 -4
- package/dist/modules/runtime_settings.d.ts +1 -1
- package/dist/modules/runtime_settings.js +3 -3
- package/dist/modules/types.d.ts +48 -4
- package/dist/scripts/analyze-orders.d.ts +1 -1
- package/dist/scripts/analyze-orders.js +4 -4
- package/dist/scripts/divergence-calc.js +6 -6
- package/dist/scripts/validate_bots.d.ts +1 -1
- package/dist/scripts/validate_bots.js +3 -3
- package/dist/unlock.js +7 -2
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -2
- package/docs/COW_INVARIANTS.md +6 -6
- package/docs/DEXBOT_COMPARISON.md +5 -5
- package/docs/EVOLUTION.md +8 -7
- 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 +14 -0
- package/docs/MPA_CREDIT_USAGE.md +1 -1
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +12 -4
- package/docs/README.md +3 -3
- package/docs/architecture.md +6 -6
- package/docs/developer_guide.md +7 -2
- package/package.json +1 -1
- package/tests/README.md +1 -1
|
@@ -13,7 +13,7 @@ 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;
|
|
@@ -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);
|
|
@@ -1750,10 +1760,115 @@ function logGridPriceInvariantSummary(bot, stats, site) {
|
|
|
1750
1760
|
}
|
|
1751
1761
|
catch { /* summary is best-effort */ }
|
|
1752
1762
|
}
|
|
1763
|
+
/**
|
|
1764
|
+
* P2 observability (advisory, never blocks): count a BUY emitted at or above
|
|
1765
|
+
* the last filled BUY pivot.
|
|
1766
|
+
*
|
|
1767
|
+
* This is the "re-stamp a just-filled BUY above the anchor" shape the
|
|
1768
|
+
* LAST-FILL-GUARD exists to block (`BUY > pivot*(1-half)`), so a counted
|
|
1769
|
+
* emission means the guard was bypassed (spread correction / stamped gap
|
|
1770
|
+
* evacuation) or the pivot was unjudgeable and the probe failed open. The
|
|
1771
|
+
* counter makes a bypass leak visible without changing placement policy —
|
|
1772
|
+
* the guard already owns enforcement, and turning this into a second gate
|
|
1773
|
+
* would re-introduce the reverted placement-guard class.
|
|
1774
|
+
*
|
|
1775
|
+
* Warns at most once per batch (keyed on `_currentCycleId`). Never throws.
|
|
1776
|
+
*
|
|
1777
|
+
* @returns {boolean} true when the emission was counted
|
|
1778
|
+
*/
|
|
1779
|
+
function recordRestampBuyAboveAnchor(bot, price, type) {
|
|
1780
|
+
try {
|
|
1781
|
+
if (type !== ORDER_TYPES.BUY)
|
|
1782
|
+
return false;
|
|
1783
|
+
if (bot?.manager?._lastFilledType !== ORDER_TYPES.BUY)
|
|
1784
|
+
return false;
|
|
1785
|
+
const pivot = Number(bot?.manager?._lastFilledPrice);
|
|
1786
|
+
const p = Number(price);
|
|
1787
|
+
if (!Number.isFinite(pivot) || pivot <= 0 || !Number.isFinite(p) || p <= 0)
|
|
1788
|
+
return false;
|
|
1789
|
+
// At or above the pivot is the re-stamp shape; a lower BUY is the
|
|
1790
|
+
// legitimate rotation target (I3) and is not counted.
|
|
1791
|
+
if (p < pivot)
|
|
1792
|
+
return false;
|
|
1793
|
+
if (bot._metrics)
|
|
1794
|
+
bot._metrics.restampBuyAboveAnchorCount = (bot._metrics.restampBuyAboveAnchorCount || 0) + 1;
|
|
1795
|
+
// Warn at most once per batch. Stored as a single scalar (not a
|
|
1796
|
+
// per-cycle map key) so the flag cannot accumulate unbounded keys on
|
|
1797
|
+
// the bot across cycles.
|
|
1798
|
+
const cycleId = bot?._currentCycleId ?? 'na';
|
|
1799
|
+
const botRecord = bot;
|
|
1800
|
+
if (botRecord._lastRestampWarnCycleId !== cycleId) {
|
|
1801
|
+
botRecord._lastRestampWarnCycleId = cycleId;
|
|
1802
|
+
bot?.manager?.logger?.log?.(`[RESTAMP-BUY] BUY emitted at ${Format.formatPrice6(p)} at/above the last filled BUY ` +
|
|
1803
|
+
`${Format.formatPrice6(pivot)} (guard bypass or unjudgeable pivot); counted, not blocked. ` +
|
|
1804
|
+
`(reported once per batch)`, 'warn');
|
|
1805
|
+
}
|
|
1806
|
+
return true;
|
|
1807
|
+
}
|
|
1808
|
+
catch {
|
|
1809
|
+
return false;
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
/**
|
|
1813
|
+
* Collect non-spread-correction CREATE/UPDATE destinations that sit inside
|
|
1814
|
+
* the plan's gap band.
|
|
1815
|
+
*
|
|
1816
|
+
* Mode C(a) SHADOW: the gap band is not unconditionally illegal — spread
|
|
1817
|
+
* correction legitimately places INTO it (the LAST-FILL-GUARD bypass exists
|
|
1818
|
+
* for exactly that) and gap evacuation moves an order OUT of it. Excluding
|
|
1819
|
+
* those origins leaves the genuinely suspicious set: a rail placement whose
|
|
1820
|
+
* destination geometry IS the spread. The result is counted/warned, never
|
|
1821
|
+
* blocked (see the guard call site for the revert-history rationale).
|
|
1822
|
+
*
|
|
1823
|
+
* Pure and never throws. A non-finite boundary/gap selects the empty set.
|
|
1824
|
+
*
|
|
1825
|
+
* @param {Array<Object>|null} actions - COW actions
|
|
1826
|
+
* @param {unknown} boundary - The PLAN's boundary (workingBoundary), not the committed one
|
|
1827
|
+
* @param {unknown} gapSlots - Gap slot count
|
|
1828
|
+
* @returns {string[]} destinations inside the gap band
|
|
1829
|
+
*/
|
|
1830
|
+
function collectGapBandPlacementShadowSlots(actions, boundary, gapSlots) {
|
|
1831
|
+
try {
|
|
1832
|
+
// Explicit null/empty guard BEFORE Number(): Number(null) === 0 and
|
|
1833
|
+
// Number('') === 0 would otherwise read an unknown boundary as slot 0
|
|
1834
|
+
// and select a real gap band around it (same trap that
|
|
1835
|
+
// buildCowResultFromPlan guards for workingBoundary).
|
|
1836
|
+
if (boundary === null || boundary === undefined || boundary === '')
|
|
1837
|
+
return [];
|
|
1838
|
+
if (gapSlots === null || gapSlots === undefined || gapSlots === '')
|
|
1839
|
+
return [];
|
|
1840
|
+
const b = Number(boundary);
|
|
1841
|
+
const g = Number(gapSlots);
|
|
1842
|
+
if (!Number.isFinite(b) || !Number.isFinite(g) || !Array.isArray(actions))
|
|
1843
|
+
return [];
|
|
1844
|
+
const out = [];
|
|
1845
|
+
for (const action of actions) {
|
|
1846
|
+
if (action?.type !== COW_ACTIONS.CREATE && action?.type !== COW_ACTIONS.UPDATE)
|
|
1847
|
+
continue;
|
|
1848
|
+
const origin = action?.origin;
|
|
1849
|
+
if (origin === COW_ORIGINS.SPREAD_CORRECTION || origin === COW_ORIGINS.GAP_EVACUATION)
|
|
1850
|
+
continue;
|
|
1851
|
+
const destId = String(action?.newGridId || action?.id || action?.order?.id || '');
|
|
1852
|
+
if (!destId)
|
|
1853
|
+
continue;
|
|
1854
|
+
const idx = parseSlotIndex(destId);
|
|
1855
|
+
if (idx === null || idx === undefined)
|
|
1856
|
+
continue;
|
|
1857
|
+
if (!isSlotIndexInGapBand(idx, b, g))
|
|
1858
|
+
continue;
|
|
1859
|
+
out.push(destId);
|
|
1860
|
+
}
|
|
1861
|
+
return out;
|
|
1862
|
+
}
|
|
1863
|
+
catch {
|
|
1864
|
+
return [];
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1753
1867
|
/**
|
|
1754
1868
|
* LAST-FILL-GUARD helper — pivot ± halfIncrement (replaces price-tolerance).
|
|
1755
|
-
* last fill @x with increment i
|
|
1756
|
-
*
|
|
1869
|
+
* last fill @x with increment i (blocked shapes): BUY > x*(1 - i/2/100),
|
|
1870
|
+
* SELL < x*(1 + i/2/100)
|
|
1871
|
+
* e.g. x=1000, i=0.5% => BUY > 997.5 and SELL < 1002.5 are blocked
|
|
1757
1872
|
* Cold (pivot null or lastType null) => disabled. Spread-correction CREATES
|
|
1758
1873
|
* bypass per-action (see broadcast sites); gap-evacuation rotation UPDATEs
|
|
1759
1874
|
* bypass only via the violation-reducing allowance (origin='gap-evacuation',
|
|
@@ -1794,6 +1909,44 @@ function isLastFillGuardBlocked(price, _size, type, lastPrice, lastType, increme
|
|
|
1794
1909
|
return { blocked: true, pivot, halfInc, threshold: sellThreshold };
|
|
1795
1910
|
return { blocked: false, pivot: null, halfInc, threshold: null };
|
|
1796
1911
|
}
|
|
1912
|
+
/**
|
|
1913
|
+
* Whether a spread-correction CREATE may bypass the LAST-FILL-GUARD.
|
|
1914
|
+
*
|
|
1915
|
+
* The bypass exists so gap repair can close even after a recent fill (the
|
|
1916
|
+
* correction is tightening the spread, not chasing it). It must not become a
|
|
1917
|
+
* licence to place THROUGH the market the bot last traded at:
|
|
1918
|
+
*
|
|
1919
|
+
* 1. A real fill pivot (`lastFillPivotSource === 'fill'`) is always honored —
|
|
1920
|
+
* no bypass. A sell below the last fill (or a buy above it) is the
|
|
1921
|
+
* issue-#31 adverse fill.
|
|
1922
|
+
* 2. A cold/book pivot is a heuristic (book seed) or absent, so the historical
|
|
1923
|
+
* fail-open bypass is kept — but only while the LOCAL snapshot is fresh.
|
|
1924
|
+
* A stale snapshot (known-unmatched chain orders, or an old sync) can hide
|
|
1925
|
+
* the real window edge, so the bypass is withheld and the guard applies.
|
|
1926
|
+
*
|
|
1927
|
+
* Exported for tests.
|
|
1928
|
+
* @param {Object} bot
|
|
1929
|
+
* @returns {boolean} True when the bypass may be used
|
|
1930
|
+
*/
|
|
1931
|
+
function isSpreadCorrectionBypassAllowed(bot) {
|
|
1932
|
+
const mgr = bot?.manager;
|
|
1933
|
+
if (!mgr)
|
|
1934
|
+
return true; // no manager state ⇒ nothing for the guard to protect
|
|
1935
|
+
// ONE verdict with the planner (evaluateSpreadCorrectionReadiness): the
|
|
1936
|
+
// bypass is licensed only when the snapshot is trusted AND no real FILL
|
|
1937
|
+
// reference exists. The LAST-FILL-GUARD is fill-based, so a live market
|
|
1938
|
+
// price (which only strengthens the planner's crossing floor) must not
|
|
1939
|
+
// change this decision. A real fill denies it; a stale or known-unmatched
|
|
1940
|
+
// snapshot denies it too (the guard applies instead). Fail-closed (deny
|
|
1941
|
+
// bypass) if the gate throws — never less safe than applying the guard.
|
|
1942
|
+
try {
|
|
1943
|
+
const readiness = evaluateSpreadCorrectionReadiness(mgr);
|
|
1944
|
+
return readiness.snapshotTrusted && readiness.fillMarketRef == null;
|
|
1945
|
+
}
|
|
1946
|
+
catch {
|
|
1947
|
+
return false;
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1797
1950
|
/**
|
|
1798
1951
|
* Refresh the LAST-FILL guard pivot from fills that arrived while the current
|
|
1799
1952
|
* batch was being planned or broadcast but have not been ingested yet.
|
|
@@ -2062,7 +2215,8 @@ function buildCowResultFromPlan(bot, plan) {
|
|
|
2062
2215
|
// Guard null/undefined explicitly: Number(null) === 0 would be treated as a
|
|
2063
2216
|
// valid finite boundary (index 0), silently biasing role classification.
|
|
2064
2217
|
const rawBoundary = plan?.boundaryIdx;
|
|
2065
|
-
|
|
2218
|
+
// Absent-aware: null/undefined/'' are unknown (NaN), never boundary 0.
|
|
2219
|
+
const requestedBoundary = Format.toKnownNumber(rawBoundary);
|
|
2066
2220
|
const workingBoundary = Number.isFinite(requestedBoundary)
|
|
2067
2221
|
? requestedBoundary
|
|
2068
2222
|
: bot.manager.boundaryIdx;
|
|
@@ -2074,8 +2228,16 @@ function buildCowResultFromPlan(bot, plan) {
|
|
|
2074
2228
|
const toWorkingHole = (slot) => {
|
|
2075
2229
|
try {
|
|
2076
2230
|
const idx = parseSlotIndex(slot?.id);
|
|
2077
|
-
|
|
2078
|
-
|
|
2231
|
+
// Explicit null/'' guard: the workingBoundary fallback (manager.boundaryIdx)
|
|
2232
|
+
// can be null, and Number(null) === 0 would misclassify slot 0 as a BUY
|
|
2233
|
+
// rail hole (same trap guarded for plan.boundaryIdx above).
|
|
2234
|
+
const b = (workingBoundary === null || workingBoundary === undefined || workingBoundary === '')
|
|
2235
|
+
? NaN
|
|
2236
|
+
: Number(workingBoundary);
|
|
2237
|
+
const rawGapSlots = bot?.manager?._gapSlots;
|
|
2238
|
+
const gapSlots = (rawGapSlots === null || rawGapSlots === undefined || rawGapSlots === '')
|
|
2239
|
+
? NaN
|
|
2240
|
+
: Number(rawGapSlots);
|
|
2079
2241
|
if (idx !== null && idx !== undefined && Number.isFinite(b) && Number.isFinite(gapSlots) && gapSlots >= 0) {
|
|
2080
2242
|
if (Number(idx) <= b)
|
|
2081
2243
|
return toRailHolePlaceholder(slot, ORDER_TYPES.BUY);
|
|
@@ -2860,6 +3022,112 @@ async function runPreBroadcastGuards(bot, cowResult) {
|
|
|
2860
3022
|
}
|
|
2861
3023
|
};
|
|
2862
3024
|
}
|
|
3025
|
+
// MODE C(b) — pre-broadcast UPDATE-target existence check off the
|
|
3026
|
+
// slot->orderId map. A tracked order that is already gone on chain makes a
|
|
3027
|
+
// limit_order_update abort the broadcast chunk ("Order does not exist …
|
|
3028
|
+
// cannot update") and leaves a partially-applied grid. Re-reading the
|
|
3029
|
+
// referenced ids right before broadcast turns that into a clean
|
|
3030
|
+
// pre-broadcast refusal + structural resync, so nothing is half-applied.
|
|
3031
|
+
const updateTargetIds = new Set();
|
|
3032
|
+
for (const action of actions) {
|
|
3033
|
+
if (action?.type === COW_ACTIONS.UPDATE && action.orderId)
|
|
3034
|
+
updateTargetIds.add(String(action.orderId));
|
|
3035
|
+
}
|
|
3036
|
+
if (updateTargetIds.size > 0 && typeof chainOrders.batchReadOrders === 'function') {
|
|
3037
|
+
try {
|
|
3038
|
+
const readResult = await chainOrders.batchReadOrders([...updateTargetIds], 3000);
|
|
3039
|
+
const readMap = readResult;
|
|
3040
|
+
// Fail OPEN on a non-Map result (tests/other accessors): only an
|
|
3041
|
+
// authoritative map can prove an order gone.
|
|
3042
|
+
if (readMap && typeof readMap.get === 'function') {
|
|
3043
|
+
const missing = [];
|
|
3044
|
+
for (const id of updateTargetIds) {
|
|
3045
|
+
if (!readMap.get(id))
|
|
3046
|
+
missing.push(id);
|
|
3047
|
+
}
|
|
3048
|
+
if (missing.length > 0 && typeof chainOrders.readSingleOrder === 'function') {
|
|
3049
|
+
// Second, independent read before an absence decision: a
|
|
3050
|
+
// node that has not yet seen a freshly created order can
|
|
3051
|
+
// return null from the batch read. Re-reading each candidate
|
|
3052
|
+
// individually cancels the absence when the order is found;
|
|
3053
|
+
// a failed re-read must not manufacture an absence (fail
|
|
3054
|
+
// open), so only a read that returns an explicit null is
|
|
3055
|
+
// treated as confirming the gap.
|
|
3056
|
+
const stillMissing = [];
|
|
3057
|
+
for (const id of missing) {
|
|
3058
|
+
let present = true;
|
|
3059
|
+
try {
|
|
3060
|
+
present = Boolean(await chainOrders.readSingleOrder(id, 3000));
|
|
3061
|
+
}
|
|
3062
|
+
catch { /* failed re-verify must not manufacture an absence */ }
|
|
3063
|
+
if (!present)
|
|
3064
|
+
stillMissing.push(id);
|
|
3065
|
+
}
|
|
3066
|
+
missing.length = 0;
|
|
3067
|
+
missing.push(...stillMissing);
|
|
3068
|
+
}
|
|
3069
|
+
if (missing.length > 0) {
|
|
3070
|
+
bot.manager.logger.log(`[COW] Rejecting UPDATE batch pre-broadcast: ${missing.length} target(s) missing on chain ` +
|
|
3071
|
+
`(${missing.slice(0, 8).join(', ')}${missing.length > 8 ? ', …' : ''}); ` +
|
|
3072
|
+
`grid/chain existence divergence — structural resync required`, 'error');
|
|
3073
|
+
popPushedWorkingGrid(bot, cowResult);
|
|
3074
|
+
await requestStructuralResync(bot, 'pre-broadcast update target missing on chain', { missingUpdateOrderIds: missing });
|
|
3075
|
+
return {
|
|
3076
|
+
proceed: false,
|
|
3077
|
+
result: {
|
|
3078
|
+
executed: false,
|
|
3079
|
+
aborted: true,
|
|
3080
|
+
reason: 'UPDATE_TARGET_MISSING',
|
|
3081
|
+
missingUpdateOrderIds: missing,
|
|
3082
|
+
hadRotation: false
|
|
3083
|
+
}
|
|
3084
|
+
};
|
|
3085
|
+
}
|
|
3086
|
+
}
|
|
3087
|
+
}
|
|
3088
|
+
catch (existenceErr) {
|
|
3089
|
+
// A failed/foreign read must never block a legitimate broadcast;
|
|
3090
|
+
// the chain's own rejection remains the backstop.
|
|
3091
|
+
bot.manager.logger.log(`[COW] Pre-broadcast UPDATE existence check failed (${getErrorMessage(existenceErr)}); ` +
|
|
3092
|
+
`proceeding (chain rejection remains the backstop)`, 'debug');
|
|
3093
|
+
}
|
|
3094
|
+
}
|
|
3095
|
+
// MODE C(a) — gap-band placement SHADOW check (observability + summary,
|
|
3096
|
+
// no placement change). A non-spread-correction CREATE/UPDATE whose
|
|
3097
|
+
// destination sits inside the plan's gap band is the Mode-C geometry that
|
|
3098
|
+
// the reverted P1/P2 cancellation nets used to mop up; enforcement is
|
|
3099
|
+
// deliberately NOT done here because spread correction legitimately places
|
|
3100
|
+
// INTO the band (the LAST-FILL-GUARD bypass exists for exactly that) and a
|
|
3101
|
+
// hard reject would re-open the P1-e2898e51 regression class. Count + warn
|
|
3102
|
+
// so the leak is measurable before any policy change.
|
|
3103
|
+
try {
|
|
3104
|
+
const planBoundaryValue = cowResult?.workingBoundary;
|
|
3105
|
+
const planBoundaryRaw = (planBoundaryValue === null || planBoundaryValue === undefined || planBoundaryValue === '')
|
|
3106
|
+
? NaN
|
|
3107
|
+
: Number(planBoundaryValue);
|
|
3108
|
+
// Fall back to the committed boundary only when it is itself known:
|
|
3109
|
+
// Number(null) === 0 and Number('') === 0 must not silently become
|
|
3110
|
+
// slot 0 (same trap the helper guards).
|
|
3111
|
+
const managerBoundaryRaw = bot.manager?.boundaryIdx;
|
|
3112
|
+
const shadowBoundary = Number.isFinite(planBoundaryRaw)
|
|
3113
|
+
? planBoundaryRaw
|
|
3114
|
+
: (managerBoundaryRaw != null && managerBoundaryRaw !== '' ? Number(managerBoundaryRaw) : NaN);
|
|
3115
|
+
// Absent-aware gap: Number(null) === 0 would defeat the helper's own
|
|
3116
|
+
// null guard by passing a collapsed 0 band before the helper sees it.
|
|
3117
|
+
const shadowGapSlots = Format.toKnownNumber(bot.manager?._gapSlots);
|
|
3118
|
+
const shadowSlots = collectGapBandPlacementShadowSlots(actions, shadowBoundary, shadowGapSlots);
|
|
3119
|
+
if (shadowSlots.length > 0) {
|
|
3120
|
+
if (bot._metrics) {
|
|
3121
|
+
bot._metrics.gapBandPlacementShadowCount =
|
|
3122
|
+
(bot._metrics.gapBandPlacementShadowCount || 0) + shadowSlots.length;
|
|
3123
|
+
}
|
|
3124
|
+
bot.manager.logger.log(`[COW-GAP-BAND] shadow: ${shadowSlots.length} non-spread-correction placement(s) ` +
|
|
3125
|
+
`inside the plan's gap band (boundary ${shadowBoundary}, gap ${shadowGapSlots}): ` +
|
|
3126
|
+
`${shadowSlots.slice(0, 8).join(', ')}${shadowSlots.length > 8 ? ', …' : ''} ` +
|
|
3127
|
+
`— counted for observability, NOT blocked`, 'warn');
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
catch { /* shadow check must never break a batch */ }
|
|
2863
3131
|
// Crossing-check candidate set (master + pending-broadcast + unmatched
|
|
2864
3132
|
// chain orders). Built after the batch-level pending/unmatched guards so
|
|
2865
3133
|
// it reflects any sync they triggered.
|
|
@@ -3112,8 +3380,12 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3112
3380
|
// whose freeze picked up a pre-freeze queued fill look "moved" at the
|
|
3113
3381
|
// gate — a spurious warn plus a redundant full re-check against the
|
|
3114
3382
|
// identical pivot.
|
|
3115
|
-
|
|
3116
|
-
|
|
3383
|
+
// Same effective reference the per-action guard judges against (live
|
|
3384
|
+
// pivot, else the bot-scoped market fill) so the freeze cannot run cold
|
|
3385
|
+
// while the guard still blocks.
|
|
3386
|
+
const frozenRef = resolveLastFillGuardReference(bot.manager);
|
|
3387
|
+
const frozenPivotAtBatchStart = frozenRef.price;
|
|
3388
|
+
const frozenTypeAtBatchStart = frozenRef.type;
|
|
3117
3389
|
for (const action of actions) {
|
|
3118
3390
|
if (action.type === COW_ACTIONS.CANCEL) {
|
|
3119
3391
|
try {
|
|
@@ -3206,8 +3478,9 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3206
3478
|
try {
|
|
3207
3479
|
const actionOrigin = action?.origin;
|
|
3208
3480
|
const batchOrigin = cowResult?.origin;
|
|
3209
|
-
const isCorrectionCreate = actionOrigin === COW_ORIGINS.SPREAD_CORRECTION
|
|
3210
|
-
|| (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION)
|
|
3481
|
+
const isCorrectionCreate = (actionOrigin === COW_ORIGINS.SPREAD_CORRECTION
|
|
3482
|
+
|| (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION))
|
|
3483
|
+
&& isSpreadCorrectionBypassAllowed(bot);
|
|
3211
3484
|
if (!isCorrectionCreate) {
|
|
3212
3485
|
const { check, refreshed } = runLastFillGuardCheck(bot, createPrice, order.size, order.type, lastFillGuardStats, true);
|
|
3213
3486
|
if (refreshed)
|
|
@@ -3238,6 +3511,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3238
3511
|
skippedCreateSlotIds.add(order.id);
|
|
3239
3512
|
continue;
|
|
3240
3513
|
}
|
|
3514
|
+
recordRestampBuyAboveAnchor(bot, createPrice, order.type);
|
|
3241
3515
|
const buildResult = await chainOrders.buildCreateOrderOp(bot.account, args.amountToSell, args.sellAssetId, args.minToReceive, args.receiveAssetId, null);
|
|
3242
3516
|
if (!buildResult) {
|
|
3243
3517
|
bot.manager.logger.log(`Skipping create op for ${action.id}: amounts would round to 0 on blockchain`, 'warn');
|
|
@@ -3379,8 +3653,10 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3379
3653
|
let bypassedEvacuation = false;
|
|
3380
3654
|
const rotationOrigin = action?.origin;
|
|
3381
3655
|
if (rotationOrigin === COW_ORIGINS.GAP_EVACUATION) {
|
|
3382
|
-
|
|
3383
|
-
|
|
3656
|
+
// Absent-aware: a legacy stamp carrying null/''
|
|
3657
|
+
// geometry must not read as boundary 0 / gap 0.
|
|
3658
|
+
const frozenB = Format.toKnownNumber(action?.evacBoundary);
|
|
3659
|
+
const frozenG = Format.toKnownNumber(action?.evacGapSlots);
|
|
3384
3660
|
let stampUsable = Number.isFinite(frozenB) && Number.isFinite(frozenG);
|
|
3385
3661
|
if (stampUsable) {
|
|
3386
3662
|
// Stale-stamp check: the stamp froze PLAN-BUILD
|
|
@@ -3509,6 +3785,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3509
3785
|
skippedUpdateSlotIds.add(action.newGridId);
|
|
3510
3786
|
continue;
|
|
3511
3787
|
}
|
|
3788
|
+
recordRestampBuyAboveAnchor(bot, newPrice, orderType);
|
|
3512
3789
|
const buildResult = await chainOrders.buildUpdateOrderOp(bot.account, action.orderId, { amountToSell, minToReceive, newPrice, orderType }, masterOrder.rawOnChain || null);
|
|
3513
3790
|
if (!buildResult) {
|
|
3514
3791
|
skippedUpdateCount++;
|
|
@@ -3644,6 +3921,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3644
3921
|
if (!recordGridPriceInvariantCheck(bot, targetSlotId, fbPrice, gridPriceInvariantStats, 'CREATE-FALLBACK')) {
|
|
3645
3922
|
continue;
|
|
3646
3923
|
}
|
|
3924
|
+
recordRestampBuyAboveAnchor(bot, fbPrice, fbType);
|
|
3647
3925
|
const fbResult = await chainOrders.buildCreateOrderOp(bot.account, fbArgs.amountToSell, fbArgs.sellAssetId, fbArgs.minToReceive, fbArgs.receiveAssetId, null);
|
|
3648
3926
|
if (fbResult) {
|
|
3649
3927
|
operations.push(fbResult.op);
|
|
@@ -3764,8 +4042,12 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
3764
4042
|
const gateGuarded = finalGateStats.checked + finalGateStats.bypassed;
|
|
3765
4043
|
const totalGuarded = lastFillGuardStats.checked + lastFillGuardStats.bypassed + gateGuarded;
|
|
3766
4044
|
if (totalGuarded > 0) {
|
|
3767
|
-
|
|
3768
|
-
|
|
4045
|
+
// Same effective reference the guard judged against (live pivot
|
|
4046
|
+
// else the bot-scoped market fill) so the summary cannot report
|
|
4047
|
+
// disabled(cold) while placements were actually blocked.
|
|
4048
|
+
const sumRef = resolveLastFillGuardReference(bot.manager);
|
|
4049
|
+
const sumPivotRaw = sumRef.price;
|
|
4050
|
+
const sumType = sumRef.type;
|
|
3769
4051
|
const sumInc = resolveLastFillGuardIncrement(bot);
|
|
3770
4052
|
const cold = sumPivotRaw == null || !Number.isFinite(Number(sumPivotRaw)) || sumType == null;
|
|
3771
4053
|
const batchOrigin = cowResult?.origin;
|
|
@@ -4183,6 +4465,10 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
|
|
|
4183
4465
|
// balance reflects the on-chain cost (shared with the
|
|
4184
4466
|
// refused-commit paths via recoverRefusedCommit).
|
|
4185
4467
|
return await recoverRefusedCommit(bot, chainOrders, '[COW][UNCERTAIN]', { placedContexts: opContexts, polledCreateIds: confirmation.confirmedChainIds }, opContexts, effectiveBoundary, {
|
|
4468
|
+
// Poll-confirmed SUCCESS: the commit was accepted;
|
|
4469
|
+
// this funnel is only reused for chain adoption +
|
|
4470
|
+
// fee deduction, so it must not count as a refusal.
|
|
4471
|
+
refusedCommit: false,
|
|
4186
4472
|
extraReturn: { commitRefused: false },
|
|
4187
4473
|
successReturn: { executed: true, hadRotation: false, uncertainResolved: true },
|
|
4188
4474
|
failureResyncReason: 'poll-confirmed commit (chain adoption unavailable)',
|
|
@@ -4475,6 +4761,18 @@ async function persistGridAndClearPendingBroadcasts(bot, logPrefix) {
|
|
|
4475
4761
|
* @returns {Promise<Object>} The commit-refused return object
|
|
4476
4762
|
*/
|
|
4477
4763
|
async function recoverRefusedCommit(bot, chainOrders, logPrefix, adoptOpts, contexts, workingBoundary, opts = {}) {
|
|
4764
|
+
// P2 observability: count genuine commit refusals at this single funnel (so
|
|
4765
|
+
// the three call sites cannot double-count). This function is ALSO the
|
|
4766
|
+
// shared funnel for the poll-confirmed SUCCESS path (chain adoption + fee
|
|
4767
|
+
// deduction), which passes `refusedCommit: false` because the commit was
|
|
4768
|
+
// accepted — counting it would overstate the refusal signal. Never gates
|
|
4769
|
+
// behavior.
|
|
4770
|
+
try {
|
|
4771
|
+
if (opts.refusedCommit !== false && bot._metrics) {
|
|
4772
|
+
bot._metrics.refusedCommitCount = (bot._metrics.refusedCommitCount || 0) + 1;
|
|
4773
|
+
}
|
|
4774
|
+
}
|
|
4775
|
+
catch { /* metrics are best-effort */ }
|
|
4478
4776
|
const extraReturn = (opts.extraReturn ?? {});
|
|
4479
4777
|
const successReturn = opts.successReturn;
|
|
4480
4778
|
const failureResyncReason = (opts.failureResyncReason ?? 'commit refused after broadcast (chain adoption unavailable)');
|
|
@@ -4590,8 +4888,12 @@ function runLastFillGuardCheck(bot, price, size, type, stats, skipRefresh = fals
|
|
|
4590
4888
|
}
|
|
4591
4889
|
catch { /* best-effort */ }
|
|
4592
4890
|
}
|
|
4593
|
-
|
|
4594
|
-
|
|
4891
|
+
// Effective reference: the live pivot when armed, else the bot-scoped
|
|
4892
|
+
// market fill that survives a grid regeneration. Without the fallback a
|
|
4893
|
+
// rebuild un-arms the guard until the next fill.
|
|
4894
|
+
const lastRef = resolveLastFillGuardReference(bot.manager);
|
|
4895
|
+
const lastPrice = lastRef.price;
|
|
4896
|
+
const lastType = lastRef.type;
|
|
4595
4897
|
const inc = resolveLastFillGuardIncrement(bot);
|
|
4596
4898
|
// Validate the pivot onto the ladder before use (see resolveOnGridPivot).
|
|
4597
4899
|
// Reported once per probe at warn when the raw pivot was NOT a grid level:
|
|
@@ -4718,8 +5020,9 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
4718
5020
|
const queueDepthAfter = Array.isArray(bot?._incomingFillQueue)
|
|
4719
5021
|
? bot._incomingFillQueue.length
|
|
4720
5022
|
: null;
|
|
4721
|
-
const
|
|
4722
|
-
const
|
|
5023
|
+
const liveRef = resolveLastFillGuardReference(bot.manager);
|
|
5024
|
+
const livePivot = Number(liveRef.price);
|
|
5025
|
+
const liveType = liveRef.type;
|
|
4723
5026
|
const liveCold = !Number.isFinite(livePivot) || liveType == null;
|
|
4724
5027
|
// No-op fast path: pivot unchanged (or uncomparable) since the freeze.
|
|
4725
5028
|
// frozenCold + liveCold: guard stayed disabled — nothing to re-check.
|
|
@@ -4760,7 +5063,7 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
4760
5063
|
const dropIdx = new Set();
|
|
4761
5064
|
const dropped = [];
|
|
4762
5065
|
const inc = resolveLastFillGuardIncrement(bot);
|
|
4763
|
-
const onGrid = resolveOnGridPivot(bot.manager,
|
|
5066
|
+
const onGrid = resolveOnGridPivot(bot.manager, liveRef.price);
|
|
4764
5067
|
for (let i = 0; i < opContexts.length; i++) {
|
|
4765
5068
|
const ctx = opContexts[i];
|
|
4766
5069
|
if (!ctx || ctx.kind === 'cancel' || ctx.kind === 'size-update')
|
|
@@ -4779,8 +5082,9 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
4779
5082
|
// Spread-correction CREATE bypass (mirrors the build loop:
|
|
4780
5083
|
// per-action origin, batch origin as back-compat fallback).
|
|
4781
5084
|
const actionOrigin = action?.origin;
|
|
4782
|
-
if (actionOrigin === COW_ORIGINS.SPREAD_CORRECTION
|
|
4783
|
-
|| (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION))
|
|
5085
|
+
if ((actionOrigin === COW_ORIGINS.SPREAD_CORRECTION
|
|
5086
|
+
|| (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION))
|
|
5087
|
+
&& isSpreadCorrectionBypassAllowed(bot)) {
|
|
4784
5088
|
if (stats)
|
|
4785
5089
|
stats.bypassed = (Number(stats.bypassed) || 0) + 1;
|
|
4786
5090
|
continue;
|
|
@@ -4833,8 +5137,8 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
|
|
|
4833
5137
|
// especially not on an op the build loop already allowed.
|
|
4834
5138
|
const rotOrigin = action?.origin;
|
|
4835
5139
|
if (rotOrigin === COW_ORIGINS.GAP_EVACUATION
|
|
4836
|
-
&& Number.isFinite(
|
|
4837
|
-
&& Number.isFinite(
|
|
5140
|
+
&& Number.isFinite(Format.toKnownNumber(action?.evacBoundary))
|
|
5141
|
+
&& Number.isFinite(Format.toKnownNumber(action?.evacGapSlots))) {
|
|
4838
5142
|
if (stats)
|
|
4839
5143
|
stats.bypassed = (Number(stats.bypassed) || 0) + 1;
|
|
4840
5144
|
continue;
|
|
@@ -5222,43 +5526,24 @@ async function processBatchResults(bot, result, opContexts) {
|
|
|
5222
5526
|
updateOperationCount
|
|
5223
5527
|
};
|
|
5224
5528
|
}
|
|
5225
|
-
export { isLastFillGuardBlocked, resolveOnGridPivot, checkGridPriceInvariant, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast,
|
|
5529
|
+
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
5530
|
// Exported for regression tests (issue #23 sibling): the uncertain-broadcast
|
|
5227
5531
|
// discard path must never drop a placement silently when master lost the slot.
|
|
5228
5532
|
export { restoreDiscardedCreates };
|
|
5229
5533
|
export default {
|
|
5230
5534
|
buildOutsideInPairGroupsForOrders,
|
|
5231
5535
|
buildOutsideInPairGroupsForCreateEntries,
|
|
5232
|
-
extractOperationResults,
|
|
5233
|
-
findMissingCreateResultContexts,
|
|
5234
5536
|
markMissingCreateResultsAsStructuralBlocker,
|
|
5235
5537
|
formatUnmatchedChainOrderForLog,
|
|
5236
5538
|
recordPendingBroadcast,
|
|
5237
5539
|
clearPendingBroadcasts,
|
|
5238
|
-
clearPendingBroadcastsForSlots,
|
|
5239
|
-
popPushedWorkingGrid,
|
|
5240
|
-
buildChainOrderFingerprint,
|
|
5241
|
-
normalizeChainOrderForPendingMatch,
|
|
5242
5540
|
findChainOrderForSlot,
|
|
5243
5541
|
reconcileAfterUncertainBroadcast,
|
|
5244
|
-
reconcileAfterUncertainBroadcastImpl,
|
|
5245
|
-
shouldExecuteCreatePairMode,
|
|
5246
5542
|
executeWithRetryOnUncertain,
|
|
5247
5543
|
executeChunkedWithRetryOnUncertain,
|
|
5248
|
-
|
|
5249
|
-
validateOperationFunds,
|
|
5250
|
-
resolveIdealSizeForValidation,
|
|
5251
|
-
validateOrderSizeForExecution,
|
|
5252
|
-
buildActionsFromPlan,
|
|
5544
|
+
popPushedWorkingGrid,
|
|
5253
5545
|
buildCowResultFromPlan,
|
|
5254
|
-
restoreSkippedUpdateSlotsInWorkingGrid,
|
|
5255
|
-
resolveRefillBoundaryHold,
|
|
5256
|
-
toRefillSlotIdSet,
|
|
5257
|
-
trackBoundaryHold,
|
|
5258
|
-
applyRotationTransitionsToWorkingGrid,
|
|
5259
|
-
pollChainForConfirmation,
|
|
5260
5546
|
updateOrdersOnChainBatchCOW,
|
|
5261
5547
|
processBatchResults,
|
|
5262
|
-
runFinalPivotGate,
|
|
5263
5548
|
};
|
|
5264
5549
|
//# sourceMappingURL=dexbot_cow_runtime.js.map
|
|
@@ -25,12 +25,6 @@ interface CredentialClientOptions {
|
|
|
25
25
|
*/
|
|
26
26
|
onNodeFailed?: (nodeUrl: string) => void;
|
|
27
27
|
}
|
|
28
|
-
interface CredentialDaemonMeta {
|
|
29
|
-
uncertainOnTimeout?: boolean;
|
|
30
|
-
operations?: unknown[] | null;
|
|
31
|
-
accountName?: string | null;
|
|
32
|
-
batchId?: string | null;
|
|
33
|
-
}
|
|
34
28
|
export interface CredentialDaemonResponse {
|
|
35
29
|
success?: boolean;
|
|
36
30
|
error?: string;
|
|
@@ -45,14 +39,6 @@ export interface CredentialDaemonResponse {
|
|
|
45
39
|
/** Node reported by the daemon as in play at the failure (typed replies). */
|
|
46
40
|
nodeUrl?: string | null;
|
|
47
41
|
}
|
|
48
|
-
interface RequestPayload {
|
|
49
|
-
type: string;
|
|
50
|
-
accountName: string;
|
|
51
|
-
operations: unknown[];
|
|
52
|
-
sessionId?: string | null;
|
|
53
|
-
hmac?: string;
|
|
54
|
-
nodeUrl?: string;
|
|
55
|
-
}
|
|
56
42
|
declare const DEFAULT_SOCKET_PATH: string;
|
|
57
43
|
declare const DEFAULT_READY_FILE: string;
|
|
58
44
|
declare const DEFAULT_BROADCAST_TIMEOUT_MS: number;
|
|
@@ -80,9 +66,8 @@ declare class BroadcastUncertainError extends Error {
|
|
|
80
66
|
timeoutMs: number | null;
|
|
81
67
|
constructor(message: string, details?: BroadcastUncertainErrorDetails);
|
|
82
68
|
}
|
|
83
|
-
declare function sendCredentialDaemonRequest(socketPath: string, payload: RequestPayload, timeoutMs: number, meta?: CredentialDaemonMeta): Promise<CredentialDaemonResponse>;
|
|
84
69
|
declare function isCredentialDaemonReady(options?: CredentialClientOptions): boolean;
|
|
85
70
|
declare function waitForCredentialDaemon(timeoutMs?: number, options?: CredentialClientOptions): Promise<void>;
|
|
86
71
|
declare function executeOperationsViaCredentialDaemon(accountName: string, operations: unknown[], options?: CredentialClientOptions): Promise<CredentialDaemonResponse>;
|
|
87
|
-
export { DEFAULT_READY_FILE, DEFAULT_SOCKET_PATH, DEFAULT_BROADCAST_TIMEOUT_MS,
|
|
72
|
+
export { DEFAULT_READY_FILE, DEFAULT_SOCKET_PATH, DEFAULT_BROADCAST_TIMEOUT_MS, executeOperationsViaCredentialDaemon, isCredentialDaemonReady, waitForCredentialDaemon, BroadcastUncertainError };
|
|
88
73
|
//# sourceMappingURL=dexbot_credential_client.d.ts.map
|
|
@@ -219,5 +219,5 @@ async function executeOperationsViaCredentialDaemon(accountName, operations, opt
|
|
|
219
219
|
throw err;
|
|
220
220
|
}
|
|
221
221
|
}
|
|
222
|
-
export { DEFAULT_READY_FILE, DEFAULT_SOCKET_PATH, DEFAULT_BROADCAST_TIMEOUT_MS,
|
|
222
|
+
export { DEFAULT_READY_FILE, DEFAULT_SOCKET_PATH, DEFAULT_BROADCAST_TIMEOUT_MS, executeOperationsViaCredentialDaemon, isCredentialDaemonReady, waitForCredentialDaemon, BroadcastUncertainError };
|
|
223
223
|
//# sourceMappingURL=dexbot_credential_client.js.map
|
|
@@ -7,7 +7,7 @@ export interface FillOpLike {
|
|
|
7
7
|
}
|
|
8
8
|
type MissingKeyMessageFn = (op: FillOpLike, fill: unknown) => string;
|
|
9
9
|
type FallbackKeyMessageFn = (op: FillOpLike, fill: unknown, fillKey: string) => string;
|
|
10
|
-
|
|
10
|
+
type ReplayMessageFn = (op: FillOpLike, fill: unknown, fillKey: string) => string;
|
|
11
11
|
type FillErrorFn = (op: FillOpLike, fill: unknown, err: unknown) => string;
|
|
12
12
|
interface SweepOrphanFillOptions {
|
|
13
13
|
context: string;
|
|
@@ -331,7 +331,7 @@ async function applyReplaySafeTrackedFillAccounting(bot, fill, fillOp, options =
|
|
|
331
331
|
*/
|
|
332
332
|
async function applyReplaySafeOrphanFillAccounting(bot, fill, fillOp, options = {}) {
|
|
333
333
|
const { context, logger, replayMessage, persistenceMode } = resolveReplaySafeFillOptions(bot, options);
|
|
334
|
-
|
|
334
|
+
const result = await applyReplaySafeFillAccounting(bot, fill, fillOp, {
|
|
335
335
|
logger,
|
|
336
336
|
missingKeyMessage: (op) => `[${context}] Missing fill history id and orphan fallback key for ${op.order_id}; deferring to open-orders sync`,
|
|
337
337
|
fallbackKeyMessage: (op) => `[${context}] Missing fill history id for orphan fill ${op.order_id}; using degraded orphan replay key for proceeds-only accounting`,
|
|
@@ -340,6 +340,17 @@ async function applyReplaySafeOrphanFillAccounting(bot, fill, fillOp, options =
|
|
|
340
340
|
persistenceMode,
|
|
341
341
|
allowOrphanFallbackKey: true
|
|
342
342
|
});
|
|
343
|
+
// P2 observability: this wrapper is orphan-fill-only (processSweepOrphanFill),
|
|
344
|
+
// so an `applied` result is exactly one set of proceeds credited outside
|
|
345
|
+
// slot accounting. `duplicate`/`error`/`missing_key` are not credits and
|
|
346
|
+
// would make the metric useless as a "funds left the grid" signal.
|
|
347
|
+
try {
|
|
348
|
+
if (result?.status === 'applied' && bot?._metrics) {
|
|
349
|
+
bot._metrics.orphanFillCreditedCount = (bot._metrics.orphanFillCreditedCount || 0) + 1;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
catch { /* metrics are best-effort */ }
|
|
353
|
+
return result;
|
|
343
354
|
}
|
|
344
355
|
/**
|
|
345
356
|
* Create a fill callback handler for blockchain subscription events.
|