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
package/dist/dexbot.js CHANGED
@@ -47,8 +47,9 @@ const __dirname = _esmDirname(__filename);
47
47
  * Runtime: dexbot start [bot] | stop | reload | restart | delete | status | pm2
48
48
  * Trading: dexbot test <bot> | drystart <bot> | reset {all|<bot>}
49
49
  * Config: dexbot bot | key | enable {all|<bot>} | disable {all|<bot>} | default | update
50
- * Analysis: dexbot order [<bot>] | export <bot> | credit [<bot>] | rich <asset...>
51
- * dexbot tv <target> | dw <target> | pnl <account>
50
+ * Analysis: dexbot order [<bot|account>] | export <bot> | credit [<bot|account>] | rich <asset...>
51
+ * dexbot tv <target> | dw <target> | liquid <target> | pnl <account>
52
+ * dexbot asset <bts|symbol> (shorthand: dexbot a <bts|symbol>)
52
53
  * Files: dexbot clear | clear-orders | clear-market-adapter | clear-all
53
54
  *
54
55
  * NPM SCRIPTS (alternative invocation):
@@ -120,7 +121,7 @@ async function _resolveCollateralAssetId(ref) {
120
121
  }
121
122
  const { setupGracefulShutdown, registerCleanup, unregisterCleanup } = require('./modules/graceful_shutdown');
122
123
  const { collectValidationIssues, loadSettingsFile, normalizeBotEntries, resolveRawBotEntries, saveSettingsFile, } = require('./modules/bot_settings');
123
- const { buildRuntimeScriptArgs } = require('./modules/launcher/runtime_entry');
124
+ const { buildRuntimeScriptPath, runRuntimeScript } = require('./modules/launcher/runtime_entry');
124
125
  const { parseWorkerArgs, LAUNCHER_WORKER_COMMAND } = require('./modules/launcher/launch_modes');
125
126
  const { detectRuntimeMode, runtimeControlHelp, runtimeModeLabel, checkStatusTarget, resolveStatusRoute } = require('./modules/launcher/runtime_mode');
126
127
  const { PATHS, getHomeProfilesDir, getRecalculateTriggerFile, printRelocationNotices } = require('./modules/paths');
@@ -143,8 +144,8 @@ if (typeof credentialPolicy.checkPolicyFileSecurity === 'function')
143
144
  // Primary CLI driver that manages tracked bots and helper utilities such as key/bot editors.
144
145
  const PROFILES_BOTS_FILE = PATHS.PROFILES.BOTS_JSON;
145
146
  const PROFILES_DIR = PATHS.PROFILES_DIR;
146
- const CLI_COMMANDS = ['start', 'test', 'reset', 'default', 'disable', 'enable', 'drystart', 'key', 'bot', 'pm2', 'update', 'export', 'order', 'credit', 'rich', 'tv', 'dw', 'pnl', 'git', 'clear', 'clear-orders', 'clear-market-adapter', 'clear-all', 'status', 'unlock', 'delete', 'stop', 'restart', 'reload', 'help'];
147
- const COMMAND_ALIASES = { orders: 'order', keys: 'key', bots: 'bot', stat: 'status', stats: 'status', start: 'unlock', defaults: 'default', stp: 'stop', stopall: 'stop', restartall: 'restart', reloadall: 'reload' };
147
+ const CLI_COMMANDS = ['start', 'test', 'reset', 'default', 'disable', 'enable', 'drystart', 'key', 'bot', 'pm2', 'update', 'export', 'order', 'credit', 'rich', 'tv', 'dw', 'liquid', 'pnl', 'asset', 'git', 'clear', 'clear-orders', 'clear-market-adapter', 'clear-all', 'status', 'unlock', 'delete', 'stop', 'restart', 'reload', 'help'];
148
+ const COMMAND_ALIASES = { orders: 'order', keys: 'key', bots: 'bot', stat: 'status', stats: 'status', start: 'unlock', defaults: 'default', stp: 'stop', stopall: 'stop', restartall: 'restart', reloadall: 'reload', liq: 'liquid', liqu: 'liquid', liquidity: 'liquid', a: 'asset' };
148
149
  const CLI_HELP_FLAGS = ['-h', '--help'];
149
150
  const CLI_EXAMPLES_FLAG = '--cli-examples';
150
151
  const CLI_EXAMPLES = [
@@ -157,9 +158,11 @@ const CLI_EXAMPLES = [
157
158
  { title: 'Update DEXBot2', command: 'dexbot update', notes: 'Pull, install, and restart active bots.' },
158
159
  { title: 'Export bot trades', command: 'dexbot export <bot>', notes: 'Write trades and settings to CSV/JSON.' },
159
160
  { title: 'Analyze order grids', command: 'dexbot order', notes: 'Spread, increment, and funds; --export for HTML.' },
160
- { title: 'Show live credit positions', command: 'dexbot credit', notes: 'Summed MPA + borrowed-credit positions per bot.' },
161
+ { title: 'Show live credit positions', command: 'dexbot credit [<bot|account>]', notes: 'Summed MPA + borrowed-credit positions per bot (all credit bots by default).' },
161
162
  { title: 'Asset rich list', command: 'dexbot rich <asset> [<asset...>]', notes: 'Top holder(s) per asset from the chain asset holders API.' },
162
- { title: 'Chart a bot, pool, or pair', command: 'dexbot tv <bot|pool-id|AssetA/AssetB> --month 3', notes: 'OHLC chart; --feed charts MPA price-feed history.' },
163
+ { title: 'Chart a bot, pool, or pair', command: 'dexbot tv <bot|pool|AssetA/AssetB> --month 3', notes: 'OHLC chart; pool = id (133) or pool token (LP share asset); --feed charts MPA price-feed history.' },
164
+ { title: 'Liquidity depth chart', command: 'dexbot liquid <bot|pool|AssetA/AssetB>', notes: 'Order-book + AMM pool cumulative depth; pool = id or pool token (aliases: liq, liqu, liquidity).' },
165
+ { title: 'Asset supply distribution', command: 'dexbot a bts', notes: 'Where BTS sits (collateral, pools, locks, residual) + HTML report. A bare symbol (dexbot a <symbol>) covers an issued asset; canonical: asset.' },
163
166
  { title: 'PnL report', command: 'dexbot pnl <bot|account> --month 3 [--pair BASE/QUOTE]', notes: 'Self-contained HTML PnL report for the resolved bot or chain account.' }
164
167
  ];
165
168
  const STARTUP_COLORS = {
@@ -207,14 +210,19 @@ function printCLIUsage() {
207
210
  ['default', 'Reset generated settings to defaults.'],
208
211
  ['update', 'Update DEXBot2 and restart active bots.'],
209
212
  ]],
213
+ // Ordered by the investigation an operator actually runs: grid state and its
214
+ // data export, then market research, then accounting/chain context. Keep the
215
+ // README "Bot Management" block in the same order so the two cannot drift.
210
216
  ['Analysis', [
211
- ['order [<bot>]', 'Analyze persisted order grids; --export for HTML.'],
217
+ ['order [<bot|account>]', 'Analyze persisted order grids for a bot, an account (name or 1.2.x id), or all bots; --export for HTML.'],
212
218
  ['export <bot>', 'Export bot trades/settings to CSV/JSON.'],
213
- ['credit [<bot>]', 'Show live MPA and borrowed-credit positions.'],
214
- ['rich <asset...>', 'Per-asset rich list / top holder; --top N, --json.'],
215
- ['tv <target>', 'OHLC chart for <bot|pool-id|AssetA/AssetB>; --month N (default 3), --feed for MPA price-feed history.'],
219
+ ['tv <target>', 'OHLC chart for <bot|pool|AssetA/AssetB> (pool = id or pool token); --month N (default 3), --feed for MPA price-feed history.'],
216
220
  ['dw <target>', 'Dynamic-weight research chart; same targets and flags as tv.'],
221
+ ['liquid <target>', 'Liquidity depth chart for <bot|pool|AssetA/AssetB> (pool = id or pool token); --range, --depth, --steps (aliases: liq, liqu, liquidity).'],
217
222
  ['pnl <account>', 'HTML PnL report for a bot or account; --month N, optional --pair BASE/QUOTE filter.'],
223
+ ['credit [<bot|account>]', 'Show live MPA and borrowed-credit positions for a bot, an account (name or 1.2.x id), or every credit-enabled bot.'],
224
+ ['asset <bts|symbol>', 'Supply distribution: bts = core asset, bare symbol/id = issued asset; --json, --html (shorthand: a, e.g. dexbot a bts).'],
225
+ ['rich <asset...>', 'Per-asset rich list / top holder; --top N, --json.'],
218
226
  ]],
219
227
  ['Files', [
220
228
  ['clear', 'Delete log files. Stop the runtime first.'],
@@ -265,7 +273,7 @@ if (cliArgs.some(arg => CLI_HELP_FLAGS.includes(arg))) {
265
273
  // so the script prints its usage. Only scripts with offline help handling
266
274
  // belong here — forwarding to a script without it could misinterpret the
267
275
  // flag as input (e.g. a bot-name filter triggering live work).
268
- const HELP_OWNING_COMMANDS = new Set(['credit', 'rich', 'tv', 'dw', 'pnl']);
276
+ const HELP_OWNING_COMMANDS = new Set(['credit', 'rich', 'tv', 'dw', 'liquid', 'pnl', 'asset']);
269
277
  const requestedCommand = COMMAND_ALIASES[cliArgs[0]] ?? cliArgs[0];
270
278
  if (!HELP_OWNING_COMMANDS.has(requestedCommand)) {
271
279
  printCLIUsage();
@@ -842,9 +850,38 @@ async function exportBotTrades(botName) {
842
850
  process.exit(1);
843
851
  }
844
852
  }
853
+ /**
854
+ * Script-backed commands: command name → entry-point segments under the code
855
+ * root. Every entry owns its own argument parsing and usage text (the
856
+ * HELP_OWNING_COMMANDS set forwards `--help` to it), so the CLI only spawns it
857
+ * and mirrors the exit code.
858
+ */
859
+ const SCRIPT_COMMANDS = {
860
+ order: ['scripts', 'analyze-orders'],
861
+ credit: ['scripts', 'analyze-credit'],
862
+ rich: ['scripts', 'rich_list'],
863
+ git: ['scripts', 'analyze-git'],
864
+ tv: ['scripts', 'tv'],
865
+ dw: ['scripts', 'dw'],
866
+ liquid: ['scripts', 'liquid'],
867
+ pnl: ['scripts', 'pnl'],
868
+ asset: ['scripts', 'asset'],
869
+ };
870
+ /**
871
+ * Spawn a runtime entry point with inherited stdio and exit with its status.
872
+ * `rest` defaults to the CLI arguments after the command.
873
+ *
874
+ * Returns `true` after `process.exit` so a caller whose exit is intercepted
875
+ * (tests) still stops the command instead of falling through the switch.
876
+ */
877
+ function exitWithRuntimeScript(segments, label, rest = cliArgs.slice(1)) {
878
+ const status = runRuntimeScript(buildRuntimeScriptPath(__dirname, segments), rest, { label, cwd: PATHS.PROJECT_ROOT });
879
+ process.exit(status);
880
+ return true;
881
+ }
845
882
  /**
846
883
  * Parse and execute CLI commands.
847
- * Supported commands: test, drystart, reset, default, disable, enable, key, bot, pm2, update, export, order, credit, tv, dw, clear, status, unlock, help
884
+ * Supported commands: test, drystart, reset, default, disable, enable, key, bot, pm2, update, export, order, credit, tv, dw, liquid, pnl, asset, clear, status, unlock, help
848
885
  * @returns {Promise<boolean>} True if a command was handled, false otherwise
849
886
  */
850
887
  async function handleCLICommands() {
@@ -942,32 +979,12 @@ async function handleCLICommands() {
942
979
  }
943
980
  process.exit(0);
944
981
  return true;
945
- case 'pm2': {
946
- const { spawnSync } = require('child_process');
982
+ case 'pm2':
947
983
  // Forward the remaining CLI args to pm2.js so subcommands work
948
984
  // (`dexbot pm2 stop <bot>`, `dexbot pm2 restart all`, `dexbot pm2
949
- // help`...). Previously the subcommand was silently dropped and the
950
- // full-setup path ran, so `dexbot pm2 start X` started ALL bots and
951
- // `dexbot pm2 stop X` no-oped into a full setup.
952
- // buildRuntimeScriptArgs resolves the pm2 entry point under the
953
- // dist-only runtime layout (dist/pm2.js); plain node executes
954
- // compiled entries since the tsx removal.
955
- const pm2Args = buildRuntimeScriptArgs({
956
- codeRoot: __dirname,
957
- scriptSegments: ['pm2'],
958
- scriptArgs: cliArgs.slice(1),
959
- });
960
- const result = spawnSync(Config.EXEC_PATH, pm2Args, {
961
- cwd: PATHS.PROJECT_ROOT,
962
- stdio: 'inherit',
963
- });
964
- if (result.error) {
965
- console.error(`pm2: ${result.error.message}`);
966
- process.exit(1);
967
- }
968
- process.exit(result.status ?? 0);
969
- return true;
970
- }
985
+ // help`...). A dropped subcommand used to make `dexbot pm2 start X`
986
+ // start ALL bots and `dexbot pm2 stop X` no-op into a full setup.
987
+ return exitWithRuntimeScript(['pm2'], 'pm2');
971
988
  case 'update':
972
989
  setSuppressConnectionLog(true);
973
990
  require('./scripts/update');
@@ -977,118 +994,24 @@ async function handleCLICommands() {
977
994
  await exportBotTrades(target);
978
995
  process.exit(0);
979
996
  return true;
980
- case 'order': {
981
- const { spawnSync } = require('child_process');
982
- const scriptArgs = buildRuntimeScriptArgs({
983
- codeRoot: __dirname,
984
- scriptSegments: ['scripts', 'analyze-orders'],
985
- scriptArgs: cliArgs.slice(1),
986
- });
987
- const result = spawnSync(Config.EXEC_PATH, scriptArgs, {
988
- cwd: PATHS.PROJECT_ROOT,
989
- stdio: 'inherit',
990
- });
991
- if (result.error) {
992
- console.error(`order: ${result.error.message}`);
993
- process.exit(1);
994
- }
995
- process.exit(result.status ?? 0);
996
- return true;
997
- }
998
- case 'credit': {
999
- const { spawnSync } = require('child_process');
1000
- const scriptArgs = buildRuntimeScriptArgs({
1001
- codeRoot: __dirname,
1002
- scriptSegments: ['scripts', 'analyze-credit'],
1003
- scriptArgs: cliArgs.slice(1),
1004
- });
1005
- const result = spawnSync(Config.EXEC_PATH, scriptArgs, {
1006
- cwd: PATHS.PROJECT_ROOT,
1007
- stdio: 'inherit',
1008
- });
1009
- if (result.error) {
1010
- console.error(`credit: ${result.error.message}`);
1011
- process.exit(1);
1012
- }
1013
- process.exit(result.status ?? 0);
1014
- return true;
1015
- }
1016
- case 'rich': {
1017
- const { spawnSync } = require('child_process');
1018
- const scriptArgs = buildRuntimeScriptArgs({
1019
- codeRoot: __dirname,
1020
- scriptSegments: ['scripts', 'rich_list'],
1021
- scriptArgs: cliArgs.slice(1),
1022
- });
1023
- const result = spawnSync(Config.EXEC_PATH, scriptArgs, {
1024
- cwd: PATHS.PROJECT_ROOT,
1025
- stdio: 'inherit',
1026
- });
1027
- if (result.error) {
1028
- console.error(`rich: ${result.error.message}`);
1029
- process.exit(1);
1030
- }
1031
- process.exit(result.status ?? 0);
1032
- return true;
1033
- }
1034
- case 'git': {
1035
- // Repository statistics analyzer (scripts/analyze-git.ts): parses
1036
- // git history and writes analysis/charts/repo-stats.html. Git-only;
1037
- // it requires a source checkout (.git present).
1038
- const { spawnSync } = require('child_process');
1039
- const scriptArgs = buildRuntimeScriptArgs({
1040
- codeRoot: __dirname,
1041
- scriptSegments: ['scripts', 'analyze-git'],
1042
- });
1043
- const result = spawnSync(Config.EXEC_PATH, scriptArgs, {
1044
- cwd: PATHS.PROJECT_ROOT,
1045
- stdio: 'inherit',
1046
- });
1047
- if (result.error) {
1048
- console.error(`git: ${result.error.message}`);
1049
- process.exit(1);
1050
- }
1051
- process.exit(result.status ?? 0);
1052
- return true;
1053
- }
997
+ case 'order':
998
+ case 'credit':
999
+ case 'rich':
1000
+ case 'git':
1054
1001
  case 'tv':
1055
1002
  case 'dw':
1056
- case 'pnl': {
1057
- const { spawnSync } = require('child_process');
1058
- const scriptArgs = buildRuntimeScriptArgs({
1059
- codeRoot: __dirname,
1060
- scriptSegments: ['scripts', command],
1061
- scriptArgs: cliArgs.slice(1),
1062
- });
1063
- const result = spawnSync(Config.EXEC_PATH, scriptArgs, {
1064
- cwd: PATHS.PROJECT_ROOT,
1065
- stdio: 'inherit',
1066
- });
1067
- if (result.error) {
1068
- console.error(`${command}: ${result.error.message}`);
1069
- process.exit(1);
1070
- }
1071
- process.exit(result.status ?? 0);
1072
- return true;
1073
- }
1074
- case 'unlock': {
1075
- const { spawnSync } = require('child_process');
1076
- // buildRuntimeScriptArgs resolves the unlock entry point for the
1077
- // active runtime layout: dist/unlock.js when compiled, unlock.ts
1078
- // in source layouts. A hard-coded dist path silently no-ops
1079
- // (ENOENT -> exit 0), hiding the launcher.
1080
- const unlockArgs = buildRuntimeScriptArgs({
1081
- codeRoot: __dirname,
1082
- scriptSegments: ['unlock'],
1083
- scriptArgs: cliArgs.slice(1),
1084
- });
1085
- const result = spawnSync(Config.EXEC_PATH, unlockArgs, {
1086
- cwd: PATHS.PROJECT_ROOT,
1087
- stdio: 'inherit',
1088
- });
1089
- process.exit(result.status ?? 0);
1090
- return true;
1091
- }
1003
+ case 'liquid':
1004
+ case 'pnl':
1005
+ case 'asset':
1006
+ // Registered analysis/utility entry points; each one owns its
1007
+ // argument parsing, usage text and `--help` (see
1008
+ // HELP_OWNING_COMMANDS), so the CLI only forwards argv.
1009
+ return exitWithRuntimeScript(SCRIPT_COMMANDS[command], command);
1010
+ case 'unlock':
1011
+ // Resolved through buildRuntimeScriptPath for the active runtime
1012
+ // layout (dist/unlock.js when compiled). A hard-coded dist path used
1013
+ // to no-op silently (ENOENT -> exit 0), hiding the launcher.
1014
+ return exitWithRuntimeScript(['unlock'], 'unlock');
1092
1015
  case 'clear':
1093
1016
  case 'clear-orders':
1094
1017
  case 'clear-market-adapter':
@@ -1168,7 +1091,6 @@ async function handleCLICommands() {
1168
1091
  process.exit(code);
1169
1092
  return true;
1170
1093
  };
1171
- const { spawnSync } = require('child_process');
1172
1094
  // Centralized detection (modules/launcher/runtime_mode.ts), shared
1173
1095
  // with the mode-aware help output so the two cannot disagree.
1174
1096
  const runtimeInfo = detectRuntimeMode();
@@ -1176,16 +1098,8 @@ async function handleCLICommands() {
1176
1098
  // so the report matches the help banner; otherwise a live unlock
1177
1099
  // runtime is shown by delegating to `unlock status`.
1178
1100
  if (resolveStatusRoute(runtimeInfo) === 'unlock') {
1179
- const unlockArgs = buildRuntimeScriptArgs({
1180
- codeRoot: __dirname,
1181
- scriptSegments: ['unlock'],
1182
- scriptArgs: ['status', ...(target ? [target] : [])],
1183
- });
1184
- const result = spawnSync(Config.EXEC_PATH, unlockArgs, {
1185
- cwd: PATHS.PROJECT_ROOT,
1186
- stdio: 'inherit',
1187
- });
1188
- return finish(result.status ?? 0);
1101
+ const status = runRuntimeScript(buildRuntimeScriptPath(__dirname, ['unlock']), ['status', ...(target ? [target] : [])], { label: 'unlock', cwd: PATHS.PROJECT_ROOT });
1102
+ return finish(status);
1189
1103
  }
1190
1104
  // status is whole-runtime on every surface. With no unlock bot
1191
1105
  // runtime up, validate and ignore a bot name here so the behavior
@@ -1262,20 +1176,11 @@ async function handleCLICommands() {
1262
1176
  case 'delete':
1263
1177
  case 'stop':
1264
1178
  case 'restart':
1265
- case 'reload': {
1266
- const { spawnSync } = require('child_process');
1267
- const unlockArgs = buildRuntimeScriptArgs({
1268
- codeRoot: __dirname,
1269
- scriptSegments: ['unlock'],
1270
- scriptArgs: [command, ...cliArgs.slice(1)],
1271
- });
1272
- const result = spawnSync(Config.EXEC_PATH, unlockArgs, {
1273
- cwd: PATHS.PROJECT_ROOT,
1274
- stdio: 'inherit',
1275
- });
1276
- process.exit(result.status ?? 0);
1277
- return true;
1278
- }
1179
+ case 'reload':
1180
+ // The unlock runtime owns every lifecycle verb (stop/restart/
1181
+ // reload/delete) for both modes, so the CLI forwards the verb plus
1182
+ // the remaining arguments and mirrors the exit code.
1183
+ return exitWithRuntimeScript(['unlock'], command, [command, ...cliArgs.slice(1)]);
1279
1184
  case 'help':
1280
1185
  printCLIUsage();
1281
1186
  process.exit(0);
@@ -151,6 +151,12 @@ declare function loadGeneralSettings(): {
151
151
  DUST_HEALTH_CHECK_INTERVAL_MS: number;
152
152
  DUST_CANCEL_TIMEOUT_MS: number;
153
153
  BROADCAST_STALE_CLEAR_MS: number;
154
+ PENDING_BROADCAST_TTL_MS: number;
155
+ BATCH_INFLIGHT_STALE_MS: number;
156
+ RECOVERY_INFLIGHT_STALE_MS: number;
157
+ PLACEMENT_STALE_CLEAR_MS: number;
158
+ CHAIN_SIZE_APPLIED_MARKER_TTL_MS: number;
159
+ STRUCTURAL_REBUILD_DEFER_MAX_MS: number;
154
160
  BROADCAST_DEFER_SAFETY_MARGIN_MS: number;
155
161
  FILL_BROADCAST_DEFER_MAX_MS: number;
156
162
  FILL_TOTALS_RETRY_BASE_MS: number;
@@ -361,7 +367,11 @@ declare function loadGeneralSettings(): {
361
367
  BLACKLIST_THRESHOLD: number;
362
368
  BLACKLIST_COOLDOWN_MS: number;
363
369
  FAILURE_REPORT_COOLDOWN_MS: number;
364
- LIVE_FAILURE_HEALTH_SUCCESS_STREAK: number;
370
+ FAILURE_STRIKE_DECAY_MS: number;
371
+ FLAP_WINDOW_MS: number;
372
+ FLAP_HALF_LIFE_MS: number;
373
+ FLAP_PENALTY_MS_PER_DROP: number;
374
+ FLAP_PENALTY_MAX_MS: number;
365
375
  EXPECTED_CHAIN_ID: string;
366
376
  SELECTION_STRATEGY: string;
367
377
  };
@@ -298,6 +298,18 @@ declare class AccountOrders {
298
298
  type: string;
299
299
  fillsAt: number;
300
300
  } | null;
301
+ /**
302
+ * Load the persisted sync-pass-1 "size already applied" markers.
303
+ * Stored in the free-form debugInputs blob (no order-row schema change).
304
+ * Returns a sanitized `{ orderId: { filledInt, at } }` map (empty when
305
+ * absent/malformed); freshness/TTL enforcement happens manager-side.
306
+ * @param {boolean} forceReload - If true, reload from disk
307
+ * @returns {Object}
308
+ */
309
+ loadChainSizeAppliedFills(forceReload?: boolean): Record<string, {
310
+ filledInt: number;
311
+ at: number;
312
+ }>;
301
313
  /**
302
314
  * Erase a persisted last-market-fill row that restoreLastMarketFill
303
315
  * rejected (TTL expiry / malformed). Mirrors clearPersistedLastFillPivot:
@@ -589,6 +589,36 @@ class AccountOrders {
589
589
  this._ensureLoaded(forceReload);
590
590
  return normalizeLastMarketFill(this.data && this.data.lastMarketFill);
591
591
  }
592
+ /**
593
+ * Load the persisted sync-pass-1 "size already applied" markers.
594
+ * Stored in the free-form debugInputs blob (no order-row schema change).
595
+ * Returns a sanitized `{ orderId: { filledInt, at } }` map (empty when
596
+ * absent/malformed); freshness/TTL enforcement happens manager-side.
597
+ * @param {boolean} forceReload - If true, reload from disk
598
+ * @returns {Object}
599
+ */
600
+ loadChainSizeAppliedFills(forceReload = false) {
601
+ this._ensureLoaded(forceReload);
602
+ const out = {};
603
+ const stored = this.data && this.data.debugInputs
604
+ ? this.data.debugInputs.chainSizeAppliedFills
605
+ : null;
606
+ if (!stored || typeof stored !== 'object')
607
+ return out;
608
+ let count = 0;
609
+ for (const [id, raw] of Object.entries(stored)) {
610
+ if (!id || count >= 500)
611
+ continue;
612
+ const e = raw;
613
+ const filledInt = Math.round(Number(e?.filledInt));
614
+ const at = Number(e?.at);
615
+ if (!Number.isFinite(filledInt) || filledInt <= 0 || !Number.isFinite(at))
616
+ continue;
617
+ out[id] = { filledInt, at };
618
+ count++;
619
+ }
620
+ return out;
621
+ }
592
622
  /**
593
623
  * Erase a persisted last-market-fill row that restoreLastMarketFill
594
624
  * rejected (TTL expiry / malformed). Mirrors clearPersistedLastFillPivot:
@@ -0,0 +1,25 @@
1
+ /** Ids/refs per `get_assets` call; get_assets has no page limit to respect. */
2
+ declare const LOOKUP_BATCH = 250;
3
+ type ChainRead = (method: string, args: unknown[]) => Promise<unknown>;
4
+ interface RawAssetObject {
5
+ id?: string;
6
+ symbol?: string;
7
+ precision?: number;
8
+ [key: string]: unknown;
9
+ }
10
+ interface AssetLookupResult {
11
+ /** The reference exactly as the caller passed it (for error messages). */
12
+ request: string;
13
+ /** The chain object, or null when the reference does not exist. */
14
+ asset: RawAssetObject | null;
15
+ }
16
+ /**
17
+ * Resolve asset references (symbols in any case, or `1.3.x` ids), preserving
18
+ * the caller's order. Unresolvable references come back with `asset: null`.
19
+ */
20
+ declare function lookupAssetRefs(read: ChainRead, refs: unknown[]): Promise<AssetLookupResult[]>;
21
+ /** Resolve one asset reference, or null when it does not exist on chain. */
22
+ declare function resolveAssetRef(read: ChainRead, ref: unknown): Promise<RawAssetObject | null>;
23
+ export { LOOKUP_BATCH, lookupAssetRefs, resolveAssetRef };
24
+ export type { ChainRead, RawAssetObject, AssetLookupResult };
25
+ //# sourceMappingURL=asset_lookup.d.ts.map
@@ -0,0 +1,75 @@
1
+ 'use strict';
2
+ /**
3
+ * CHAIN ASSET LOOKUP (case-insensitive, one implementation)
4
+ *
5
+ * Every CLI path that takes an asset from a human — `dexbot asset <symbol>`,
6
+ * `dexbot rich <asset...>`, `dexbot liq`/`tv`/`dw` pairs, the liquidity
7
+ * analyzer's `--base/--quote`, pool tokens — resolves it through here.
8
+ *
9
+ * BitShares stores symbols canonically UPPERCASE and `get_assets` /
10
+ * `lookup_asset_symbols` are case-sensitive, so `dexbot asset token.sym`
11
+ * found nothing while `TOKEN.SYM` worked. The reference is therefore
12
+ * normalized with `normalizeAssetSymbol` (modules/utils/asset_symbols.ts) and
13
+ * looked up in ONE batched `get_assets` call, which accepts symbols and
14
+ * `1.3.x` ids alike and returns the extended asset object.
15
+ *
16
+ * Only when the canonical spelling misses is the spelling as typed retried, so
17
+ * a node that really does hold a non-canonical symbol still resolves.
18
+ *
19
+ * The reader is injected, so the module stays browser-safe.
20
+ */
21
+ import { assetSymbolCandidates } from './utils/asset_symbols.js';
22
+ /** Ids/refs per `get_assets` call; get_assets has no page limit to respect. */
23
+ const LOOKUP_BATCH = 250;
24
+ function chunk(items, size) {
25
+ const out = [];
26
+ for (let i = 0; i < items.length; i += size)
27
+ out.push(items.slice(i, i + size));
28
+ return out;
29
+ }
30
+ async function getAssets(read, refs) {
31
+ const out = [];
32
+ for (const batch of chunk(refs, LOOKUP_BATCH)) {
33
+ const rows = await read('get_assets', [batch]);
34
+ for (let i = 0; i < batch.length; i++) {
35
+ const row = Array.isArray(rows) ? rows[i] : null;
36
+ out.push(row && typeof row.id === 'string' ? row : null);
37
+ }
38
+ }
39
+ return out;
40
+ }
41
+ /**
42
+ * Resolve asset references (symbols in any case, or `1.3.x` ids), preserving
43
+ * the caller's order. Unresolvable references come back with `asset: null`.
44
+ */
45
+ async function lookupAssetRefs(read, refs) {
46
+ const requested = refs.map((ref) => String(ref ?? '').trim());
47
+ // Canonical spelling first (ids pass through), spelling as typed as fallback.
48
+ const candidates = requested.map((ref) => assetSymbolCandidates(ref));
49
+ const primary = candidates.map((list) => list[1] ?? list[0] ?? '');
50
+ // Nothing to look up for empty refs; keep the slots so order is preserved.
51
+ const indexes = requested.map((_, index) => index).filter((index) => primary[index] !== '');
52
+ const resolved = new Map();
53
+ if (indexes.length > 0) {
54
+ const rows = await getAssets(read, indexes.map((index) => primary[index]));
55
+ indexes.forEach((index, offset) => resolved.set(index, rows[offset] ?? null));
56
+ // A node could hold a non-canonical (lowercase) symbol: retry just those
57
+ // refs with the spelling as typed, once, in a single batch.
58
+ const retry = indexes.filter((index) => !resolved.get(index) && (candidates[index][0] ?? '') !== primary[index]);
59
+ if (retry.length > 0) {
60
+ const retried = await getAssets(read, retry.map((index) => candidates[index][0]));
61
+ retry.forEach((index, offset) => {
62
+ if (retried[offset])
63
+ resolved.set(index, retried[offset]);
64
+ });
65
+ }
66
+ }
67
+ return requested.map((request, index) => ({ request, asset: resolved.get(index) ?? null }));
68
+ }
69
+ /** Resolve one asset reference, or null when it does not exist on chain. */
70
+ async function resolveAssetRef(read, ref) {
71
+ const [result] = await lookupAssetRefs(read, [ref]);
72
+ return result?.asset ?? null;
73
+ }
74
+ export { LOOKUP_BATCH, lookupAssetRefs, resolveAssetRef };
75
+ //# sourceMappingURL=asset_lookup.js.map
@@ -139,11 +139,24 @@ function createTransport(config = {}) {
139
139
  }
140
140
  return false;
141
141
  }
142
- function setStatus(newStatus) {
142
+ /**
143
+ * Publish a transport status change.
144
+ *
145
+ * `displayNode` exists so teardown paths can name the node they are
146
+ * closing *after* the active-node field has been cleared. Before this, an
147
+ * intentional disconnect logged `(node=null)`, which made 120 of 172
148
+ * closes in a live log run unattributable — the single biggest hole in
149
+ * connection diagnostics.
150
+ *
151
+ * `onStatusChange` is never handed the display value: it reads the live
152
+ * transport state via getNodeUrl(), which is null after disconnect().
153
+ */
154
+ function setStatus(newStatus, displayNode) {
143
155
  if (status !== newStatus) {
144
156
  const prevStatus = status;
145
157
  status = newStatus;
146
- transportLogger.info(`status change: ${prevStatus} -> ${newStatus} (node=${nodeUrl})`);
158
+ const logNode = displayNode === undefined ? nodeUrl : displayNode;
159
+ transportLogger.info(`status change: ${prevStatus} -> ${newStatus} (node=${logNode})`);
147
160
  if (onStatusChange) {
148
161
  try {
149
162
  onStatusChange(newStatus, nodeUrl);
@@ -277,7 +290,7 @@ function createTransport(config = {}) {
277
290
  }
278
291
  });
279
292
  }
280
- function setupMessageHandler(socket) {
293
+ function setupMessageHandler(socket, socketUrl) {
281
294
  socket.onmessage = (raw) => {
282
295
  let msg;
283
296
  try {
@@ -344,7 +357,11 @@ function createTransport(config = {}) {
344
357
  };
345
358
  socket.onerror = (evt) => {
346
359
  const msg = evt && evt.message ? evt.message : 'WebSocket connection error';
347
- transportLogger.warn(`WebSocket error on ${nodeUrl}: ${msg}`);
360
+ // Name the socket's own node, not the currently active one: a
361
+ // superseded socket can still emit an error after a switch, and
362
+ // logging it against `nodeUrl` blamed the wrong node (or logged
363
+ // `on null`).
364
+ transportLogger.warn(`WebSocket error on ${socketUrl}: ${msg}`);
348
365
  };
349
366
  }
350
367
  function _onConnected(socket, url, idx, wasReconnect) {
@@ -367,7 +384,7 @@ function createTransport(config = {}) {
367
384
  reconnectAttempts = 0;
368
385
  // A successful connection clears the deprioritization for this node.
369
386
  failedNodes.delete(url);
370
- setupMessageHandler(socket);
387
+ setupMessageHandler(socket, url);
371
388
  return (async () => {
372
389
  if (validateNode) {
373
390
  await validateNode();
@@ -566,8 +583,9 @@ function createTransport(config = {}) {
566
583
  catch (_) { }
567
584
  }
568
585
  connectingSockets.clear();
586
+ const closingNode = nodeUrl;
569
587
  nodeUrl = null;
570
- setStatus('closed');
588
+ setStatus('closed', closingNode);
571
589
  }
572
590
  /**
573
591
  * Force a reconnect on the active connection, preferring a different node.