dexbot 1.7.0 → 1.7.2

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 (115) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +3 -3
  3. package/analysis/README.md +33 -13
  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/account_resolver.js +5 -6
  8. package/dist/analysis/analyze_liquidity.js +15 -4
  9. package/dist/analysis/bot_key_utils.d.ts +44 -1
  10. package/dist/analysis/bot_key_utils.js +76 -7
  11. package/dist/analysis/fills_cache.js +2 -1
  12. package/dist/analysis/grid_correction_check.d.ts +1 -19
  13. package/dist/analysis/grid_correction_check.js +12 -30
  14. package/dist/analysis/liquidity/liquidity_chart_generator.js +190 -20
  15. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +41 -16
  16. package/dist/analysis/liquidity/liquidity_depth_model.js +49 -21
  17. package/dist/analysis/liquidity/liquidity_view.d.ts +15 -0
  18. package/dist/analysis/liquidity/liquidity_view.js +11 -0
  19. package/dist/analysis/resolve_bot_accounts.js +7 -6
  20. package/dist/analysis/trade_profitability.js +2 -1
  21. package/dist/credential-daemon.js +13 -2
  22. package/dist/dexbot.js +4 -4
  23. package/dist/modules/account_bots.d.ts +12 -1
  24. package/dist/modules/account_bots.js +7 -5
  25. package/dist/modules/account_orders.d.ts +12 -0
  26. package/dist/modules/account_orders.js +30 -0
  27. package/dist/modules/bitshares-native/transport.js +24 -6
  28. package/dist/modules/bitshares_client.d.ts +24 -6
  29. package/dist/modules/bitshares_client.js +44 -7
  30. package/dist/modules/bot_settings.d.ts +2 -0
  31. package/dist/modules/constants.d.ts +28 -3
  32. package/dist/modules/constants.js +79 -10
  33. package/dist/modules/dexbot_class.d.ts +23 -6
  34. package/dist/modules/dexbot_class.js +44 -0
  35. package/dist/modules/dexbot_cow_runtime.d.ts +128 -8
  36. package/dist/modules/dexbot_cow_runtime.js +688 -188
  37. package/dist/modules/dexbot_fill_runtime.js +124 -35
  38. package/dist/modules/dexbot_maintenance_runtime.d.ts +1 -1
  39. package/dist/modules/dexbot_maintenance_runtime.js +259 -79
  40. package/dist/modules/dexbot_startup_runtime.js +32 -20
  41. package/dist/modules/dexbot_state_recovery.d.ts +33 -1
  42. package/dist/modules/dexbot_state_recovery.js +167 -5
  43. package/dist/modules/node_connect_policy.d.ts +8 -1
  44. package/dist/modules/node_connect_policy.js +18 -2
  45. package/dist/modules/node_flap_score.d.ts +87 -0
  46. package/dist/modules/node_flap_score.js +124 -0
  47. package/dist/modules/node_health_cache.d.ts +40 -3
  48. package/dist/modules/node_health_cache.js +66 -20
  49. package/dist/modules/node_manager.d.ts +101 -19
  50. package/dist/modules/node_manager.js +255 -65
  51. package/dist/modules/order/accounting.d.ts +9 -4
  52. package/dist/modules/order/accounting.js +131 -19
  53. package/dist/modules/order/async_lock.d.ts +7 -1
  54. package/dist/modules/order/async_lock.js +7 -1
  55. package/dist/modules/order/export.js +25 -18
  56. package/dist/modules/order/fill_ledger.d.ts +99 -0
  57. package/dist/modules/order/fill_ledger.js +103 -0
  58. package/dist/modules/order/format.d.ts +24 -10
  59. package/dist/modules/order/format.js +30 -10
  60. package/dist/modules/order/grid.d.ts +75 -18
  61. package/dist/modules/order/grid.js +289 -72
  62. package/dist/modules/order/grid_reconcile.d.ts +5 -1
  63. package/dist/modules/order/grid_reconcile.js +333 -210
  64. package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
  65. package/dist/modules/order/grid_reconcile_internal.js +223 -91
  66. package/dist/modules/order/index.d.ts +18 -5
  67. package/dist/modules/order/index.js +5 -5
  68. package/dist/modules/order/lifecycle.d.ts +353 -0
  69. package/dist/modules/order/lifecycle.js +1109 -0
  70. package/dist/modules/order/manager.d.ts +277 -20
  71. package/dist/modules/order/manager.js +680 -64
  72. package/dist/modules/order/placement_lock.d.ts +102 -0
  73. package/dist/modules/order/placement_lock.js +222 -0
  74. package/dist/modules/order/strategy.js +13 -1
  75. package/dist/modules/order/sync_engine.d.ts +74 -114
  76. package/dist/modules/order/sync_engine.js +254 -198
  77. package/dist/modules/order/utils/math.d.ts +29 -4
  78. package/dist/modules/order/utils/math.js +61 -4
  79. package/dist/modules/order/utils/order.d.ts +106 -37
  80. package/dist/modules/order/utils/order.js +256 -81
  81. package/dist/modules/order/utils/system.d.ts +99 -6
  82. package/dist/modules/order/utils/system.js +249 -35
  83. package/dist/modules/order/utils/validate.d.ts +7 -1
  84. package/dist/modules/order/utils/validate.js +48 -2
  85. package/dist/modules/outcome.d.ts +54 -0
  86. package/dist/modules/outcome.js +51 -0
  87. package/dist/modules/settings_merge.d.ts +4 -0
  88. package/dist/modules/settings_merge.js +9 -0
  89. package/dist/modules/timing_policy.d.ts +82 -0
  90. package/dist/modules/timing_policy.js +244 -0
  91. package/dist/modules/types.d.ts +149 -22
  92. package/dist/scripts/analyze-credit.js +54 -17
  93. package/dist/scripts/analyze-orders.d.ts +4 -2
  94. package/dist/scripts/analyze-orders.js +113 -34
  95. package/dist/scripts/chart_targets.js +11 -15
  96. package/dist/scripts/test-credit-renewal.js +12 -5
  97. package/docs/COW_INVARIANTS.md +71 -8
  98. package/docs/DEXBOT_COMPARISON.md +6 -6
  99. package/docs/EVOLUTION.md +10 -8
  100. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  101. package/docs/GRID_PRICE_INVARIANT.md +1 -1
  102. package/docs/GRID_RECONCILE.md +18 -13
  103. package/docs/LOGGING.md +25 -1
  104. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +183 -26
  105. package/docs/README.md +23 -2
  106. package/docs/WORKFLOW.md +9 -3
  107. package/docs/architecture.md +68 -13
  108. package/docs/developer_guide.md +25 -8
  109. package/modules/README.md +6 -0
  110. package/package.json +3 -3
  111. package/scripts/README.md +16 -0
  112. package/scripts/pdev.sh +14 -1
  113. package/scripts/pmain.sh +23 -8
  114. package/scripts/ptest.sh +7 -0
  115. package/tests/README.md +30 -1
@@ -146,24 +146,17 @@ export interface ChainOrdersLike {
146
146
  wasRecentlyOwnCancelled?(orderId: string): boolean;
147
147
  [key: string]: unknown;
148
148
  }
149
- /**
150
- * Minimal runtime surface shared by the `dexbot_*_runtime.ts` layer. This is
151
- * a seeded interface to grow as each runtime file is typed — the index
152
- * signature keeps the many `_camelCase` internals reachable (as `unknown`)
153
- * while the common surface gets real types. Replace index-signature reads with
154
- * named fields as the relevant owners are typed.
155
- */
156
- /**
157
- * The DexBot runtime surface used by the `dexbot_*_runtime.ts` layer (and the
158
- * `DexBot` class itself, which structurally satisfies it). No index signature:
159
- * every member the runtime touches is enumerated, so a typo or an undeclared
160
- * internal is a compile error instead of a silent `unknown`.
161
- */
162
149
  /** Credential-daemon signing token (used until the private key is unlocked). */
163
150
  export interface SigningToken {
164
151
  accountName: string;
165
152
  socketPath?: string;
166
153
  }
154
+ /**
155
+ * The `DEXBot` runtime surface used by the `dexbot_*_runtime.ts` layer (the
156
+ * `DEXBot` class itself structurally satisfies it). No index signature: every
157
+ * member the runtime touches is enumerated, so a typo or an undeclared internal
158
+ * is a compile error instead of a silent `unknown`.
159
+ */
167
160
  export interface BotLike {
168
161
  config: GridConfig;
169
162
  manager: OrderManagerLike;
@@ -742,11 +735,11 @@ interface AccountTotalsGate {
742
735
  ok: boolean;
743
736
  [key: string]: unknown;
744
737
  }
745
- /** Accountant surface the sync engine calls directly. */
746
738
  /** Result of `accountant.processFillAccounting()`. */
747
739
  interface FillAccountingResult extends UnknownRecord {
748
740
  status: string;
749
741
  }
742
+ /** Accountant surface the sync engine calls directly. */
750
743
  interface AccountantLike {
751
744
  processFillAccounting(fillOp: unknown, fillKey: string, options?: UnknownRecord): Promise<boolean>;
752
745
  adjustTotalBalance(orderType: string, delta: number, operation: string): Promise<unknown>;
@@ -914,6 +907,8 @@ export interface AccountOrdersLike {
914
907
  }
915
908
  /** Batch-persistence handle for processed fill keys. */
916
909
  export interface ProcessedFillStoreLike {
910
+ /** In-memory booked keys (key -> processedAt). The dedupe authority at credit time. */
911
+ tracker: Map<string, number>;
917
912
  configure(options?: {
918
913
  accountOrders?: AccountOrdersLike | null;
919
914
  }): void;
@@ -959,16 +954,63 @@ interface ManagerRecoveryState {
959
954
  [key: string]: unknown;
960
955
  }
961
956
  /**
962
- * The contract the order engine consumes from `OrderManager`. This is the
963
- * decoupled interface the `modules/order/**` layer types its `manager`
964
- * parameters against, so the engine does not need to import the concrete
965
- * class (avoiding a runtime import cycle). `OrderManager` structurally
966
- * satisfies it.
957
+ * Three-valued result of an operation whose outcome is not always knowable.
967
958
  *
968
- * Optional members are either wired in later by the runtime layer
969
- * (e.g. `requestStructuralGridResync`, `notifyBoundaryUpdate`) or read only
970
- * defensively; keep them optional so partial test doubles still type-check.
959
+ * The engine used to encode this as an ad-hoc `uncertain: true` property next
960
+ * to a second ad-hoc flag (`ambiguousRead`), so the two could disagree and no
961
+ * consumer was forced to handle the third case. `unknown` is now a real
962
+ * alternative in the type: code that branches on "applied or not" fails to
963
+ * compile until it says what it does when it does not know.
964
+ */
965
+ export type OutcomeKind = 'applied' | 'rejected' | 'unknown';
966
+ /** Why the outcome is unknown. Every `unknown` must say which one it is. */
967
+ export type UnknownCause = 'timeout' | 'ambiguous-read' | 'lost-receipt' | 'unavailable';
968
+ export interface AppliedOutcome<T> {
969
+ kind: 'applied';
970
+ value: T;
971
+ }
972
+ export interface RejectedOutcome {
973
+ kind: 'rejected';
974
+ reason: string;
975
+ }
976
+ export interface UnknownOutcome {
977
+ kind: 'unknown';
978
+ cause: UnknownCause;
979
+ detail?: string;
980
+ }
981
+ export type Outcome<T = unknown> = AppliedOutcome<T> | RejectedOutcome | UnknownOutcome;
982
+ /**
983
+ * Structural mirror of `LifecycleView` (modules/order/lifecycle.ts).
984
+ *
985
+ * Declared here rather than imported so `types.ts` stays dependency-free; the
986
+ * registry's own view type is structurally assignable to it.
971
987
  */
988
+ export interface OrderLifecycleViewLike {
989
+ slotId: string | null;
990
+ orderId: string | null;
991
+ phase: 'intent' | 'broadcasting' | 'landed' | 'filling' | 'gone' | 'unknown';
992
+ evidence: 'none' | 'local' | 'broadcast-receipt' | 'chain-snapshot' | 'fill-history' | 'adoption';
993
+ recordedAt: number;
994
+ observedAt: number;
995
+ assignedAt: number;
996
+ placedAt: number;
997
+ committedAt: number;
998
+ isUnknown: boolean;
999
+ /** Phase is `unknown` or `broadcasting`: unresolved evidence, not absence. */
1000
+ isUnresolved: boolean;
1001
+ mayExistOnChain: boolean;
1002
+ isConfirmedGone: boolean;
1003
+ isIntentOnly: boolean;
1004
+ isOnChain: boolean;
1005
+ isFreshlyPlaced(graceMs?: number, now?: number): boolean;
1006
+ isRecentlyAssigned(windowMs?: number, now?: number): boolean;
1007
+ isRecentlyCommitted(windowMs?: number, now?: number): boolean;
1008
+ isInFlight(windowMs?: number, now?: number): boolean;
1009
+ isUnresolvedFresh(now?: number): boolean;
1010
+ appliedFillMatches(filledInt: number): boolean;
1011
+ /** True when the phase was recorded by evidence from outside the process. */
1012
+ isChainBacked(): boolean;
1013
+ }
972
1014
  /** Minimal surface of the credit runtime consumed by the bot/manager layer. */
973
1015
  export interface CreditRuntimeLike {
974
1016
  config: GridConfig;
@@ -978,7 +1020,41 @@ export interface CreditRuntimeLike {
978
1020
  runCreditWatchdog(): Promise<unknown>;
979
1021
  shutdown(): Promise<unknown>;
980
1022
  }
1023
+ /**
1024
+ * The contract the order engine consumes from `OrderManager`. This is the
1025
+ * decoupled interface the `modules/order/**` layer types its `manager`
1026
+ * parameters against, so the engine does not need to import the concrete
1027
+ * class (avoiding a runtime import cycle). `OrderManager` structurally
1028
+ * satisfies it.
1029
+ *
1030
+ * Optional members are either wired in later by the runtime layer
1031
+ * (e.g. `requestStructuralGridResync`, `notifyBoundaryUpdate`) or read only
1032
+ * defensively; keep them optional so partial test doubles still type-check.
1033
+ */
981
1034
  export interface OrderManagerLike {
1035
+ /**
1036
+ * Unified order-lifecycle read surface (see modules/order/lifecycle.ts).
1037
+ * Answers "does this order exist on chain, and how sure are we" from ONE
1038
+ * record instead of the per-site subsets the engine used to consult.
1039
+ */
1040
+ _lifecycle?: {
1041
+ view(identity: string | null | undefined): OrderLifecycleViewLike;
1042
+ markUnknown?(orderId: string | null | undefined, input?: {
1043
+ slotId?: string | null;
1044
+ evidence?: OrderLifecycleViewLike['evidence'];
1045
+ }): OrderLifecycleViewLike;
1046
+ markLanded?(orderId: string | null | undefined, input?: {
1047
+ slotId?: string | null;
1048
+ evidence?: OrderLifecycleViewLike['evidence'];
1049
+ phase?: OrderLifecycleViewLike['phase'];
1050
+ }): OrderLifecycleViewLike;
1051
+ };
1052
+ getLifecycle(identity: string | null | undefined): OrderLifecycleViewLike;
1053
+ getSlotLifecycle(slot: {
1054
+ id?: string;
1055
+ orderId?: string | null;
1056
+ createUncertain?: boolean;
1057
+ } | null | undefined): OrderLifecycleViewLike;
982
1058
  _consecutiveBoundaryHolds?: number;
983
1059
  /**
984
1060
  * Set by the spread-correction planner when the corrected side's rail reserves
@@ -1023,6 +1099,8 @@ export interface OrderManagerLike {
1023
1099
  targetGrid?: unknown;
1024
1100
  initialSpreadCount: number;
1025
1101
  currentSpreadCount: number;
1102
+ /** True once the spread metric has been measured (load/create); both counters are 0 before that. */
1103
+ _spreadCountKnown?: boolean;
1026
1104
  outOfSpread: number;
1027
1105
  btsBalance?: {
1028
1106
  free: number;
@@ -1053,6 +1131,7 @@ export interface OrderManagerLike {
1053
1131
  _pauseRecalcLogging: boolean;
1054
1132
  _throwOnIllegalState: boolean;
1055
1133
  _fillBatchInFlight: number;
1134
+ _gridUpdateBlockedCycles?: number;
1056
1135
  _fillProcessingLock: ManagerLock;
1057
1136
  _syncLock: ManagerLock;
1058
1137
  _divergenceLock: ManagerLock;
@@ -1142,6 +1221,10 @@ export interface OrderManagerLike {
1142
1221
  _gridBloatDetectedAt?: number;
1143
1222
  isRebalancing(): boolean;
1144
1223
  isBootstrapping(): boolean;
1224
+ beginStructuralRebuild?(reason?: string): void;
1225
+ endStructuralRebuild?(): void;
1226
+ isStructuralRebuildInProgress?(): boolean;
1227
+ structuralRebuildReason?(): string | null;
1145
1228
  isBroadcastingActive(): boolean;
1146
1229
  isPlanningActive(): boolean;
1147
1230
  setShuttingDown(value: boolean): void;
@@ -1149,6 +1232,50 @@ export interface OrderManagerLike {
1149
1232
  finishBootstrap(): void;
1150
1233
  startBroadcasting(): void;
1151
1234
  stopBroadcasting(): void;
1235
+ /** Exclusive placement region shared by every chain-mutating path. */
1236
+ acquirePlacement?: (kind: string, options?: {
1237
+ timeoutMs?: number;
1238
+ isShuttingDown?: () => boolean;
1239
+ }) => Promise<{
1240
+ kind: string;
1241
+ release(): void;
1242
+ } | null>;
1243
+ tryAcquirePlacement?: (kind: string) => {
1244
+ kind: string;
1245
+ release(): void;
1246
+ } | null;
1247
+ isPlacementActive?: () => boolean;
1248
+ /** Whether this lease still owns the region (authoritative nesting check). */
1249
+ isPlacementLeaseCurrent?: (lease: {
1250
+ kind: string;
1251
+ release(): void;
1252
+ } | null | undefined) => boolean;
1253
+ withPlacement?<T>(kind: string, fn: (lease: {
1254
+ kind: string;
1255
+ release(): void;
1256
+ }) => Promise<T>, options?: {
1257
+ timeoutMs?: number;
1258
+ isShuttingDown?: () => boolean;
1259
+ }): Promise<T | null>;
1260
+ placementKind?: () => string | null;
1261
+ placementHeldForMs?: () => number;
1262
+ /** Force-release a placement region held longer than the leak watchdog. */
1263
+ _clearStalePlacementRegion?: (maxAgeMs?: number, options?: {
1264
+ batchInFlightMs?: number;
1265
+ }) => boolean;
1266
+ /** Pass-1 chain-size markers (see note/consumeChainSizeAppliedFillAmount). */
1267
+ _chainSizeAppliedFills?: Map<string, {
1268
+ filledInt: number;
1269
+ at: number;
1270
+ }>;
1271
+ noteChainSizeAppliedFill?: (orderId: string, filledInt: number, maxAgeMs?: number) => void;
1272
+ consumeChainSizeAppliedFillAmount?: (orderId: string, filledInt: number, maxAgeMs?: number) => number;
1273
+ snapshotChainSizeAppliedFills?: () => Record<string, {
1274
+ filledInt: number;
1275
+ at: number;
1276
+ }>;
1277
+ restoreChainSizeAppliedFills?: (payload: unknown) => void;
1278
+ isStructuralRebuildStale?: (reason: unknown) => boolean;
1152
1279
  addBroadcastRegionEndListener(listener: () => void): void;
1153
1280
  _applySync(data: unknown, src: string): Promise<unknown>;
1154
1281
  synchronizeWithChain(data: unknown, src: string): Promise<SyncResult>;
@@ -28,20 +28,29 @@ const require = createRequire(import.meta.url);
28
28
  * debt_asset, debt_amount, collateral_asset, collateral_amount.
29
29
  *
30
30
  * Usage:
31
- * node dist/scripts/analyze-credit.js # credit-enabled bots only
32
- * node dist/scripts/analyze-credit.js <bot> # single bot (name or key)
31
+ * node dist/scripts/analyze-credit.js # credit-enabled bots only
32
+ * node dist/scripts/analyze-credit.js <bot> # single bot (name or key)
33
+ * node dist/scripts/analyze-credit.js <account> # every bot on that account
34
+ *
35
+ * The positional target matches a bot name/key, or the chain account the bot
36
+ * trades from (`preferredAccount` as a name or 1.2.x id, or the `accountId`
37
+ * stamped beside it by analysis/account_resolver.ts). Account matching is what
38
+ * makes `dexbot credit <account>` work on a shared account, where one account
39
+ * hosts several bot entries — the same target spelling `dexbot pnl` accepts.
33
40
  */
34
41
  const { BitShares, waitForConnected, disconnectClient, setSuppressConnectionLog } = require('../modules/bitshares_client');
35
42
  const { FEE_PARAMETERS } = require('../modules/constants');
36
43
  const { PATHS } = require('../modules/paths');
37
44
  const { getErrorMessage } = require('../modules/utils/errors');
38
- const { sanitizeKey } = require('../modules/utils/sanitize_key');
39
45
  const { normalizeAssetRef, normalizeAssetSymbol, isSameAssetSymbol } = require('../modules/utils/asset_symbols');
40
46
  const { loadSettingsFile, resolveRawBotEntries, normalizeBotEntries } = require('../modules/bot_settings');
41
47
  import { pathToFileURL } from 'node:url';
42
48
  // Terminal colors: centralized palette (modules/cli_colors.ts), shared with
43
49
  // `dexbot order` so both analyzers stay visually in lockstep.
44
50
  import { CLI_COLORS as colors } from '../modules/cli_colors.js';
51
+ // `<bot|account>` target matching lives in analysis/bot_key_utils so `credit`,
52
+ // `order`, `pnl` and the chart commands share one rule set.
53
+ import { matchBotTargetIn } from '../analysis/bot_key_utils.js';
45
54
  import { muteChainLogs } from '../modules/utils/chain_logs.js';
46
55
  import { setGlobalConsoleLevel } from '../modules/order/logger.js';
47
56
  import { deriveLiquidityPoolTokenValue } from '../modules/order/utils/system.js';
@@ -186,29 +195,57 @@ function mpaCollateralRaw(order) {
186
195
  async function main() {
187
196
  const rawArgs = process.argv.slice(2);
188
197
  if (rawArgs.includes('-h') || rawArgs.includes('--help')) {
189
- console.log('Usage: dexbot credit [<bot>]');
198
+ console.log('Usage: dexbot credit [<bot|account>]');
190
199
  console.log(' No args Summed MPA + borrowed-credit positions for credit-enabled bots.');
191
- console.log(' <bot> Only the named bot (matches name or sanitized key).');
200
+ console.log(' <bot> Only the named bot (matches name or bot key).');
201
+ console.log(' <account> Only the bots trading that account (preferredAccount name or 1.2.x id);');
202
+ console.log(' a shared account lists every bot entry that uses it.');
192
203
  console.log('Live chain data via get_margin_positions + get_credit_deals_by_borrower per preferredAccount.');
193
204
  process.exit(0);
194
205
  }
195
206
  const botFilter = rawArgs.find((a) => !a.startsWith('-'))?.trim().toLowerCase() || null;
196
207
  const { config } = loadSettingsFile(BOTS_FILE);
197
- let bots = normalizeBotEntries(resolveRawBotEntries(config))
198
- .filter((b) => b && b.active !== false && hasLending(b));
199
- if (botFilter) {
200
- const sanitized = sanitizeKey(botFilter);
201
- const matched = bots.filter((b) => String(b.name || '').toLowerCase() === botFilter ||
202
- sanitizeKey(String(b.name || '')) === sanitized ||
203
- String(b.botKey || '').toLowerCase() === botFilter);
204
- if (matched.length === 0) {
205
- console.log(`${colors.sell}No credit bot found for '${botFilter}'.${colors.reset}`);
208
+ // Keep every entry (with its file-order index, which unnamed bots' keys are
209
+ // derived from) so target matching cannot drift from what the runtime writes.
210
+ const allBots = normalizeBotEntries(resolveRawBotEntries(config)).filter((b) => Boolean(b));
211
+ const activeBots = allBots.filter((b) => b.active !== false);
212
+ // One account can back several bot entries, so a matched account selects all
213
+ // of them — the account-level view `dexbot credit <account>` promises.
214
+ const targets = botFilter ? matchBotTargetIn(allBots, botFilter) : [];
215
+ const targeted = botFilter ? new Set(targets.map((m) => m.meta)) : null;
216
+ let bots = activeBots.filter((b) => hasLending(b) && (!targeted || targeted.has(b)));
217
+ if (botFilter && bots.length === 0) {
218
+ const matchedEntries = targets.map((m) => m.meta);
219
+ const describe = (b) => ` - ${b.name || b.botKey || 'unnamed'}${b.preferredAccount ? ` (account: ${b.preferredAccount})` : ''}${hasLending(b) ? '' : ' (no debtPolicy)'}${b.active === false ? ' (inactive)' : ''}`;
220
+ // The `Available bots` hint keeps listing inactive entries so a disabled
221
+ // bot's name and account stay discoverable.
222
+ if (matchedEntries.length === 0) {
223
+ console.log(`${colors.sell}No credit bot or account found for '${botFilter}'.${colors.reset}`);
206
224
  console.log('Available bots:');
207
- const all = normalizeBotEntries(resolveRawBotEntries(config));
208
- all.forEach((b) => console.log(` - ${b.name}${hasLending(b) ? '' : ' (no debtPolicy)'}`));
225
+ allBots.forEach((b) => console.log(describe(b)));
226
+ process.exit(0);
227
+ }
228
+ const enabledMatches = matchedEntries.filter((b) => b.active !== false);
229
+ if (enabledMatches.length === 0) {
230
+ // Disabled bots are never reported, whatever their policy.
231
+ console.log(`${colors.yellow}Matched '${botFilter}' only on inactive entries:${colors.reset}`);
232
+ matchedEntries.forEach((b) => console.log(describe(b)));
233
+ console.log('Enable it with `dexbot enable <bot>`, or drop the filter to sum the active credit bots.');
209
234
  process.exit(0);
210
235
  }
211
- bots = matched;
236
+ // Enabled match(es) without a debtPolicy: that policy also supplies the
237
+ // per-bot asset filter, so without it a shared account's positions cannot
238
+ // be attributed. List every match — an inactive entry may still carry the
239
+ // policy and only need enabling.
240
+ console.log(`${colors.yellow}Matched '${botFilter}' but no enabled entry has debtPolicy.lending:${colors.reset}`);
241
+ matchedEntries.forEach((b) => console.log(describe(b)));
242
+ // Every enabled match lacks the policy here (a credit-enabled one would have
243
+ // been reported), so both remedies are always offered.
244
+ console.log('Add a debtPolicy via `dexbot bot` to include it in `dexbot credit`.');
245
+ if (matchedEntries.some((b) => b.active === false)) {
246
+ console.log('Disabled entries also need `dexbot enable <bot>` first.');
247
+ }
248
+ process.exit(0);
212
249
  }
213
250
  if (bots.length === 0) {
214
251
  console.log(`No credit-enabled bots found in ${BOTS_FILE} (debtPolicy.lending is empty everywhere).`);
@@ -10,13 +10,15 @@
10
10
  * - Grid slot distribution (% near center) vs grid composition
11
11
  *
12
12
  * Usage:
13
- * node dist/scripts/analyze-orders.js # terminal output
14
- * node dist/scripts/analyze-orders.js --export # standalone HTML report
13
+ * node dist/scripts/analyze-orders.js # terminal output
14
+ * node dist/scripts/analyze-orders.js <bot|account> # one bot, or every bot on an account
15
+ * node dist/scripts/analyze-orders.js --export # standalone HTML report
15
16
  */
16
17
  import { CLI_COLORS as colors } from '../modules/cli_colors.js';
17
18
  /** Loose JSON-object view used across the analyzer. */
18
19
  type JsonObj = Record<string, unknown>;
19
20
  interface GridSlot {
21
+ id?: string;
20
22
  type?: string;
21
23
  state?: string;
22
24
  price: number;
@@ -10,13 +10,16 @@
10
10
  * - Grid slot distribution (% near center) vs grid composition
11
11
  *
12
12
  * Usage:
13
- * node dist/scripts/analyze-orders.js # terminal output
14
- * node dist/scripts/analyze-orders.js --export # standalone HTML report
13
+ * node dist/scripts/analyze-orders.js # terminal output
14
+ * node dist/scripts/analyze-orders.js <bot|account> # one bot, or every bot on an account
15
+ * node dist/scripts/analyze-orders.js --export # standalone HTML report
15
16
  */
16
17
  import fs from 'node:fs';
17
18
  import path from 'node:path';
18
19
  import { formatCurrency, formatFundsValue } from '../modules/order/format.js';
19
20
  import { resolveConfiguredPriceBound } from '../modules/order/utils/order.js';
21
+ import { calculateGapSlots } from '../modules/order/utils/math.js';
22
+ import { parseSlotIndex } from '../modules/order/utils/slot.js';
20
23
  import { ORDER_TYPES, ORDER_STATES, MARKET_ADAPTER } from '../modules/constants.js';
21
24
  import { applyAsymmetricBounds } from '../market_adapter/core/asymmetric_bounds.js';
22
25
  import { PATHS } from '../modules/paths.js';
@@ -26,7 +29,10 @@ const { readJSON } = getStorage();
26
29
  import { getErrorMessage } from '../modules/utils/errors.js';
27
30
  import { toFileUrl } from '../analysis/chart_utils.js';
28
31
  import { CLI_TAGS, savedLine } from '../modules/cli_progress.js';
29
- import { isSameBotName, sanitizeKey } from '../modules/utils/sanitize_key.js';
32
+ import { isSameBotName } from '../modules/utils/sanitize_key.js';
33
+ // Bot keys and `<bot|account>` target matching are shared with the other
34
+ // analysis tools (analysis/bot_key_utils) so the commands cannot drift.
35
+ import { computeBotKey, matchBotAccountTarget, matchBotEntryTarget } from '../analysis/bot_key_utils.js';
30
36
  import { CLI_COLORS as colors } from '../modules/cli_colors.js';
31
37
  import { pathToFileURL } from 'node:url';
32
38
  const ORDERS_DIR = PATHS.ORDERS_DIR;
@@ -53,17 +59,6 @@ const HEADER_WIDTH = 11 + BAR_WIDTH;
53
59
  * Utility Functions
54
60
  * Helper functions for file I/O, formatting, and data retrieval
55
61
  */
56
- function createBotKey(bot, index) {
57
- if (bot && bot.name) {
58
- return sanitizeKey(String(bot.name));
59
- }
60
- const identifier = bot && bot.assetA && bot.assetB
61
- ? `${bot.assetA}/${bot.assetB}`
62
- : bot && bot.assetAId && bot.assetBId
63
- ? `${bot.assetAId}/${bot.assetBId}`
64
- : `bot-${index}`;
65
- return `${sanitizeKey(identifier)}-${index}`;
66
- }
67
62
  function hasOrderGrid(data) {
68
63
  if (!data || typeof data !== 'object' || Array.isArray(data))
69
64
  return false;
@@ -299,7 +294,9 @@ function getConfiguredBotConfig(botKey, botData) {
299
294
  return botsConfig.find((bot, index) => {
300
295
  if (!bot)
301
296
  return false;
302
- return createBotKey(bot, index) === botKey || (meta.name && isSameBotName(bot.name, meta.name));
297
+ // Same key generator the runtime writes with (analysis/bot_key_utils →
298
+ // modules/account_orders), so a renamed pair can never drift.
299
+ return computeBotKey(bot, index) === botKey || (meta.name && isSameBotName(bot.name, meta.name));
303
300
  }) || null;
304
301
  }
305
302
  function getOrderFileCandidate(fileName) {
@@ -395,12 +392,23 @@ function analyzeOrder(botData, config, botKey) {
395
392
  const hasBoundary = typeof botData.boundaryIdx === 'number' && Number.isFinite(botData.boundaryIdx);
396
393
  const boundaryIdx = hasBoundary ? botData.boundaryIdx : 0;
397
394
  const boundaryLess = !hasBoundary;
398
- const buySlots = boundaryLess
399
- ? grid.filter((s) => s.type === ORDER_TYPES.BUY)
400
- : grid.filter((s, i) => i <= boundaryIdx && s.type === ORDER_TYPES.BUY);
401
- const sellSlots = boundaryLess
402
- ? grid.filter((s) => s.type === ORDER_TYPES.SELL)
403
- : grid.filter((s, i) => i > boundaryIdx && s.type === ORDER_TYPES.SELL);
395
+ /** Slot identity: the parsed `slot-N` id wins over the array position (a re-sort invalidates position). */
396
+ const slotIndex = (s, i) => {
397
+ const parsed = parseSlotIndex(s?.id);
398
+ return parsed === null ? i : parsed;
399
+ };
400
+ // CLASSIFY BY SLOT TYPE, NOT BY ARRAY SLICE.
401
+ // The persisted boundary says where the rails SHOULD be; a live order can be
402
+ // stranded inside the spread band (a boundary commit moved away from it and
403
+ // GAP-EVAC has not evacuated it yet) and it keeps its rail type. Slicing by
404
+ // index (`i <= boundaryIdx`) dropped exactly those orders from every bucket:
405
+ // the report then summed to fewer slots than the grid holds AND measured the
406
+ // "real" spread from the geometry edge instead of the actual top of book
407
+ // (observed live: 2.02% reported vs 1.21% on chain, with two live buys hidden
408
+ // inside the band). Type buckets keep every order visible; the geometry
409
+ // disagreement is reported explicitly via `gapBand.inBandPlaced`.
410
+ const buySlots = grid.filter((s) => s.type === ORDER_TYPES.BUY);
411
+ const sellSlots = grid.filter((s) => s.type === ORDER_TYPES.SELL);
404
412
  const spreadSlots = grid.filter((s) => s.type === ORDER_TYPES.SPREAD);
405
413
  const activeBuySlots = buySlots.filter((s) => s.state === ORDER_STATES.ACTIVE || s.state === ORDER_STATES.PARTIAL);
406
414
  const virtualBuySlots = buySlots.filter((s) => s.state === ORDER_STATES.VIRTUAL);
@@ -425,8 +433,11 @@ function analyzeOrder(botData, config, botKey) {
425
433
  // design (a partially-placed grid IS partially masked); it is not a bug, but
426
434
  // the output should be read with that caveat in mind.
427
435
  const hasOrderId = (s) => !!(s && s.orderId);
428
- const railBuys = boundaryLess ? grid.filter((s) => s.type === ORDER_TYPES.BUY) : grid.slice(0, boundaryIdx + 1);
429
- const railSells = boundaryLess ? grid.filter((s) => s.type === ORDER_TYPES.SELL) : grid.slice(boundaryIdx + 1);
436
+ // Rail lists are type-based for the same reason as the buckets above: a
437
+ // stranded live order is still a live order on its side, and excluding it
438
+ // fabricates a tighter (geometry-edge) spread.
439
+ const railBuys = buySlots;
440
+ const railSells = sellSlots;
430
441
  const placedBuys = railBuys.filter((s) => s.type === ORDER_TYPES.BUY && hasOrderId(s));
431
442
  const placedSells = railSells.filter((s) => s.type === ORDER_TYPES.SELL && hasOrderId(s));
432
443
  const geoBuy = railBuys.filter((s) => s.type === ORDER_TYPES.BUY);
@@ -446,6 +457,45 @@ function analyzeOrder(botData, config, botKey) {
446
457
  const realSpread = bestBuySlot && bestSellSlot
447
458
  ? ((bestSellSlot.price - bestBuySlot.price) / bestBuySlot.price)
448
459
  : 0;
460
+ /**
461
+ * Gap-band occupancy: live rail orders resting strictly inside the band.
462
+ * These are the spread-collapse signature — they hold band slots that should
463
+ * be empty, so the top-of-book spread is narrower than the configured gap.
464
+ * Detection is geometry-only (slot index vs boundary/gap), matching the
465
+ * runtime's `detectGapEvacuationCandidates`. The band width comes from the
466
+ * snapshot's frozen genesis (the geometry the slots were built with), then
467
+ * the live config, then the count of SPREAD-typed slots.
468
+ */
469
+ const snapshotGapSlots = Number(botData.genesis?.gapSlots);
470
+ // Unknown geometry stays unknown: without a frozen genesis gap or a live
471
+ // config there is no band to judge, and guessing one (e.g. from the
472
+ // SPREAD-typed slot count, which includes empty rail holes) would fabricate
473
+ // an "occupied band" warning. Same absent-aware rule as the runtime.
474
+ const gapSlots = Number.isFinite(snapshotGapSlots) && snapshotGapSlots >= 0
475
+ ? Math.floor(snapshotGapSlots)
476
+ : (config
477
+ ? calculateGapSlots(config.incrementPercent, config.targetSpreadPercent, config.gridLimits)
478
+ : null);
479
+ const sellStartIdx = hasBoundary && gapSlots !== null ? boundaryIdx + 1 + gapSlots : null;
480
+ const inBandPlaced = [];
481
+ if (hasBoundary && gapSlots !== null && sellStartIdx !== null) {
482
+ grid.forEach((s, i) => {
483
+ if (!hasOrderId(s))
484
+ return;
485
+ const idx = slotIndex(s, i);
486
+ if (idx > boundaryIdx && idx < sellStartIdx) {
487
+ inBandPlaced.push({
488
+ // Real snapshots always carry a slot id; fall back to the chain order
489
+ // id (then the array position) so the report always names something
490
+ // an operator can act on.
491
+ id: String(s.id ?? s.orderId ?? `#${i}`),
492
+ type: String(s.type ?? '?'),
493
+ price: Number(s.price),
494
+ idx,
495
+ });
496
+ }
497
+ });
498
+ }
449
499
  let spreadDiff, targetSpread, incrementCheck;
450
500
  /**
451
501
  * Config-based Comparisons
@@ -527,6 +577,7 @@ function analyzeOrder(botData, config, botKey) {
527
577
  buy: buySlots.length,
528
578
  sell: sellSlots.length,
529
579
  spread: spreadSlots.length,
580
+ stranded: inBandPlaced.length,
530
581
  activeBuy: activeBuySlots.length,
531
582
  virtualBuy: virtualBuySlots.length,
532
583
  activeSell: activeSellSlots.length,
@@ -534,6 +585,11 @@ function analyzeOrder(botData, config, botKey) {
534
585
  partialBuy: buySlots.filter((s) => s.state === ORDER_STATES.PARTIAL).length,
535
586
  partialSell: sellSlots.filter((s) => s.state === ORDER_STATES.PARTIAL).length
536
587
  },
588
+ gapBand: {
589
+ gapSlots,
590
+ sellStartIdx,
591
+ inBandPlaced
592
+ },
537
593
  // Slot data for weight visualization
538
594
  slotData: {
539
595
  buy: buySlots,
@@ -1137,6 +1193,19 @@ function formatAnalysis(analysisInput) {
1137
1193
  else {
1138
1194
  lines.push(` Spread:${formatPercent(analysis.spread.real).padStart(6)} | Incr.:${formatPercent(analysis.increment.avg).padStart(6)}`);
1139
1195
  }
1196
+ // Spread-collapse warning: live rail orders sitting inside the gap band eat
1197
+ // the spread slots, so the reported spread is the REAL top-of-book gap (which
1198
+ // is narrower than the configured one). Naming the slots is what makes the
1199
+ // state actionable — they need a GAP-EVAC evacuation, not a config change.
1200
+ const inBandPlaced = analysis.gapBand?.inBandPlaced ?? [];
1201
+ if (inBandPlaced.length > 0) {
1202
+ const names = inBandPlaced
1203
+ .map((o) => `${o.id} ${o.type} @${formatCurrency(o.price)}`)
1204
+ .join(', ');
1205
+ lines.push(` ${colors.sell}⚠️ Spread band occupied:${colors.reset} ` +
1206
+ `${inBandPlaced.length} live order(s) inside the ${analysis.gapBand?.gapSlots ?? '?'}-slot band ` +
1207
+ `(${names}) — real spread is narrower than target; GAP-EVAC must evacuate them`);
1208
+ }
1140
1209
  // Active orders comparison
1141
1210
  if (analysis.hasConfig && analysis.coreOrdersTarget) {
1142
1211
  const buyTarget = analysis.coreOrdersTarget.buy;
@@ -1426,9 +1495,10 @@ function generateHtmlReport(analyses) {
1426
1495
  function main() {
1427
1496
  const rawArgs = process.argv.slice(2);
1428
1497
  const exportHtml = rawArgs.includes('--export');
1429
- // Positional (non-flag) args are treated as bot key filters. Example:
1430
- // node dist/scripts/analyze-orders.js <bot>
1431
- // node dist/scripts/analyze-orders.js <bot> --export
1498
+ // Positional (non-flag) args select the analysed grids: a bot name/key, or a
1499
+ // chain account (every bot trading it). Examples:
1500
+ // node dist/scripts/analyze-orders.js <bot|account>
1501
+ // node dist/scripts/analyze-orders.js <bot|account> --export
1432
1502
  const botKeyFilter = rawArgs.find((arg) => !arg.startsWith('-'))?.trim().toLowerCase() || null;
1433
1503
  if (!exportHtml) {
1434
1504
  const targetNote = botKeyFilter ? ` (filter: ${botKeyFilter})` : '';
@@ -1437,21 +1507,30 @@ function main() {
1437
1507
  }
1438
1508
  // Get all order files sorted by modification time (newest first)
1439
1509
  let { files, skippedCandidates } = getOrderFiles();
1440
- // Filter to a single bot when a bot key was requested. Also match the
1441
- // sanitized form of a bot name (e.g. "AAA-BBB" -> "aaa-bbb").
1510
+ // Filter to the requested bot or account. Target matching is the shared
1511
+ // `<bot|account>` rule set (analysis/bot_key_utils): bot key, bot name, or the
1512
+ // chain account the bot trades from (`preferredAccount` name / 1.2.x id).
1513
+ // The file's own key still matches when a snapshot has no bots.json entry.
1442
1514
  if (botKeyFilter) {
1443
- const sanitizedFilter = sanitizeKey(botKeyFilter);
1444
- const matched = files.filter((file) => String(file.botKey).toLowerCase() === botKeyFilter
1445
- || String(file.botKey).toLowerCase() === sanitizedFilter
1446
- || (file.config?.name && sanitizeKey(file.config.name) === sanitizedFilter));
1515
+ const matched = files.filter((file) => {
1516
+ const config = file.config ?? null;
1517
+ return matchBotEntryTarget(config, botKeyFilter, file.botKey) !== null
1518
+ || matchBotAccountTarget(config, botKeyFilter);
1519
+ });
1447
1520
  if (matched.length === 0) {
1448
1521
  if (exportHtml) {
1449
1522
  generateHtmlReport([]);
1450
1523
  }
1451
1524
  else {
1452
- console.log(`${colors.sell}No order grid found for bot key '${botKeyFilter}'.${colors.reset}`);
1525
+ console.log(`${colors.sell}No order grid found for '${botKeyFilter}'.${colors.reset}`);
1453
1526
  console.log('Available bots:');
1454
- files.forEach((file) => console.log(` - ${file.botKey}`));
1527
+ files.forEach((file) => {
1528
+ const config = file.config ?? null;
1529
+ const name = config?.name ? String(config.name) : '';
1530
+ const nameSuffix = name && name.toLowerCase() !== String(file.botKey).toLowerCase() ? ` (${name})` : '';
1531
+ const account = config?.preferredAccount ? ` (account: ${String(config.preferredAccount)})` : '';
1532
+ console.log(` - ${file.botKey}${nameSuffix}${account}`);
1533
+ });
1455
1534
  }
1456
1535
  process.exit(0);
1457
1536
  }
@@ -5,9 +5,8 @@
5
5
  * from drifting on which bots are recognised and how the "unknown target"
6
6
  * hint is rendered.
7
7
  */
8
- import { isSameBotName } from '../modules/utils/sanitize_key.js';
9
8
  import { isPoolIdRef, isPoolRefLike } from '../modules/liquidity_pool_ref.js';
10
- import { loadBotMeta, loadBotSettings, computeBotKey } from '../analysis/bot_key_utils.js';
9
+ import { computeBotKey, loadBotMeta, loadBotSettings, matchBotTargetIn } from '../analysis/bot_key_utils.js';
11
10
  /** Pool id targets (`133` / `1.19.x`) — delegates to the shared pool-ref rules. */
12
11
  function isPoolIdTarget(target) {
13
12
  return isPoolIdRef(target);
@@ -20,19 +19,16 @@ function isPoolTarget(target) {
20
19
  function findBotByTarget(target) {
21
20
  const settings = loadBotSettings();
22
21
  const entries = Array.isArray(settings?.bots) ? settings.bots : [];
23
- for (let i = 0; i < entries.length; i++) {
24
- const entry = entries[i];
25
- if (!entry)
26
- continue;
27
- if (isSameBotName(entry.name, target))
28
- return { botKey: computeBotKey(entry, i) ?? '', meta: entry };
29
- }
30
- const meta = loadBotMeta(target);
31
- if (meta) {
32
- const idx = entries.findIndex((entry) => isSameBotName(entry.name, meta.name));
33
- return { botKey: computeBotKey(meta, idx >= 0 ? idx : 0) ?? '', meta };
34
- }
35
- return null;
22
+ // Name/key matching is the shared `<bot|account>` rule set
23
+ // (analysis/bot_key_utils); these commands take bot targets only — an
24
+ // account can back several bots, so an account spelling would silently
25
+ // chart whichever entry came first.
26
+ const match = matchBotTargetIn(entries, target).find((m) => m.matchedBy !== 'account');
27
+ if (!match)
28
+ return null;
29
+ // loadBotMeta canonicalises the pair symbols (analysis-wide convention).
30
+ const meta = loadBotMeta(match.botKey) ?? match.meta;
31
+ return { botKey: match.botKey, meta };
36
32
  }
37
33
  /** Bot keys used in the unknown-target hint (first 8 shown by callers). */
38
34
  function knownBotKeys() {