dexbot 1.6.18 → 1.7.1

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 (146) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +24 -18
  3. package/analysis/README.md +117 -5
  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_dynamic_weight.js +2 -1
  9. package/dist/analysis/analyze_kalman.js +3 -2
  10. package/dist/analysis/analyze_liquidity.d.ts +17 -0
  11. package/dist/analysis/analyze_liquidity.js +336 -0
  12. package/dist/analysis/analyze_regime.js +3 -2
  13. package/dist/analysis/analyze_regime_windows.js +3 -2
  14. package/dist/analysis/analyze_volatility.js +3 -2
  15. package/dist/analysis/bot_key_utils.d.ts +44 -1
  16. package/dist/analysis/bot_key_utils.js +76 -7
  17. package/dist/analysis/fills_cache.js +2 -1
  18. package/dist/analysis/grid_correction_check.d.ts +1 -19
  19. package/dist/analysis/grid_correction_check.js +12 -30
  20. package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
  21. package/dist/analysis/liquidity/liquidity_chain.js +178 -0
  22. package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
  23. package/dist/analysis/liquidity/liquidity_chart_generator.js +693 -0
  24. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +166 -0
  25. package/dist/analysis/liquidity/liquidity_depth_model.js +258 -0
  26. package/dist/analysis/liquidity/liquidity_view.d.ts +53 -0
  27. package/dist/analysis/liquidity/liquidity_view.js +66 -0
  28. package/dist/analysis/resolve_bot_accounts.js +7 -6
  29. package/dist/analysis/trade_profitability.js +4 -2
  30. package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
  31. package/dist/credential-daemon.js +13 -2
  32. package/dist/dexbot.js +77 -172
  33. package/dist/modules/account_bots.d.ts +11 -1
  34. package/dist/modules/account_orders.d.ts +12 -0
  35. package/dist/modules/account_orders.js +30 -0
  36. package/dist/modules/asset_lookup.d.ts +25 -0
  37. package/dist/modules/asset_lookup.js +75 -0
  38. package/dist/modules/bitshares-native/transport.js +24 -6
  39. package/dist/modules/bitshares_client.d.ts +24 -6
  40. package/dist/modules/bitshares_client.js +44 -7
  41. package/dist/modules/bot_settings.d.ts +2 -0
  42. package/dist/modules/chain_scan.d.ts +64 -0
  43. package/dist/modules/chain_scan.js +80 -0
  44. package/dist/modules/cli_colors.d.ts +5 -0
  45. package/dist/modules/cli_colors.js +7 -0
  46. package/dist/modules/cli_progress.d.ts +51 -0
  47. package/dist/modules/cli_progress.js +113 -0
  48. package/dist/modules/constants.d.ts +26 -3
  49. package/dist/modules/constants.js +63 -8
  50. package/dist/modules/dexbot_class.d.ts +1 -6
  51. package/dist/modules/dexbot_class.js +14 -0
  52. package/dist/modules/dexbot_cow_runtime.d.ts +97 -7
  53. package/dist/modules/dexbot_cow_runtime.js +634 -136
  54. package/dist/modules/dexbot_fill_runtime.js +132 -23
  55. package/dist/modules/dexbot_maintenance_runtime.js +242 -74
  56. package/dist/modules/dexbot_startup_runtime.js +32 -20
  57. package/dist/modules/dexbot_state_recovery.d.ts +33 -1
  58. package/dist/modules/dexbot_state_recovery.js +167 -5
  59. package/dist/modules/launcher/runtime_entry.d.ts +21 -1
  60. package/dist/modules/launcher/runtime_entry.js +36 -1
  61. package/dist/modules/liquidity_pool_ref.d.ts +32 -0
  62. package/dist/modules/liquidity_pool_ref.js +116 -0
  63. package/dist/modules/node_connect_policy.d.ts +8 -1
  64. package/dist/modules/node_connect_policy.js +18 -2
  65. package/dist/modules/node_flap_score.d.ts +87 -0
  66. package/dist/modules/node_flap_score.js +124 -0
  67. package/dist/modules/node_health_cache.d.ts +40 -3
  68. package/dist/modules/node_health_cache.js +66 -20
  69. package/dist/modules/node_manager.d.ts +101 -19
  70. package/dist/modules/node_manager.js +255 -65
  71. package/dist/modules/order/accounting.js +56 -7
  72. package/dist/modules/order/format.d.ts +24 -10
  73. package/dist/modules/order/format.js +30 -10
  74. package/dist/modules/order/grid.js +91 -13
  75. package/dist/modules/order/grid_reconcile.d.ts +5 -1
  76. package/dist/modules/order/grid_reconcile.js +333 -189
  77. package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
  78. package/dist/modules/order/grid_reconcile_internal.js +298 -100
  79. package/dist/modules/order/index.d.ts +19 -1
  80. package/dist/modules/order/lifecycle.d.ts +353 -0
  81. package/dist/modules/order/lifecycle.js +1109 -0
  82. package/dist/modules/order/manager.d.ts +273 -5
  83. package/dist/modules/order/manager.js +654 -48
  84. package/dist/modules/order/placement_lock.d.ts +102 -0
  85. package/dist/modules/order/placement_lock.js +222 -0
  86. package/dist/modules/order/strategy.js +13 -1
  87. package/dist/modules/order/sync_engine.d.ts +33 -1
  88. package/dist/modules/order/sync_engine.js +241 -73
  89. package/dist/modules/order/utils/math.d.ts +39 -1
  90. package/dist/modules/order/utils/math.js +83 -1
  91. package/dist/modules/order/utils/order.d.ts +181 -5
  92. package/dist/modules/order/utils/order.js +455 -9
  93. package/dist/modules/order/utils/system.d.ts +81 -1
  94. package/dist/modules/order/utils/system.js +331 -44
  95. package/dist/modules/order/utils/validate.d.ts +7 -1
  96. package/dist/modules/order/utils/validate.js +80 -3
  97. package/dist/modules/outcome.d.ts +54 -0
  98. package/dist/modules/outcome.js +51 -0
  99. package/dist/modules/settings_merge.d.ts +4 -0
  100. package/dist/modules/settings_merge.js +9 -0
  101. package/dist/modules/timing_policy.d.ts +82 -0
  102. package/dist/modules/timing_policy.js +244 -0
  103. package/dist/modules/types.d.ts +137 -0
  104. package/dist/modules/utils/asset_symbols.d.ts +13 -2
  105. package/dist/modules/utils/asset_symbols.js +21 -2
  106. package/dist/scripts/analysis_runner.d.ts +10 -0
  107. package/dist/scripts/analysis_runner.js +33 -0
  108. package/dist/scripts/analyze-credit.js +54 -17
  109. package/dist/scripts/analyze-orders.d.ts +4 -2
  110. package/dist/scripts/analyze-orders.js +115 -35
  111. package/dist/scripts/asset.d.ts +26 -0
  112. package/dist/scripts/asset.js +165 -0
  113. package/dist/scripts/bts_distribution.d.ts +1 -0
  114. package/dist/scripts/bts_distribution.js +194 -142
  115. package/dist/scripts/chart_command.d.ts +1 -1
  116. package/dist/scripts/chart_command.js +60 -86
  117. package/dist/scripts/chart_targets.d.ts +18 -0
  118. package/dist/scripts/chart_targets.js +48 -0
  119. package/dist/scripts/dw.js +1 -1
  120. package/dist/scripts/liquid.d.ts +24 -0
  121. package/dist/scripts/liquid.js +134 -0
  122. package/dist/scripts/rich_list.js +12 -16
  123. package/dist/scripts/test-credit-renewal.js +12 -5
  124. package/dist/scripts/token_distribution.d.ts +2 -0
  125. package/dist/scripts/token_distribution.js +132 -108
  126. package/dist/scripts/tv.js +1 -1
  127. package/dist/scripts/verify-browser-bundle.js +18 -0
  128. package/docs/COW_INVARIANTS.md +69 -10
  129. package/docs/DEXBOT_COMPARISON.md +6 -6
  130. package/docs/EVOLUTION.md +10 -8
  131. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  132. package/docs/GRID_PRICE_INVARIANT.md +5 -2
  133. package/docs/GRID_RECONCILE.md +36 -11
  134. package/docs/LOGGING.md +50 -4
  135. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +177 -27
  136. package/docs/README.md +23 -2
  137. package/docs/WORKFLOW.md +12 -4
  138. package/docs/architecture.md +42 -5
  139. package/docs/developer_guide.md +25 -8
  140. package/modules/README.md +8 -1
  141. package/package.json +3 -1
  142. package/scripts/README.md +39 -7
  143. package/scripts/pdev.sh +14 -1
  144. package/scripts/pmain.sh +23 -8
  145. package/scripts/ptest.sh +7 -0
  146. package/tests/README.md +30 -1
@@ -6,9 +6,9 @@ import { readOpenOrdersGuarded } from './chain_orders.js';
6
6
  import { ORDER_TYPES, TIMING } from './constants.js';
7
7
  import * as Format from './order/format.js';
8
8
  import * as grid from './order/grid.js';
9
- import { convertToSpreadPlaceholder, parseChainOrder, isNonBlockingUnmatchedOrder } from './order/utils/order.js';
10
- import { restoreGapEvacStreaks, applyPersistedPendingCrawls, resetLastFillPivot } from './order/utils/system.js';
11
- import { blockchainToFloat, calculateGapSlots, validatePersistedBoundary, isTransientInBandRejection } from './order/utils/math.js';
9
+ import { convertToSpreadPlaceholder, parseChainOrder, isNonBlockingUnmatchedOrder, detectGapEvacuationCandidates, updateGapEvacuationStreaks } from './order/utils/order.js';
10
+ import { restoreGapEvacStreaks, applyPersistedPendingCrawls, resetLastFillPivot, hasUnsettledFills } from './order/utils/system.js';
11
+ import { blockchainToFloat, calculateGapSlots, resolveGapSlots, validatePersistedBoundary, isTransientInBandRejection } from './order/utils/math.js';
12
12
  import { ON_MISSING_GENESIS, isMissingGenesisError } from './order/genesis_policy.js';
13
13
  import { hasExecutableActions } from './order/utils/validate.js';
14
14
  import { getErrorMessage } from './utils/errors.js';
@@ -68,6 +68,7 @@ async function triggerStateRecoverySync(bot, reason = 'state recovery sync') {
68
68
  return;
69
69
  }
70
70
  bot._recoverySyncInFlight++;
71
+ bot._recoverySyncInFlightStartedAt = Date.now();
71
72
  try {
72
73
  bot.manager.logger.log(`Triggering state recovery sync (${reason})...`, 'info');
73
74
  await bot.manager.fetchAccountTotals(bot.accountId);
@@ -96,7 +97,10 @@ async function triggerStateRecoverySync(bot, reason = 'state recovery sync') {
96
97
  bot.manager.logger.log(`[RECOVERY] State recovery sync (${reason}) failed: ${getErrorMessage(err)}. Preserving current state; the next sync cycle will retry.`, 'error');
97
98
  }
98
99
  finally {
99
- bot._recoverySyncInFlight--;
100
+ bot._recoverySyncInFlight = Math.max(0, bot._recoverySyncInFlight - 1);
101
+ if (bot._recoverySyncInFlight === 0) {
102
+ bot._recoverySyncInFlightStartedAt = 0;
103
+ }
100
104
  }
101
105
  }
102
106
  /**
@@ -484,6 +488,142 @@ async function recoverFromPersistedGrid(bot) {
484
488
  return { success: false, reason: getErrorMessage(err) };
485
489
  }
486
490
  }
491
+ /**
492
+ * Rate limit for gap-evac repairs (one fill-less re-plan per bot per minute).
493
+ * The post-commit hook and the maintenance sweep can both observe the same
494
+ * stranding; without a floor a plan that fails to resolve it (guard, funds,
495
+ * crossing) would re-plan on every commit and burn broadcasts.
496
+ */
497
+ const GAP_EVAC_REPAIR_COOLDOWN_MS = 60 * TIMING.MILLISECONDS_PER_SECOND;
498
+ const _lastGapEvacRepairAt = new WeakMap();
499
+ /**
500
+ * Detect live orders resting INSIDE the committed gap band and schedule the
501
+ * repair (fill-less COW re-plan + cancel-only teeth as last resort).
502
+ *
503
+ * Why this exists: a boundary commit that moves the boundary away from a live
504
+ * order strands it inside the spread band. The plan normally evacuates it with
505
+ * a rotation in the SAME batch, but the LAST-FILL-GUARD re-proves an evacuation
506
+ * against the PRE-COMMIT geometry and refuses it as stale when the plan's own
507
+ * crawl is what created the stranding (fail-closed by design — see the
508
+ * 2026-10-30 bid-edge incident). The batch then commits the new boundary with
509
+ * the stranded order still live, and because plans are fill-driven the state
510
+ * never heals while the market is quiet: the 4-slot spread band keeps two live
511
+ * buys and the real spread collapses (observed: 1.21% against a 2.0% target).
512
+ *
513
+ * Re-planning AFTER the commit is safe where the in-batch rotation is not: the
514
+ * committed geometry is now the LIVE geometry, so the evacuation stamp passes
515
+ * `isEvacuationStampStillValid` and the rotation executes as one price update.
516
+ *
517
+ * Cheap when healthy: one `detectGapEvacuationCandidates` scan (O(grid)) and an
518
+ * early return. Callers run it on commit (writer of the stranding) and on the
519
+ * maintenance tick (covers restarts and commits from paths without a bot
520
+ * reference).
521
+ *
522
+ * @param {import('./dexbot_class.js').DEXBot} bot
523
+ * @param {string} context - Label for logging/telemetry
524
+ * @returns `{ stranded, scheduled }` — stranded slot ids found, whether a
525
+ * re-plan was scheduled.
526
+ */
527
+ function scheduleGapEvacRepair(bot, context = 'gap-evac sweep') {
528
+ const manager = bot.manager;
529
+ if (!manager || !(manager.orders instanceof Map) || manager.orders.size === 0) {
530
+ return { stranded: [], scheduled: false };
531
+ }
532
+ try {
533
+ // UNKNOWN GEOMETRY IS NOT HEALTH. Without a committed boundary (or a
534
+ // known band width) there is no band to judge, so this sweep must not
535
+ // conclude "clean" — clearing the ledger or scheduling against a guessed
536
+ // band would be the same "absent reads as 0" trap that hid the stranding
537
+ // in the first place. Same fail-closed contract as
538
+ // isEvacuationStampStillValid.
539
+ const boundaryKnown = Number.isFinite(Format.toKnownNumber(manager.boundaryIdx));
540
+ const gapKnown = Number.isFinite(Format.toKnownNumber(manager._gapSlots))
541
+ || Number.isFinite(Format.toKnownNumber(manager._genesis?.gapSlots));
542
+ if (!boundaryKnown || !gapKnown)
543
+ return { stranded: [], scheduled: false };
544
+ const gapSlots = resolveGapSlots(manager);
545
+ const candidates = detectGapEvacuationCandidates(manager.orders, manager.boundaryIdx, gapSlots, { assets: manager.assets, genesis: manager._genesis });
546
+ const streaks = manager._gapEvacStreaks instanceof Map ? manager._gapEvacStreaks : null;
547
+ if (candidates.length === 0) {
548
+ // Healthy: drop resolved ledger entries so a future return to the
549
+ // band re-arms instead of inheriting a stale cycle count.
550
+ const resolved = streaks ? streaks.size : 0;
551
+ if (streaks && resolved > 0) {
552
+ updateGapEvacuationStreaks(streaks, []);
553
+ manager.logger?.log?.(`[GAP-EVAC] Spread band clean: cleared ${resolved} resolved in-band streak(s)`, 'debug');
554
+ }
555
+ return { stranded: [], scheduled: false };
556
+ }
557
+ const stranded = candidates.map((c) => `${c.id}(${c.type})`);
558
+ // Re-derive the streak ledger against the COMMITTED geometry (drops
559
+ // resolved ids) WITHOUT counting a new observation: reconcileGrid ticks
560
+ // this same ledger at plan-build time, and counting twice per cycle
561
+ // armed the cancel-only teeth in the very cycle whose rotation was about
562
+ // to evacuate the order. Observed live: the sweep's tick plus the plan's
563
+ // tick took a restored streak of 1 to 3 (cancel threshold), the teeth
564
+ // queued a cancel for both rotation sources, the pre-batch drain
565
+ // cancelled them, and the UPDATE batch was rejected pre-broadcast with
566
+ // "2 target(s) missing on chain" → structural resync + full grid reload
567
+ // instead of two in-place price updates.
568
+ const tick = streaks
569
+ ? updateGapEvacuationStreaks(streaks, candidates, null, { increment: false })
570
+ : { streaks: {}, ready: [] };
571
+ // The cancel-only teeth stay the LAST resort. `_processGapEvacuationTeeth`
572
+ // returns the number it actually queued (it re-verifies live geometry and
573
+ // honours queued-once), so report that — not the number of candidates it
574
+ // was offered.
575
+ const queueTeeth = (ready) => {
576
+ const teeth = manager._processGapEvacuationTeeth;
577
+ if (typeof teeth !== 'function' || ready.length === 0)
578
+ return 0;
579
+ const queued = Number(teeth.call(manager, ready));
580
+ return Number.isFinite(queued) && queued > 0 ? queued : 0;
581
+ };
582
+ // The repair is a broadcast: only claim to schedule it when the bot can
583
+ // actually run a fill-less rebalance (same precondition the scheduler
584
+ // itself checks), so the log never promises a repair that cannot run.
585
+ if (typeof manager.performSafeRebalance !== 'function'
586
+ || typeof bot.updateOrdersOnChainBatch !== 'function') {
587
+ // No plan cycle can run on this path, so this sweep is the ONLY
588
+ // ticker for the observation: advance the ledger before consulting it.
589
+ const ready = streaks ? updateGapEvacuationStreaks(streaks, candidates).ready : tick.ready;
590
+ const queued = queueTeeth(ready);
591
+ manager.logger?.log?.(`[GAP-EVAC] ${stranded.length} live order(s) stranded inside the spread band ` +
592
+ `(boundary ${manager.boundaryIdx}, gap ${gapSlots}): ${stranded.join(', ')} — ` +
593
+ `no fill-less re-plan available on this path; teeth queued=${queued}`,
594
+ // Warn only when this tick actually did something; a bot shape
595
+ // without a re-plan path must not warn on every tick.
596
+ queued > 0 ? 'warn' : 'debug');
597
+ return { stranded, scheduled: false };
598
+ }
599
+ const now = Date.now();
600
+ const lastAt = _lastGapEvacRepairAt.get(bot) ?? 0;
601
+ const cooling = lastAt > 0 && (now - lastAt) < GAP_EVAC_REPAIR_COOLDOWN_MS;
602
+ if (cooling) {
603
+ // The previous re-plan either is still in flight or did not clear
604
+ // the stranding: fall back to the cancel-only teeth so a repeatedly
605
+ // unfixable slot cannot sit in the band forever. Readiness comes from
606
+ // the ledger as the PLAN cycles left it — scheduled re-plans keep
607
+ // running through the cooldown and each ticks it once, so the sweep
608
+ // must not count the same observation again.
609
+ const queued = queueTeeth(tick.ready);
610
+ manager.logger?.log?.(`[GAP-EVAC] ${stranded.length} live order(s) inside the spread band (${stranded.join(', ')}) — ` +
611
+ `repair cooldown active (${Math.round((GAP_EVAC_REPAIR_COOLDOWN_MS - (now - lastAt)) / 1000)}s left); ` +
612
+ `teeth queued=${queued}`, queued > 0 ? 'warn' : 'debug');
613
+ return { stranded, scheduled: false };
614
+ }
615
+ _lastGapEvacRepairAt.set(bot, now);
616
+ manager.logger?.log?.(`[GAP-EVAC] ${stranded.length} live order(s) stranded inside the spread band ` +
617
+ `(boundary ${manager.boundaryIdx}, gap ${gapSlots}): ${stranded.join(', ')} — ` +
618
+ `scheduling a fill-less re-plan to evacuate (${context})`, 'warn');
619
+ _schedulePostRecoveryRebalance(bot, `gap-evac repair (${context})`);
620
+ return { stranded, scheduled: true };
621
+ }
622
+ catch (err) {
623
+ bot.manager?.logger?.log?.(`[GAP-EVAC] Stranding sweep failed (non-fatal): ${getErrorMessage(err)}`, 'debug');
624
+ return { stranded: [], scheduled: false };
625
+ }
626
+ }
487
627
  /**
488
628
  * Best-effort target-grid rebalance after a snapshot reload.
489
629
  *
@@ -583,6 +723,28 @@ function _schedulePostRecoveryRebalance(bot, context) {
583
723
  async function rejectCorruptedGridSnapshot(bot, context) {
584
724
  if (!bot.manager?.checkFundDriftAfterFills)
585
725
  return false;
726
+ // A drift measured while fills are queued/draining/deferred (or while a
727
+ // COW/recovery batch is in flight) is NOT snapshot corruption: the queued
728
+ // fills still have to move the grid/books. Deleting the snapshot here
729
+ // destroys a valid grid and the following recovery does nothing
730
+ // (2026-11-03: drift 6234.93639 == the two queued fills; another snapshot
731
+ // rejected as corrupted while deferred fills were pending). Gate the
732
+ // destructive decision on a settled pipeline.
733
+ const pipeline = hasUnsettledFills(bot);
734
+ const batchInFlight = Number(bot._batchInFlight) || 0;
735
+ const recoveryInFlight = Number(bot._recoverySyncInFlight) || 0;
736
+ const placementHeld = typeof bot.manager.isPlacementActive === 'function' && bot.manager.isPlacementActive() === true;
737
+ const deferredRebalance = Number(bot.manager._deferredRebalanceAt) || 0;
738
+ if (pipeline.unsettled || batchInFlight > 0 || recoveryInFlight > 0 || placementHeld || deferredRebalance > 0) {
739
+ const why = pipeline.reason
740
+ || (batchInFlight > 0 ? 'batch in flight'
741
+ : recoveryInFlight > 0 ? 'recovery sync in flight'
742
+ : placementHeld ? `placement region held by ${bot.manager.placementKind?.() || 'unknown'}`
743
+ : 'deferred rebalance pending');
744
+ bot._warn?.(`[SNAPSHOT-REJECT] Skipping corruption check (${context}): pipeline not settled — ` +
745
+ `${why}; the snapshot is preserved and re-checked once fills settle`);
746
+ return false;
747
+ }
586
748
  const driftCheck = bot.manager.checkFundDriftAfterFills();
587
749
  if (driftCheck.isValid)
588
750
  return false;
@@ -694,5 +856,5 @@ async function targetedOrderRepair(bot, orderIds) {
694
856
  return false;
695
857
  }
696
858
  }
697
- export { persistAndRecoverIfNeeded, getRecentFillKeysSnapshot, triggerStateRecoverySync, abortFlowIfIllegalState, handleBatchHardAbort, applyRecoverableGridUpdates, recoverExplicitStaleOrders, recoverBatchSizeDrift, recoverFromPersistedGrid, rejectCorruptedGridSnapshot, targetedOrderRepair, _schedulePostRecoveryRebalance as schedulePostRecoveryRebalance };
859
+ export { persistAndRecoverIfNeeded, getRecentFillKeysSnapshot, triggerStateRecoverySync, abortFlowIfIllegalState, handleBatchHardAbort, applyRecoverableGridUpdates, recoverExplicitStaleOrders, recoverBatchSizeDrift, recoverFromPersistedGrid, rejectCorruptedGridSnapshot, targetedOrderRepair, scheduleGapEvacRepair, _schedulePostRecoveryRebalance as schedulePostRecoveryRebalance };
698
860
  //# sourceMappingURL=dexbot_state_recovery.js.map
@@ -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
@@ -41,7 +41,14 @@ type ConnectedNodePolicyAction = {
41
41
  * - `switch`: active node is blacklisted and healthy alternatives exist;
42
42
  * reconnect to the healthy set (deferred by the caller).
43
43
  * - `align`: active node is fine; keep the transport candidate list aligned
44
- * with the healthy set.
44
+ * with the healthy set, *including the node we are currently connected to*.
45
+ * The transport only keeps its socket on `connect()` when
46
+ * `nodeList.includes(activeNode)` (see bitshares-native/transport.ts), so
47
+ * dropping the active node from the candidate list forces a full
48
+ * disconnect/reconnect on the next `connectClient()` — even though the
49
+ * socket was healthy. Appending it as the last candidate is enough to keep
50
+ * the no-op path reachable and costs nothing: it is only used if every
51
+ * preferred node fails.
45
52
  * - `none`: nothing to do (health checks disabled, a reconnect is already in
46
53
  * progress, or there is no usable healthy set).
47
54
  *
@@ -5,7 +5,14 @@
5
5
  * - `switch`: active node is blacklisted and healthy alternatives exist;
6
6
  * reconnect to the healthy set (deferred by the caller).
7
7
  * - `align`: active node is fine; keep the transport candidate list aligned
8
- * with the healthy set.
8
+ * with the healthy set, *including the node we are currently connected to*.
9
+ * The transport only keeps its socket on `connect()` when
10
+ * `nodeList.includes(activeNode)` (see bitshares-native/transport.ts), so
11
+ * dropping the active node from the candidate list forces a full
12
+ * disconnect/reconnect on the next `connectClient()` — even though the
13
+ * socket was healthy. Appending it as the last candidate is enough to keep
14
+ * the no-op path reachable and costs nothing: it is only used if every
15
+ * preferred node fails.
9
16
  * - `none`: nothing to do (health checks disabled, a reconnect is already in
10
17
  * progress, or there is no usable healthy set).
11
18
  *
@@ -28,8 +35,17 @@ export function resolveConnectedNodeAction(input) {
28
35
  }
29
36
  const healthy = input.getHealthyNodes();
30
37
  if (healthy.length > 0) {
31
- return { action: 'align', nodes: healthy };
38
+ return { action: 'align', nodes: withActiveNodeLast(healthy, activeNode) };
32
39
  }
33
40
  return { action: 'none' };
34
41
  }
42
+ /**
43
+ * Healthy set with the active node appended when it is missing.
44
+ * Never reorders an existing candidate list.
45
+ */
46
+ function withActiveNodeLast(nodes, activeNode) {
47
+ if (!activeNode || nodes.includes(activeNode))
48
+ return nodes;
49
+ return [...nodes, activeNode];
50
+ }
35
51
  //# sourceMappingURL=node_connect_policy.js.map
@@ -0,0 +1,87 @@
1
+ /**
2
+ * modules/node_flap_score.ts - Time-decayed connection-churn (flapping) scoring
3
+ *
4
+ * Node selection used to rank nodes by raw RPC latency only, so the
5
+ * lowest-ping node won even when it dropped its socket every few hours. Live
6
+ * logs showed exactly that: three Cloudflare-fronted endpoints answered in
7
+ * 50-120ms and accounted for every abnormal close, while three
8
+ * 300-360ms endpoints never dropped once — and were never selected.
9
+ *
10
+ * This module turns transport drop *timestamps* into a ranking input:
11
+ *
12
+ * effectiveLatency = latencyMs + flapPenaltyMs
13
+ * flapScore = Σ 0.5 ^ (age_i / halfLife)
14
+ * flapPenaltyMs = min(flapScore * penaltyPerDrop, maxPenaltyMs)
15
+ *
16
+ * A node with no recent drops ranks on its ping alone. One drop costs
17
+ * `penaltyPerDrop` of effective latency and then fades with `halfLife`, so a
18
+ * node that flaps once and then behaves is re-admitted automatically, a node
19
+ * that keeps flapping stays at the back of the list, and nothing has to be
20
+ * "reset" by a lucky health probe (the old
21
+ * LIVE_FAILURE_HEALTH_SUCCESS_STREAK wipe-on-success counter).
22
+ *
23
+ * Everything here is pure: callers own persistence and logging. Drop history
24
+ * is bounded by the window (24h default) and capped by MAX_DROP_TIMES, so it
25
+ * is safe to persist in the shared health cache (see node_health_cache.ts).
26
+ */
27
+ /** Trailing window of drops that may influence selection. */
28
+ declare const DEFAULT_FLAP_WINDOW_MS: number;
29
+ /** Time for a drop's penalty weight to halve. */
30
+ declare const DEFAULT_FLAP_HALF_LIFE_MS: number;
31
+ /** Effective-latency cost of one *undecayed* drop. */
32
+ declare const DEFAULT_FLAP_PENALTY_MS_PER_DROP = 5000;
33
+ /** Ceiling for the decayed penalty, so a badly degraded node stays usable as a last resort. */
34
+ declare const DEFAULT_FLAP_PENALTY_MAX_MS: number;
35
+ /** Hard cap on retained drop timestamps per node (bounded persistence). */
36
+ declare const MAX_DROP_TIMES = 64;
37
+ /** Trailing window used for the reported drops/hour counters. */
38
+ declare const DROP_RATE_WINDOW_MS: number;
39
+ interface FlapScoreOptions {
40
+ nowMs?: number;
41
+ windowMs?: number;
42
+ halfLifeMs?: number;
43
+ penaltyMsPerDrop?: number;
44
+ maxPenaltyMs?: number;
45
+ }
46
+ interface DropCounters {
47
+ /** Drops inside the last hour (the literal "drops/h" signal). */
48
+ dropsLastHour: number;
49
+ /** Drops inside the trailing `windowMs` (24h by default). */
50
+ drops24h: number;
51
+ /** Averaged drops per hour across the window. */
52
+ dropsPerHour: number;
53
+ /** Decayed drop weight used for ranking. */
54
+ flapScore: number;
55
+ /** Effective latency penalty in ms. */
56
+ penaltyMs: number;
57
+ }
58
+ /**
59
+ * Drop `dropTimes` down to the ones inside the trailing window and cap the
60
+ * retained history. Always returns a new array.
61
+ */
62
+ declare function pruneDropTimes(dropTimes: unknown, nowMs?: number, windowMs?: number): number[];
63
+ /**
64
+ * Append one drop and return the pruned history. The same millisecond is
65
+ * collapsed (a close + keep-alive trip for the same socket is one event).
66
+ */
67
+ declare function recordDrop(dropTimes: unknown, nowMs?: number, windowMs?: number): number[];
68
+ /**
69
+ * Decayed drop weight: 1.0 for a drop that just happened, 0.5 after one
70
+ * half-life, ~0 after a few. Entries outside the window are ignored.
71
+ */
72
+ declare function flapScore(dropTimes: unknown, nowMs?: number, halfLifeMs?: number, windowMs?: number): number;
73
+ /** Effective-latency penalty in ms for the node's recent drops. */
74
+ declare function flapPenaltyMs(dropTimes: unknown, options?: FlapScoreOptions): number;
75
+ /**
76
+ * Latency + decayed flap penalty, the value node selection sorts on.
77
+ * Unknown latency stays `Infinity` so it never outranks a measured node.
78
+ */
79
+ declare function effectiveLatencyMs(latencyMs: number | null | undefined, dropTimes: unknown, options?: FlapScoreOptions): number;
80
+ /**
81
+ * Churn counters for logging/persistence: exact trailing-window counts plus
82
+ * the decayed score used for ranking.
83
+ */
84
+ declare function dropCounters(dropTimes: unknown, options?: FlapScoreOptions): DropCounters;
85
+ export { DEFAULT_FLAP_HALF_LIFE_MS, DEFAULT_FLAP_PENALTY_MAX_MS, DEFAULT_FLAP_PENALTY_MS_PER_DROP, DEFAULT_FLAP_WINDOW_MS, DROP_RATE_WINDOW_MS, MAX_DROP_TIMES, dropCounters, effectiveLatencyMs, flapPenaltyMs, flapScore, pruneDropTimes, recordDrop, };
86
+ export type { DropCounters, FlapScoreOptions };
87
+ //# sourceMappingURL=node_flap_score.d.ts.map