dexbot 1.6.18 → 1.7.0

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.
Files changed (89) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +24 -18
  3. package/analysis/README.md +95 -3
  4. package/claw/package.json +1 -1
  5. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  7. package/dist/analysis/analyze_dynamic_weight.js +2 -1
  8. package/dist/analysis/analyze_kalman.js +3 -2
  9. package/dist/analysis/analyze_liquidity.d.ts +17 -0
  10. package/dist/analysis/analyze_liquidity.js +325 -0
  11. package/dist/analysis/analyze_regime.js +3 -2
  12. package/dist/analysis/analyze_regime_windows.js +3 -2
  13. package/dist/analysis/analyze_volatility.js +3 -2
  14. package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
  15. package/dist/analysis/liquidity/liquidity_chain.js +178 -0
  16. package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
  17. package/dist/analysis/liquidity/liquidity_chart_generator.js +523 -0
  18. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +141 -0
  19. package/dist/analysis/liquidity/liquidity_depth_model.js +230 -0
  20. package/dist/analysis/liquidity/liquidity_view.d.ts +38 -0
  21. package/dist/analysis/liquidity/liquidity_view.js +55 -0
  22. package/dist/analysis/trade_profitability.js +2 -1
  23. package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
  24. package/dist/dexbot.js +74 -169
  25. package/dist/modules/asset_lookup.d.ts +25 -0
  26. package/dist/modules/asset_lookup.js +75 -0
  27. package/dist/modules/chain_scan.d.ts +64 -0
  28. package/dist/modules/chain_scan.js +80 -0
  29. package/dist/modules/cli_colors.d.ts +5 -0
  30. package/dist/modules/cli_colors.js +7 -0
  31. package/dist/modules/cli_progress.d.ts +51 -0
  32. package/dist/modules/cli_progress.js +113 -0
  33. package/dist/modules/dexbot_cow_runtime.js +14 -4
  34. package/dist/modules/dexbot_fill_runtime.js +20 -0
  35. package/dist/modules/dexbot_maintenance_runtime.js +16 -1
  36. package/dist/modules/launcher/runtime_entry.d.ts +21 -1
  37. package/dist/modules/launcher/runtime_entry.js +36 -1
  38. package/dist/modules/liquidity_pool_ref.d.ts +32 -0
  39. package/dist/modules/liquidity_pool_ref.js +116 -0
  40. package/dist/modules/order/grid.js +9 -2
  41. package/dist/modules/order/grid_reconcile.js +22 -1
  42. package/dist/modules/order/grid_reconcile_internal.js +92 -14
  43. package/dist/modules/order/index.d.ts +15 -1
  44. package/dist/modules/order/manager.d.ts +2 -0
  45. package/dist/modules/order/manager.js +3 -0
  46. package/dist/modules/order/sync_engine.d.ts +20 -0
  47. package/dist/modules/order/sync_engine.js +101 -33
  48. package/dist/modules/order/utils/math.d.ts +18 -1
  49. package/dist/modules/order/utils/math.js +30 -1
  50. package/dist/modules/order/utils/order.d.ts +107 -1
  51. package/dist/modules/order/utils/order.js +298 -1
  52. package/dist/modules/order/utils/system.d.ts +63 -1
  53. package/dist/modules/order/utils/system.js +247 -36
  54. package/dist/modules/order/utils/validate.js +33 -2
  55. package/dist/modules/types.d.ts +5 -0
  56. package/dist/modules/utils/asset_symbols.d.ts +13 -2
  57. package/dist/modules/utils/asset_symbols.js +21 -2
  58. package/dist/scripts/analysis_runner.d.ts +10 -0
  59. package/dist/scripts/analysis_runner.js +33 -0
  60. package/dist/scripts/analyze-orders.js +2 -1
  61. package/dist/scripts/asset.d.ts +26 -0
  62. package/dist/scripts/asset.js +165 -0
  63. package/dist/scripts/bts_distribution.d.ts +1 -0
  64. package/dist/scripts/bts_distribution.js +194 -142
  65. package/dist/scripts/chart_command.d.ts +1 -1
  66. package/dist/scripts/chart_command.js +60 -86
  67. package/dist/scripts/chart_targets.d.ts +18 -0
  68. package/dist/scripts/chart_targets.js +52 -0
  69. package/dist/scripts/dw.js +1 -1
  70. package/dist/scripts/liquid.d.ts +24 -0
  71. package/dist/scripts/liquid.js +134 -0
  72. package/dist/scripts/rich_list.js +12 -16
  73. package/dist/scripts/token_distribution.d.ts +2 -0
  74. package/dist/scripts/token_distribution.js +132 -108
  75. package/dist/scripts/tv.js +1 -1
  76. package/dist/scripts/verify-browser-bundle.js +18 -0
  77. package/docs/COW_INVARIANTS.md +2 -2
  78. package/docs/DEXBOT_COMPARISON.md +6 -6
  79. package/docs/EVOLUTION.md +9 -8
  80. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  81. package/docs/GRID_PRICE_INVARIANT.md +4 -1
  82. package/docs/GRID_RECONCILE.md +20 -0
  83. package/docs/LOGGING.md +25 -3
  84. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +2 -1
  85. package/docs/README.md +1 -1
  86. package/docs/WORKFLOW.md +3 -1
  87. package/modules/README.md +5 -1
  88. package/package.json +3 -1
  89. package/scripts/README.md +23 -7
@@ -0,0 +1,51 @@
1
+ /** Console tags for the read-only analysis commands. */
2
+ export declare const CLI_TAGS: {
3
+ readonly assets: "[Assets]";
4
+ readonly liquidity: "[Liquidity]";
5
+ readonly tradingView: "[TradingView]";
6
+ readonly dynamicWeight: "[DynamicWeight]";
7
+ readonly pnl: "[PnL]";
8
+ readonly orders: "[Order]";
9
+ readonly volatility: "[Volatility]";
10
+ readonly regime: "[Regime]";
11
+ readonly regimeWindows: "[RegimeWindows]";
12
+ readonly kalman: "[Kalman]";
13
+ readonly derivatives: "[Derivatives]";
14
+ };
15
+ /**
16
+ * Write (or overwrite) a transient `[Tag] message` progress line.
17
+ * Silenced when `enabled` is false, when stderr is not a TTY, or in a browser.
18
+ */
19
+ export declare function progressLine(tag: string, enabled: boolean, message: string): void;
20
+ /** Erase the transient progress line before the report is printed. */
21
+ export declare function clearProgressLine(enabled?: boolean): void;
22
+ /**
23
+ * Bind {@link progressLine} to one tag, so a script keeps its short
24
+ * `progress(enabled, message)` call sites while the format stays centralized.
25
+ */
26
+ export declare function taggedProgress(tag: string): (enabled: boolean, message: string) => void;
27
+ /**
28
+ * Trailer printed after a report is written, e.g.
29
+ * `[Assets] ✓ Report saved. Open report: (file:///…/bts-distribution.html)`.
30
+ * The caller supplies the file URL (analysis/chart_utils.toFileUrl); `kind`
31
+ * overrides the lowercased label in the "Open …" half (`'PnL report'` →
32
+ * `'report'`).
33
+ */
34
+ export declare function savedLine(tag: string, label: string, fileUrl: string, kind?: string): string;
35
+ /** Persistent `[Tag] message` line, e.g. `[Assets] Loading … from chain...`. */
36
+ export declare function loadingLine(tag: string, message: string): string;
37
+ /**
38
+ * Report section header block (leading blank line included):
39
+ * `\n ── Title ─────────────────────────────…`, bold amber.
40
+ */
41
+ export declare function section(title: string, width?: number): string;
42
+ /** Warning bullets (` • text`, red), one per entry. */
43
+ export declare function warningLines(warnings: readonly string[]): string[];
44
+ /**
45
+ * A section header plus its warning bullets, or '' when there is nothing to
46
+ * report. Every report command prints warnings the same way through this.
47
+ */
48
+ export declare function warningsBlock(warnings: readonly string[], width?: number): string;
49
+ /** Muted trailing summary line, printed just above the saved-file link. */
50
+ export declare function summaryLine(text: string): string;
51
+ //# sourceMappingURL=cli_progress.d.ts.map
@@ -0,0 +1,113 @@
1
+ 'use strict';
2
+ /**
3
+ * modules/cli_progress.ts - Shared terminal status style for CLI commands.
4
+ *
5
+ * One place for the `[Tag] …` line style used by the analysis commands
6
+ * (`dexbot liq`, the chart exporters, the supply distribution analyzers):
7
+ *
8
+ * [Tag] Loading … caller's console.log (persistent)
9
+ * [Tag] scanning 1.13.x … progressLine() - transient, stderr, TTY only
10
+ * [Tag] ✓ Report saved … savedLine() (persistent, clickable file:// link)
11
+ *
12
+ * Keeping the tag, the clear-line escape and the trailer wording here is what
13
+ * keeps `dexbot liq`, `dexbot tv`, `dexbot asset` … visually identical instead
14
+ * of each script re-implementing the same three things.
15
+ *
16
+ * Browser-safe: no Node imports. The stderr access is guarded through
17
+ * modules/env.ts, so the module can be imported from browser-reachable code
18
+ * without touching `process`.
19
+ */
20
+ import { hasProcess } from './env.js';
21
+ import { CLI_COLORS, colorize } from './cli_colors.js';
22
+ /** Erase the current terminal line (progress updates overwrite in place). */
23
+ const CLEAR_LINE = '\r\x1b[2K';
24
+ /** Console tags for the read-only analysis commands. */
25
+ export const CLI_TAGS = {
26
+ assets: '[Assets]',
27
+ liquidity: '[Liquidity]',
28
+ tradingView: '[TradingView]',
29
+ dynamicWeight: '[DynamicWeight]',
30
+ pnl: '[PnL]',
31
+ orders: '[Order]',
32
+ volatility: '[Volatility]',
33
+ regime: '[Regime]',
34
+ regimeWindows: '[RegimeWindows]',
35
+ kalman: '[Kalman]',
36
+ derivatives: '[Derivatives]',
37
+ };
38
+ /** Width of the report section headers (`── Title ──…`). */
39
+ const SECTION_WIDTH = 70;
40
+ /** stderr when it is an interactive terminal, otherwise null (no-op logging). */
41
+ function progressStream() {
42
+ if (!hasProcess())
43
+ return null;
44
+ const stream = globalThis.process?.stderr;
45
+ return stream && stream.isTTY ? stream : null;
46
+ }
47
+ /**
48
+ * Write (or overwrite) a transient `[Tag] message` progress line.
49
+ * Silenced when `enabled` is false, when stderr is not a TTY, or in a browser.
50
+ */
51
+ export function progressLine(tag, enabled, message) {
52
+ if (!enabled)
53
+ return;
54
+ const stream = progressStream();
55
+ if (!stream)
56
+ return;
57
+ stream.write(`${CLEAR_LINE}${tag} ${message}`);
58
+ }
59
+ /** Erase the transient progress line before the report is printed. */
60
+ export function clearProgressLine(enabled = true) {
61
+ if (!enabled)
62
+ return;
63
+ const stream = progressStream();
64
+ if (stream)
65
+ stream.write(CLEAR_LINE);
66
+ }
67
+ /**
68
+ * Bind {@link progressLine} to one tag, so a script keeps its short
69
+ * `progress(enabled, message)` call sites while the format stays centralized.
70
+ */
71
+ export function taggedProgress(tag) {
72
+ return (enabled, message) => progressLine(tag, enabled, message);
73
+ }
74
+ /**
75
+ * Trailer printed after a report is written, e.g.
76
+ * `[Assets] ✓ Report saved. Open report: (file:///…/bts-distribution.html)`.
77
+ * The caller supplies the file URL (analysis/chart_utils.toFileUrl); `kind`
78
+ * overrides the lowercased label in the "Open …" half (`'PnL report'` →
79
+ * `'report'`).
80
+ */
81
+ export function savedLine(tag, label, fileUrl, kind) {
82
+ return `\n${tag} ✓ ${label} saved. Open ${kind ?? label.toLowerCase()}: (${fileUrl})`;
83
+ }
84
+ /** Persistent `[Tag] message` line, e.g. `[Assets] Loading … from chain...`. */
85
+ export function loadingLine(tag, message) {
86
+ return `${tag} ${message}`;
87
+ }
88
+ /**
89
+ * Report section header block (leading blank line included):
90
+ * `\n ── Title ─────────────────────────────…`, bold amber.
91
+ */
92
+ export function section(title, width = SECTION_WIDTH) {
93
+ const rule = '─'.repeat(Math.max(0, width - title.length));
94
+ return `\n${colorize(CLI_COLORS.bold + CLI_COLORS.yellow, ` ── ${title} ${rule}`)}`;
95
+ }
96
+ /** Warning bullets (` • text`, red), one per entry. */
97
+ export function warningLines(warnings) {
98
+ return warnings.map((text) => colorize(CLI_COLORS.sell, ` • ${text}`));
99
+ }
100
+ /**
101
+ * A section header plus its warning bullets, or '' when there is nothing to
102
+ * report. Every report command prints warnings the same way through this.
103
+ */
104
+ export function warningsBlock(warnings, width = SECTION_WIDTH) {
105
+ if (warnings.length === 0)
106
+ return '';
107
+ return [section('Warnings', width), ...warningLines(warnings)].join('\n');
108
+ }
109
+ /** Muted trailing summary line, printed just above the saved-file link. */
110
+ export function summaryLine(text) {
111
+ return colorize(CLI_COLORS.gray, ` ${text}`);
112
+ }
113
+ //# sourceMappingURL=cli_progress.js.map
@@ -1777,15 +1777,22 @@ function recordRestampBuyAboveAnchor(bot, price, type) {
1777
1777
  try {
1778
1778
  if (type !== ORDER_TYPES.BUY)
1779
1779
  return false;
1780
- if (bot?.manager?._lastFilledType !== ORDER_TYPES.BUY)
1780
+ // ONE reference, the same one the guard judges against: the raw live
1781
+ // fields miss the market-row fallback (a rebuild) and would still count
1782
+ // against an expired pivot that no longer gates anything.
1783
+ const reference = resolveLastFillGuardReference(bot?.manager);
1784
+ if (reference.type !== ORDER_TYPES.BUY)
1781
1785
  return false;
1782
- const pivot = Number(bot?.manager?._lastFilledPrice);
1786
+ const pivot = Number(reference.price);
1783
1787
  const p = Number(price);
1784
1788
  if (!Number.isFinite(pivot) || pivot <= 0 || !Number.isFinite(p) || p <= 0)
1785
1789
  return false;
1786
1790
  // 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)
1791
+ // legitimate rotation target (I3) and is not counted. SAME LEVEL counts
1792
+ // too: a slot level and its execution price differ by rounding (slot
1793
+ // 1310.046339 filled at 1310.060435), so a bare `p < pivot` misses
1794
+ // exactly the shape this counter exists to expose.
1795
+ if (p < pivot && !math.pricesWithinHalfStep(p, pivot, bot?.manager?.config?.incrementPercent))
1789
1796
  return false;
1790
1797
  if (bot._metrics)
1791
1798
  bot._metrics.restampBuyAboveAnchorCount = (bot._metrics.restampBuyAboveAnchorCount || 0) + 1;
@@ -3087,6 +3094,9 @@ async function runPreBroadcastGuards(bot, cowResult) {
3087
3094
  case 'create_price_invalid':
3088
3095
  reason = `broadcast price is not a finite number`;
3089
3096
  break;
3097
+ case 'slot_create_uncertain':
3098
+ reason = `an earlier CREATE here has an unknown outcome (createUncertain)`;
3099
+ break;
3090
3100
  default:
3091
3101
  reason = `existing orderId=${violation.currentOrderId}`;
3092
3102
  }
@@ -6,6 +6,7 @@ import { NATIVE_CLIENT, FILL_PROCESSING, TIMING, MAINTENANCE, ORDER_TYPES } from
6
6
  import { getErrorMessage, resolveSeamMsOrNull, getErrorField } from './utils/errors.js';
7
7
  import { isOrderDoesNotExistError } from './dexbot_maintenance_runtime.js';
8
8
  import { slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail } from './order/utils/math.js';
9
+ import { attributeUnmatchedFillToGrid } from './order/utils/order.js';
9
10
  import { ORDER_STATES } from './constants.js';
10
11
  const buildFillKey = lazyShim('./order/utils/order', 'buildFillKey');
11
12
  const correctAllPriceMismatches = lazyShim('./order/utils/order', 'correctAllPriceMismatches');
@@ -133,6 +134,25 @@ async function processSweepOrphanFill(bot, fill, fillOp, processedFillKeys, opts
133
134
  }
134
135
  return true;
135
136
  }
137
+ // GEOMETRY FIRST, then money. The order is unknown to the grid, but the
138
+ // fill still proves a trade at a price: attribute it (pivot + owed crawl)
139
+ // BEFORE crediting the proceeds, so a fill that never reaches the strategy
140
+ // cannot leave the LAST-FILL-GUARD pivot stale — the same split-brain the
141
+ // unmatched-fill path closes for a virtualised slot. Attribution refuses a
142
+ // price outside the frozen rail, so a shelf/manual order can never arm the
143
+ // pivot at a level this grid does not trade.
144
+ try {
145
+ const pays = fillOp?.pays;
146
+ const receives = fillOp?.receives;
147
+ attributeUnmatchedFillToGrid(bot.manager, {
148
+ orderId: fillOp?.order_id != null ? String(fillOp.order_id) : null,
149
+ paysAssetId: pays?.asset_id ?? null,
150
+ paysAmountRaw: pays?.amount ?? null,
151
+ receivesAssetId: receives?.asset_id ?? null,
152
+ receivesAmountRaw: receives?.amount ?? null,
153
+ });
154
+ }
155
+ catch { /* attribution is best-effort: never block the credit */ }
136
156
  (opts.logger ?? bot.manager.logger).log?.(`[${opts.label}] Processing funds for unknown order ${fillOp.order_id} (not in grid but crediting proceeds)`, 'warn');
137
157
  const accountingResult = await bot._applyReplaySafeOrphanFillAccounting(fill, fillOp, {
138
158
  context: opts.context,
@@ -8,7 +8,7 @@ const require = createRequire(import.meta.url);
8
8
  import { lazyShim } from './lazy_shim.js';
9
9
  import fs from 'node:fs';
10
10
  import { spawn } from 'node:child_process';
11
- import { nowIso, fireStructuralResync, resolveLastFillGuardReference } from './order/utils/system.js';
11
+ import { nowIso, fireStructuralResync, resolveLastFillGuardReference, hasUnsettledFills } from './order/utils/system.js';
12
12
  import { path } from './path_api.js';
13
13
  import * as chainOrders from './chain_orders.js';
14
14
  import * as grid from './order/grid.js';
@@ -734,6 +734,21 @@ async function maybeRunTargetedDriftReconciliation(bot, context) {
734
734
  const trigger = getTargetedSyncReason(bot);
735
735
  if (!trigger)
736
736
  return false;
737
+ // UNSETTLED-FILL GATE: a startup-style reconcile derives its window from the
738
+ // master grid. While fills are still queued / draining / in flight / owed a
739
+ // crawl, that master still holds the filled slots as ACTIVE and the boundary
740
+ // has not crawled — the top-up would restore the EXPENSIVE end of the rail
741
+ // (live incident: 8 BUYs at 1282.78 -> 1310.04 re-created from a stale
742
+ // "buy 12/20" shortfall and filled within seconds). Defer to the next tick:
743
+ // the crawl commits in the same fill cycle, after which the same shortfall
744
+ // resolves against the crawled rail. No cooldown stamp, so the retry is
745
+ // immediate once the fills settle.
746
+ const unsettled = hasUnsettledFills(bot);
747
+ if (unsettled.unsettled) {
748
+ bot._log(`[TARGETED-SYNC] Deferring ${context} reconciliation: ${unsettled.reason} — ` +
749
+ `the rail must absorb the fills before it is topped up`, 'debug');
750
+ return false;
751
+ }
737
752
  const now = Date.now();
738
753
  const cooldownMs = Number.isFinite(Number(bot._targetedDriftSyncCooldownMs))
739
754
  ? Number(bot._targetedDriftSyncCooldownMs)
@@ -6,5 +6,25 @@ declare function buildRuntimeScriptArgs({ codeRoot, scriptSegments, scriptArgs,
6
6
  scriptSegments: string[];
7
7
  scriptArgs?: string[];
8
8
  }): string[];
9
- export { buildRuntimeScriptArgs, buildRuntimeScriptPath, isDistCodeRoot, SCRIPTS_ROOT };
9
+ /**
10
+ * Run a compiled entry point in a child process with inherited stdio.
11
+ *
12
+ * Every CLI command that delegates to `dist/scripts/**`, `dist/analysis/**`,
13
+ * `dist/unlock.js` or `dist/pm2.js` needs the same four things: an existence
14
+ * check that names the entry, an inherited-stdio spawn, spawn-error propagation
15
+ * and a non-zero policy. Centralising it keeps those commands reporting
16
+ * identically instead of each one re-deriving the boilerplate.
17
+ *
18
+ * @returns the child's exit status (1 when the child died from a signal).
19
+ * @throws when the entry point is missing, cannot be spawned, or exits non-zero
20
+ * with `nonZero: 'throw'`.
21
+ */
22
+ declare function runRuntimeScript(scriptPath: string, scriptArgs: string[], { label, cwd, nonZero, }: {
23
+ /** Command name used in error messages, e.g. 'order' or 'TradingView exporter'. */
24
+ label: string;
25
+ cwd: string;
26
+ /** 'ignore' (default) returns the status so the caller can mirror it. */
27
+ nonZero?: 'ignore' | 'throw';
28
+ }): number;
29
+ export { buildRuntimeScriptArgs, buildRuntimeScriptPath, isDistCodeRoot, runRuntimeScript, SCRIPTS_ROOT };
10
30
  //# sourceMappingURL=runtime_entry.d.ts.map
@@ -2,8 +2,13 @@ import { fileURLToPath } from 'node:url';
2
2
  import { dirname as _esmDirname } from 'node:path';
3
3
  const __filename = fileURLToPath(import.meta.url);
4
4
  const __dirname = _esmDirname(__filename);
5
+ import fs from 'node:fs';
6
+ import { createRequire } from 'node:module';
5
7
  import { path } from '../path_api.js';
6
8
  import { isDistRuntime as isDistCodeRoot } from '../utils/build_dir.js';
9
+ // child_process is resolved lazily so tests (and embedded callers) can stub the
10
+ // spawn binding on the CJS module object before the first run.
11
+ const require = createRequire(import.meta.url);
7
12
  // Centralised scripts root: the directory containing the entry-point scripts.
8
13
  // At this module depth (modules/launcher/), it resolves to <root> (source)
9
14
  // or <root>/dist (compiled). All launcher modules should import this rather
@@ -28,5 +33,35 @@ function buildRuntimeScriptArgs({ codeRoot, scriptSegments, scriptArgs = [], })
28
33
  const scriptPath = buildRuntimeScriptPath(codeRoot, scriptSegments);
29
34
  return [scriptPath, ...scriptArgs];
30
35
  }
31
- export { buildRuntimeScriptArgs, buildRuntimeScriptPath, isDistCodeRoot, SCRIPTS_ROOT };
36
+ /**
37
+ * Run a compiled entry point in a child process with inherited stdio.
38
+ *
39
+ * Every CLI command that delegates to `dist/scripts/**`, `dist/analysis/**`,
40
+ * `dist/unlock.js` or `dist/pm2.js` needs the same four things: an existence
41
+ * check that names the entry, an inherited-stdio spawn, spawn-error propagation
42
+ * and a non-zero policy. Centralising it keeps those commands reporting
43
+ * identically instead of each one re-deriving the boilerplate.
44
+ *
45
+ * @returns the child's exit status (1 when the child died from a signal).
46
+ * @throws when the entry point is missing, cannot be spawned, or exits non-zero
47
+ * with `nonZero: 'throw'`.
48
+ */
49
+ function runRuntimeScript(scriptPath, scriptArgs, { label, cwd, nonZero = 'ignore', }) {
50
+ if (!fs.existsSync(scriptPath)) {
51
+ throw new Error(`${label} not found at ${scriptPath} (run npm run build first)`);
52
+ }
53
+ const { spawnSync } = require('node:child_process');
54
+ const result = spawnSync(process.execPath, [scriptPath, ...scriptArgs], {
55
+ cwd,
56
+ stdio: 'inherit',
57
+ });
58
+ if (result.error)
59
+ throw result.error;
60
+ const status = result.status ?? 1;
61
+ if (nonZero === 'throw' && status !== 0) {
62
+ throw new Error(`${label} exited with status ${status}`);
63
+ }
64
+ return status;
65
+ }
66
+ export { buildRuntimeScriptArgs, buildRuntimeScriptPath, isDistCodeRoot, runRuntimeScript, SCRIPTS_ROOT };
32
67
  //# sourceMappingURL=runtime_entry.js.map
@@ -0,0 +1,32 @@
1
+ interface RawPoolLike {
2
+ id?: string;
3
+ asset_a?: string;
4
+ asset_b?: string;
5
+ asset_ids?: string[];
6
+ share_asset?: string;
7
+ }
8
+ /** Minimal database_api read surface: `(method, args) → decoded result`. */
9
+ type ChainRead = (method: string, args?: unknown[]) => Promise<unknown>;
10
+ /** `133` / `1.19.133` → `1.19.133`; anything else (a pool token) → null. */
11
+ declare function normalizePoolRef(ref: unknown): string | null;
12
+ /** True when the reference is a numeric pool id rather than a pool token. */
13
+ declare function isPoolIdRef(ref: unknown): boolean;
14
+ /**
15
+ * True when the reference *could* name a pool (numeric id or pool-token shape).
16
+ * Used by the CLI wrappers to fail fast on junk while still accepting tokens;
17
+ * only the chain can confirm a token exists.
18
+ */
19
+ declare function isPoolRefLike(ref: unknown): boolean;
20
+ /** Pool asset ids, tolerating both `asset_a`/`asset_b` and the `asset_ids` array. */
21
+ declare function poolAssetIds(pool: RawPoolLike | null | undefined): [string | null, string | null];
22
+ /**
23
+ * Resolve one pool reference to its raw chain object.
24
+ *
25
+ * Numeric references hit `get_objects` directly; a pool token is resolved
26
+ * through `lookup_asset_symbols` (the symbol as typed, then its canonical
27
+ * UPPERCASE form) and `get_liquidity_pools_by_share_asset`.
28
+ */
29
+ declare function resolvePoolRef(read: ChainRead, ref: unknown): Promise<RawPoolLike>;
30
+ export { normalizePoolRef, isPoolIdRef, isPoolRefLike, poolAssetIds, resolvePoolRef };
31
+ export type { RawPoolLike, ChainRead };
32
+ //# sourceMappingURL=liquidity_pool_ref.d.ts.map
@@ -0,0 +1,116 @@
1
+ 'use strict';
2
+ /**
3
+ * modules/liquidity_pool_ref.ts - Liquidity-pool reference resolution.
4
+ *
5
+ * Every command that takes a pool or an asset pair (`dexbot liq`, `dexbot tv`,
6
+ * `dexbot dw`, and the liquidity analyzer behind them) accepts the same two
7
+ * pool spellings:
8
+ *
9
+ * - object id: 133 or 1.19.133
10
+ * - pool token: the symbol of the pool's LP share asset — the same value a
11
+ * bot can name in its `pool` setting.
12
+ *
13
+ * Parsing and chain lookup live here so those commands cannot drift (numeric
14
+ * ids recognised by one, pool tokens by another) and so they all report the
15
+ * same "not a pool" error.
16
+ *
17
+ * Browser-safe: the chain is reached through a caller-supplied read function,
18
+ * so the same logic serves the script wrappers (shared client), the analysis
19
+ * entries (ephemeral RPC client) and unit tests (stubs).
20
+ */
21
+ import { resolveAssetRef } from './asset_lookup.js';
22
+ const POOL_ID_RE = /^1\.19\.\d+$/;
23
+ const POOL_NUM_RE = /^\d+$/;
24
+ /** `133` / `1.19.133` → `1.19.133`; anything else (a pool token) → null. */
25
+ function normalizePoolRef(ref) {
26
+ const probe = String(ref ?? '').trim();
27
+ if (POOL_ID_RE.test(probe))
28
+ return probe;
29
+ if (POOL_NUM_RE.test(probe))
30
+ return `1.19.${probe}`;
31
+ return null;
32
+ }
33
+ /** True when the reference is a numeric pool id rather than a pool token. */
34
+ function isPoolIdRef(ref) {
35
+ return normalizePoolRef(ref) !== null;
36
+ }
37
+ // Deliberately a junk filter, not a symbol validator: the chain owns the real
38
+ // symbol rules, so this only rejects references that could never name anything
39
+ // (empty, whitespace, or pair syntax) and lets every plausible token through.
40
+ const POOL_REF_SHAPE_RE = /^[^\s/]{1,64}$/;
41
+ /**
42
+ * True when the reference *could* name a pool (numeric id or pool-token shape).
43
+ * Used by the CLI wrappers to fail fast on junk while still accepting tokens;
44
+ * only the chain can confirm a token exists.
45
+ */
46
+ function isPoolRefLike(ref) {
47
+ const probe = String(ref ?? '').trim();
48
+ return isPoolIdRef(probe) || POOL_REF_SHAPE_RE.test(probe);
49
+ }
50
+ /** Pool asset ids, tolerating both `asset_a`/`asset_b` and the `asset_ids` array. */
51
+ function poolAssetIds(pool) {
52
+ if (!pool)
53
+ return [null, null];
54
+ const ids = Array.isArray(pool.asset_ids) ? pool.asset_ids : [];
55
+ return [pool.asset_a ?? ids[0] ?? null, pool.asset_b ?? ids[1] ?? null];
56
+ }
57
+ /**
58
+ * Normalize one `get_objects` / share-asset result entry: nodes answer with the
59
+ * pool object, occasionally nested in a result array, and some wrap it as
60
+ * `{ pool: {...} }`. All three shapes resolve to the pool itself.
61
+ */
62
+ function unwrapPool(entry) {
63
+ if (Array.isArray(entry)) {
64
+ for (const inner of entry) {
65
+ const pool = unwrapPool(inner);
66
+ if (pool)
67
+ return pool;
68
+ }
69
+ return null;
70
+ }
71
+ if (!entry || typeof entry !== 'object')
72
+ return null;
73
+ const record = entry;
74
+ if (record.id)
75
+ return record;
76
+ return record.pool && record.pool.id ? record.pool : null;
77
+ }
78
+ /**
79
+ * Resolve one pool reference to its raw chain object.
80
+ *
81
+ * Numeric references hit `get_objects` directly; a pool token is resolved
82
+ * through `lookup_asset_symbols` (the symbol as typed, then its canonical
83
+ * UPPERCASE form) and `get_liquidity_pools_by_share_asset`.
84
+ */
85
+ async function resolvePoolRef(read, ref) {
86
+ const probe = String(ref ?? '').trim();
87
+ if (!probe)
88
+ throw new Error('Pool reference is empty');
89
+ const poolId = normalizePoolRef(probe);
90
+ if (poolId) {
91
+ const raw = await read('get_objects', [[poolId]]);
92
+ const pool = unwrapPool(raw);
93
+ if (!pool?.id)
94
+ throw new Error(`Liquidity pool ${poolId} not found on chain`);
95
+ return pool;
96
+ }
97
+ const shareAsset = await resolveShareAsset(read, probe);
98
+ const raw = await read('get_liquidity_pools_by_share_asset', [[shareAsset.id], false, false]);
99
+ const pools = (Array.isArray(raw) ? raw : [])
100
+ .map(unwrapPool)
101
+ .filter((entry) => entry != null);
102
+ if (pools.length === 0) {
103
+ throw new Error(`'${probe}' (${shareAsset.id}) is not a liquidity-pool token; pass a pool id (133/1.19.133) or the pool token symbol`);
104
+ }
105
+ return pools[0];
106
+ }
107
+ /** Look up the LP share asset by symbol, case-insensitively (shared resolver). */
108
+ async function resolveShareAsset(read, symbol) {
109
+ const asset = await resolveAssetRef(read, symbol);
110
+ if (!asset?.id) {
111
+ throw new Error(`Pool token '${symbol}' not found on chain (expected the pool's LP share-asset symbol or a pool id like 133/1.19.133)`);
112
+ }
113
+ return { id: String(asset.id), symbol: String(asset.symbol ?? symbol) };
114
+ }
115
+ export { normalizePoolRef, isPoolIdRef, isPoolRefLike, poolAssetIds, resolvePoolRef };
116
+ //# sourceMappingURL=liquidity_pool_ref.js.map
@@ -420,7 +420,7 @@ function _snapshotFundState(manager) {
420
420
  import { floatToBlockchainInt, getPrecisionByOrderType, getPrecisionsForManager, calculateOrderCreationFees, calculateOrderSizes, calculateRotationOrderSizes, calculateAvailableFundsValue, calculateGridSideDivergenceMetric, getPrecisionSlack, getMinOrderSize, getSingleDustThreshold, getGridBestPrices, calculateSpreadFromOrders, allocateFundsByWeights, calculateGapSlots as _mathGapSlots, pricesOnSameLevel, sameGridLevel, getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, validatePersistedBoundary, isTransientInBandRejection, adjustBudgetForBtsFees, clamp, derivePriceLevels, buildGenesisFromPriceLevels, assertSlotPriceInvariant, priceForSlot, hashPriceLevels, } from './utils/math.js';
421
421
  import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, resolveEdgeCount, edgeOrderIdSet, resolveLiveEdgeAnchorPrice, liveWindowIdSet, getOrderTypeFromUpdatedFlags } from './utils/order.js';
422
422
  import { parseSlotIndex } from './utils/slot.js';
423
- import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot, rearmLastFillPivotFromMarketFill, evaluateSpreadCorrectionReadiness, maybeRefreshLiveMarketPrice, resolveLastFillGuardReference, isLastFillGuardBlocked } from './utils/system.js';
423
+ import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot, rearmLastFillPivotFromMarketFill, evaluateSpreadCorrectionReadiness, maybeRefreshLiveMarketPrice, resolveLastFillGuardReference, isLastFillPlacementBlocked } from './utils/system.js';
424
424
  import * as MathUtils from './utils/math.js';
425
425
  import { derivePriceWithPoolRef, resolveStartPriceMode } from './utils/withPoolRef.js';
426
426
  import { getWhitelistFlags } from '../market_adapter_whitelist.js';
@@ -3235,7 +3235,14 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3235
3235
  return false;
3236
3236
  if (c?.price == null || !Number.isFinite(Number(c.price)))
3237
3237
  return false;
3238
- return isLastFillGuardBlocked(Number(c.price), railType, lastFillPivot, lastFillSide).blocked === true;
3238
+ // Judge candidates with the SAME predicate the placement guards use
3239
+ // (direction rule + same grid level). The raw-pivot direction check
3240
+ // this replaces was blind to the same-level shape — a slot level and
3241
+ // its own execution price differ by rounding (slot 1310.046339
3242
+ // filled at 1310.060435) — so it admitted candidates that the
3243
+ // broadcast guard then refused, burning a correction cycle on a
3244
+ // guaranteed refusal and under-reporting "Excluded N".
3245
+ return isLastFillPlacementBlocked(manager, Number(c.price), railType).blocked === true;
3239
3246
  };
3240
3247
  let lastFillExcluded = 0;
3241
3248
  // A slot can legitimately appear in MORE than one candidate pool (an
@@ -4,7 +4,7 @@ import { _countActiveOnGrid, _cancelChainOrder, _recoverStartupSyncFailure, _ref
4
4
  import { ORDER_TYPES, ORDER_STATES, TIMING } from '../constants.js';
5
5
  import { readOpenOrdersGuarded } from '../chain_orders.js';
6
6
  import { getAssetFeesSafe, pricesOnSameLevel } from './utils/math.js';
7
- import { isOrderPlaced, parseChainOrder, isOrderOnChain, findLiveOrderOwnerByChainId, chainOrderMatchesSlotWithTolerance, duplicateOrphanLogInfo, resolveEdgeCount, } from './utils/order.js';
7
+ import { isOrderPlaced, parseChainOrder, isOrderOnChain, findLiveOrderOwnerByChainId, chainOrderMatchesSlotWithTolerance, duplicateOrphanLogInfo, resolveEdgeCount, reviveVirtualSlotFromChain, } from './utils/order.js';
8
8
  import * as Format from './format.js';
9
9
  import { getErrorMessage } from '../utils/errors.js';
10
10
  function _startupChainSnapshotSignature(orders, manager) {
@@ -200,6 +200,11 @@ export async function reconcileGridOrders({ manager, config, account, privateKey
200
200
  }
201
201
  const applyUpdate = manager._applyOrderUpdate.bind(manager);
202
202
  const chainIds = new Set((Array.isArray(chainOpenOrders) ? chainOpenOrders : []).map(o => o?.id).filter((id) => Boolean(id)));
203
+ const chainOrderById = new Map();
204
+ for (const raw of (Array.isArray(chainOpenOrders) ? chainOpenOrders : [])) {
205
+ if (raw?.id)
206
+ chainOrderById.set(String(raw.id), raw);
207
+ }
203
208
  for (const order of manager.orders.values()) {
204
209
  if (isOrderPlaced(order)) {
205
210
  if (!order.orderId || !chainIds.has(order.orderId)) {
@@ -228,6 +233,22 @@ export async function reconcileGridOrders({ manager, config, account, privateKey
228
233
  }, 'startup-phantom', { skipAccounting: true });
229
234
  }
230
235
  }
236
+ else if (order.orderId && chainIds.has(String(order.orderId))) {
237
+ // DARK LEVEL: the slot is not placed but its chain order is
238
+ // still live (a phantom cleanup on a truncated read, or a
239
+ // refused-commit adoption). Left as-is it is invisible to
240
+ // window accounting (_countActiveOnGrid counts only
241
+ // ACTIVE/PARTIAL) while its order still counts in chainCount —
242
+ // so this side reads a shortfall it can never repair, and the
243
+ // planner sees a free level that already holds an order (the
244
+ // duplicate-price precondition). Revive in place: no broadcast,
245
+ // and only when the order really rests at this slot's level.
246
+ const rawChain = chainOrderById.get(String(order.orderId)) ?? null;
247
+ const parsedChain = rawChain ? parseChainOrder(rawChain, manager.assets) : null;
248
+ // The helper logs the revive itself (one warn line, same text
249
+ // on both call sites) — no second log here.
250
+ await reviveVirtualSlotFromChain(manager, order, parsedChain, rawChain, 'startup-revive', { skipAccounting: true });
251
+ }
231
252
  }
232
253
  const matchedChainOrderIds = new Set();
233
254
  for (const gridOrder of manager.orders.values()) {