dexbot 1.6.12 → 1.6.13

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 (170) hide show
  1. package/CHANGELOG.md +33 -1
  2. package/analysis/README.md +9 -11
  3. package/analysis/ama_fitting/README.md +5 -3
  4. package/claw/README.md +1 -0
  5. package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
  6. package/claw/modules/claw_bridge.ts +0 -3
  7. package/claw/modules/claw_skill_md.ts +1 -0
  8. package/claw/package.json +3 -3
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/claw/tsconfig.json +2 -2
  12. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  13. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  14. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  15. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  16. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  17. package/dist/analysis/analyze_args.d.ts +12 -0
  18. package/dist/analysis/analyze_args.js +20 -0
  19. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  20. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  21. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  22. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  23. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  24. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  25. package/dist/analysis/chart_ui.d.ts +30 -1
  26. package/dist/analysis/chart_ui.js +37 -1
  27. package/dist/analysis/fills_cache.d.ts +3 -23
  28. package/dist/analysis/fills_cache.js +3 -84
  29. package/dist/analysis/fills_source.d.ts +31 -1
  30. package/dist/analysis/fills_source.js +69 -1
  31. package/dist/analysis/grid_correction_check.d.ts +1 -23
  32. package/dist/analysis/grid_correction_check.js +15 -58
  33. package/dist/analysis/math_utils.d.ts +85 -1
  34. package/dist/analysis/math_utils.js +116 -1
  35. package/dist/analysis/price_sources.d.ts +22 -1
  36. package/dist/analysis/price_sources.js +23 -0
  37. package/dist/analysis/resolve_source.js +31 -10
  38. package/dist/analysis/trade_profitability.d.ts +6 -0
  39. package/dist/analysis/trade_profitability.js +23 -97
  40. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  41. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  42. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +2 -15
  43. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  44. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  45. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  46. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  47. package/dist/analysis/worker_pool.d.ts +38 -0
  48. package/dist/analysis/worker_pool.js +67 -0
  49. package/dist/dexbot.js +67 -48
  50. package/dist/market_adapter/ama_signal_runner.js +21 -54
  51. package/dist/market_adapter/candle_utils.d.ts +7 -1
  52. package/dist/market_adapter/candle_utils.js +11 -1
  53. package/dist/market_adapter/cli_args.d.ts +22 -0
  54. package/dist/market_adapter/cli_args.js +30 -0
  55. package/dist/market_adapter/core/config_normalizers.js +11 -6
  56. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  57. package/dist/market_adapter/core/kibana_candles.js +3 -2
  58. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  59. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  60. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  61. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  62. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  63. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  64. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  65. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  66. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  67. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  68. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  69. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  70. package/dist/market_adapter/inputs/window_cache.js +52 -177
  71. package/dist/market_adapter/interval_utils.d.ts +11 -1
  72. package/dist/market_adapter/interval_utils.js +16 -1
  73. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  74. package/dist/market_adapter/lp_chart_runner.js +37 -19
  75. package/dist/market_adapter/market_adapter.js +27 -72
  76. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  77. package/dist/market_adapter/utils/data_discovery.js +220 -27
  78. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  79. package/dist/market_adapter/utils/month_shards.js +237 -0
  80. package/dist/modules/account_bots.d.ts +1 -0
  81. package/dist/modules/account_bots.js +102 -121
  82. package/dist/modules/account_orders.d.ts +13 -0
  83. package/dist/modules/account_orders.js +38 -44
  84. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  85. package/dist/modules/bitshares-native/chain_client.js +14 -13
  86. package/dist/modules/bitshares-native/resolvers.js +22 -25
  87. package/dist/modules/bitshares-native/serial/types.js +22 -50
  88. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  89. package/dist/modules/bot_defaults.d.ts +2 -1
  90. package/dist/modules/bot_settings.d.ts +1 -1
  91. package/dist/modules/broadcast_failure.d.ts +2 -1
  92. package/dist/modules/chain_orders.d.ts +1 -1
  93. package/dist/modules/chain_orders.js +51 -96
  94. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  95. package/dist/modules/constants.d.ts +7 -1
  96. package/dist/modules/constants.js +20 -1
  97. package/dist/modules/cr_planner.d.ts +1 -1
  98. package/dist/modules/cr_planner.js +1 -5
  99. package/dist/modules/credit_pricing.d.ts +2 -1
  100. package/dist/modules/credit_pricing.js +36 -40
  101. package/dist/modules/credit_runtime.d.ts +7 -0
  102. package/dist/modules/credit_runtime.js +45 -73
  103. package/dist/modules/daemon_node_health.d.ts +4 -3
  104. package/dist/modules/dexbot_class.d.ts +28 -17
  105. package/dist/modules/dexbot_class.js +105 -58
  106. package/dist/modules/dexbot_cow_runtime.d.ts +0 -7
  107. package/dist/modules/dexbot_cow_runtime.js +54 -28
  108. package/dist/modules/dexbot_credential_client.d.ts +0 -7
  109. package/dist/modules/dexbot_credential_client.js +1 -2
  110. package/dist/modules/dexbot_fill_runtime.d.ts +1 -2
  111. package/dist/modules/dexbot_fill_runtime.js +5 -6
  112. package/dist/modules/dexbot_maintenance_runtime.d.ts +20 -3
  113. package/dist/modules/dexbot_maintenance_runtime.js +84 -69
  114. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  115. package/dist/modules/dexbot_startup_runtime.js +13 -14
  116. package/dist/modules/general_settings.d.ts +1 -1
  117. package/dist/modules/graceful_shutdown.js +17 -11
  118. package/dist/modules/key_store.js +0 -1
  119. package/dist/modules/lazy_shim.d.ts +11 -0
  120. package/dist/modules/lazy_shim.js +16 -0
  121. package/dist/modules/node_connect_policy.d.ts +3 -2
  122. package/dist/modules/node_failure_ledger.d.ts +6 -5
  123. package/dist/modules/order/format.d.ts +12 -3
  124. package/dist/modules/order/format.js +15 -3
  125. package/dist/modules/order/genesis_policy.d.ts +3 -3
  126. package/dist/modules/order/genesis_policy.js +5 -2
  127. package/dist/modules/order/grid.d.ts +4 -2
  128. package/dist/modules/order/grid.js +91 -35
  129. package/dist/modules/order/index.d.ts +1 -0
  130. package/dist/modules/order/logger.d.ts +1 -8
  131. package/dist/modules/order/logger.js +0 -9
  132. package/dist/modules/order/manager.d.ts +9 -13
  133. package/dist/modules/order/manager.js +33 -50
  134. package/dist/modules/order/utils/order.js +39 -35
  135. package/dist/modules/order/utils/system.d.ts +9 -29
  136. package/dist/modules/order/utils/system.js +17 -2
  137. package/dist/modules/order/utils/validate.js +2 -2
  138. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  139. package/dist/modules/paths.js +32 -34
  140. package/dist/modules/runtime_settings.d.ts +2 -4
  141. package/dist/modules/settings_merge.d.ts +2 -2
  142. package/dist/modules/socket_json_client.d.ts +2 -1
  143. package/dist/modules/types.d.ts +42 -27
  144. package/dist/modules/utils/errors.js +1 -3
  145. package/dist/modules/version_notice.d.ts +11 -10
  146. package/dist/pm2.d.ts +0 -1
  147. package/dist/pm2.js +56 -35
  148. package/dist/scripts/analyze-git.js +2 -15
  149. package/dist/scripts/chart_command.js +2 -2
  150. package/dist/scripts/check_any.d.ts +4 -0
  151. package/dist/scripts/check_any.js +53 -21
  152. package/dist/scripts/diagnose-pool-history.js +1 -6
  153. package/dist/scripts/run-tests.js +0 -1
  154. package/dist/scripts/sync-version.js +0 -10
  155. package/docs/BITSHARES_ONBOARDING.md +8 -12
  156. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  157. package/docs/DEXBOT_COMPARISON.md +6 -6
  158. package/docs/EVOLUTION.md +9 -8
  159. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  160. package/docs/README.md +1 -1
  161. package/docs/WORKFLOW.md +1 -0
  162. package/docs/architecture.md +19 -10
  163. package/market_adapter/README.md +6 -4
  164. package/package.json +6 -9
  165. package/scripts/README.md +43 -38
  166. package/tests/README.md +25 -10
  167. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  168. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  169. package/scripts/git-viewer.sh +0 -489
  170. package/scripts/postinstall.js +0 -16
@@ -414,22 +414,7 @@ async function askWeightDistributionValue(promptText, defaultValue, showLegend)
414
414
  if (showLegend) {
415
415
  console.log(` ${COLORS.cyan}-1=SuperValley${COLORS.reset} ←→ ${COLORS.blue}0=Valley${COLORS.reset} ←→ ${COLORS.gray}0.5=Neutral${COLORS.reset} ←→ ${COLORS.bold}${COLORS.orange}1=Mountain${COLORS.reset} ←→ ${COLORS.redStrong}2=SuperMountain${COLORS.reset}`);
416
416
  }
417
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${defaultValue}]` : '';
418
- const raw = (await readInput(`${promptText}${suffix}: `)).trim();
419
- if (raw === '\x1b')
420
- return '\x1b';
421
- if (raw === '')
422
- return defaultValue;
423
- const parsed = Number(raw);
424
- if (Number.isNaN(parsed)) {
425
- console.log('Please enter a valid number.');
426
- return askWeightDistributionValue(promptText, defaultValue, showLegend);
427
- }
428
- if (parsed < MIN_WEIGHT || parsed > MAX_WEIGHT) {
429
- console.log(`Weight distribution must be between ${MIN_WEIGHT} and ${MAX_WEIGHT}.`);
430
- return askWeightDistributionValue(promptText, defaultValue, showLegend);
431
- }
432
- return parsed;
417
+ return askNumeric(promptText, defaultValue, (parsed) => parsed < MIN_WEIGHT || parsed > MAX_WEIGHT ? `Weight distribution must be between ${MIN_WEIGHT} and ${MAX_WEIGHT}.` : null);
433
418
  }
434
419
  /**
435
420
  * Prompts the user for a weight distribution value with a legend.
@@ -723,6 +708,24 @@ async function askNumeric(promptText, defaultValue, validate) {
723
708
  }
724
709
  return parsed;
725
710
  }
711
+ async function askTypedInput(options) {
712
+ options.onBeforePrompt?.();
713
+ const { promptText, defaultValue } = options;
714
+ const shown = defaultValue !== undefined && defaultValue !== null
715
+ ? ` [${options.formatDefault ? options.formatDefault(defaultValue) : String(defaultValue)}]`
716
+ : '';
717
+ const raw = (await readInput(`${promptText}${shown}: `, options.colorize ? { colorize: options.colorize } : {})).trim();
718
+ if (raw === '\x1b')
719
+ return '\x1b';
720
+ if (raw === '')
721
+ return defaultValue;
722
+ const result = options.parse(raw);
723
+ if ('error' in result) {
724
+ console.log(result.error);
725
+ return askTypedInput(options);
726
+ }
727
+ return result.value;
728
+ }
726
729
  /**
727
730
  * Prompts the user for a number within specified bounds.
728
731
  * @param {string} promptText - The prompt text to display.
@@ -837,34 +840,28 @@ function validateMultiplierInput(promptText, raw) {
837
840
  * @returns {Promise<number|string>} The value or '\x1b' if ESC.
838
841
  */
839
842
  async function askNumberOrMultiplier(promptText, defaultValue) {
840
- // Pre-entry legend for Range bounds (mirrors weight mountain legend)
841
- if (/^(minPrice|maxPrice)/i.test(promptText))
842
- printRangeQualityLegend();
843
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${colorPriceRangeValue(defaultValue)}]` : '';
844
- const raw = (await readInput(`${promptText}${suffix}: `, { colorize: (input) => colorRangeValueByQuality(input) })).trim();
845
- if (raw === '\x1b')
846
- return '\x1b';
847
- if (raw === '')
848
- return defaultValue;
849
- if (isMultiplierString(raw)) {
850
- const result = validateMultiplierInput(promptText, raw);
851
- if ('error' in result) {
852
- console.log(result.error);
853
- return askNumberOrMultiplier(promptText, defaultValue);
854
- }
855
- return result.value;
856
- }
857
- const parsed = Number(raw);
858
- if (Number.isNaN(parsed)) {
859
- console.log('Please enter a valid number or multiplier (e.g. 5x).');
860
- return askNumberOrMultiplier(promptText, defaultValue);
861
- }
862
- // Validate that number is > 0 (for price inputs)
863
- if (parsed <= 0) {
864
- console.log(`Invalid ${promptText}: ${parsed}. Must be > 0 (positive number)`);
865
- return askNumberOrMultiplier(promptText, defaultValue);
866
- }
867
- return parsed;
843
+ return askTypedInput({
844
+ promptText,
845
+ defaultValue,
846
+ // Pre-entry legend for Range bounds (mirrors weight mountain legend)
847
+ onBeforePrompt: () => { if (/^(minPrice|maxPrice)/i.test(promptText))
848
+ printRangeQualityLegend(); },
849
+ formatDefault: colorPriceRangeValue,
850
+ colorize: colorRangeValueByQuality,
851
+ parse: (raw) => {
852
+ if (isMultiplierString(raw)) {
853
+ const result = validateMultiplierInput(promptText, raw);
854
+ return 'error' in result ? result : { value: result.value };
855
+ }
856
+ const parsed = Number(raw);
857
+ if (Number.isNaN(parsed))
858
+ return { error: 'Please enter a valid number or multiplier (e.g. 5x).' };
859
+ // Validate that number is > 0 (for price inputs)
860
+ if (parsed <= 0)
861
+ return { error: `Invalid ${promptText}: ${parsed}. Must be > 0 (positive number)` };
862
+ return { value: parsed };
863
+ },
864
+ });
868
865
  }
869
866
  /**
870
867
  * Prompts the user for the maximum price, ensuring it's greater than minimum price.
@@ -874,43 +871,36 @@ async function askNumberOrMultiplier(promptText, defaultValue) {
874
871
  * @returns {Promise<number|string>} The value or '\x1b' if ESC.
875
872
  */
876
873
  async function askMaxPrice(promptText, defaultValue, minPrice) {
877
- printRangeQualityLegend();
878
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${colorPriceRangeValue(defaultValue)}]` : '';
879
- const raw = (await readInput(`${promptText}${suffix}: `, { colorize: (input) => colorRangeValueByQuality(input) })).trim();
880
- if (raw === '\x1b')
881
- return '\x1b';
882
- if (raw === '')
883
- return defaultValue;
884
- if (isMultiplierString(raw)) {
885
- const result = validateMultiplierInput(promptText, raw);
886
- if ('error' in result) {
887
- console.log(result.error);
888
- return askMaxPrice(promptText, defaultValue, minPrice);
889
- }
890
- return result.value;
891
- }
892
- const parsed = Number(raw);
893
- if (Number.isNaN(parsed)) {
894
- console.log('Please enter a valid number or multiplier (e.g. 5x).');
895
- return askMaxPrice(promptText, defaultValue, minPrice);
896
- }
897
- // Validate that number is > 0 (for price inputs)
898
- if (parsed <= 0) {
899
- console.log(`Invalid ${promptText}: ${parsed}. Must be > 0 (positive number)`);
900
- return askMaxPrice(promptText, defaultValue, minPrice);
901
- }
902
- // Validate that maxPrice > minPrice. Only comparable when minPrice is an
903
- // absolute value: a relative min ("2x") needs the grid center to resolve,
904
- // so it can't be checked here — the runtime bound validation covers it
905
- // (previously parseFloat("2x") == 2 wrongly rejected any absolute price <= 2).
906
- if (!isMultiplierString(minPrice)) {
907
- const minPriceValue = typeof minPrice === 'string' ? parseFloat(minPrice) : minPrice;
908
- if (minPriceValue != null && parsed <= minPriceValue) {
909
- console.log(`Invalid ${promptText}: ${parsed}. Must be > minPrice (${minPriceValue})`);
910
- return askMaxPrice(promptText, defaultValue, minPrice);
911
- }
912
- }
913
- return parsed;
874
+ return askTypedInput({
875
+ promptText,
876
+ defaultValue,
877
+ onBeforePrompt: printRangeQualityLegend,
878
+ formatDefault: colorPriceRangeValue,
879
+ colorize: colorRangeValueByQuality,
880
+ parse: (raw) => {
881
+ if (isMultiplierString(raw)) {
882
+ const result = validateMultiplierInput(promptText, raw);
883
+ return 'error' in result ? result : { value: result.value };
884
+ }
885
+ const parsed = Number(raw);
886
+ if (Number.isNaN(parsed))
887
+ return { error: 'Please enter a valid number or multiplier (e.g. 5x).' };
888
+ // Validate that number is > 0 (for price inputs)
889
+ if (parsed <= 0)
890
+ return { error: `Invalid ${promptText}: ${parsed}. Must be > 0 (positive number)` };
891
+ // Validate that maxPrice > minPrice. Only comparable when minPrice is an
892
+ // absolute value: a relative min ("2x") needs the grid center to resolve,
893
+ // so it can't be checked here — the runtime bound validation covers it
894
+ // (previously parseFloat("2x") == 2 wrongly rejected any absolute price <= 2).
895
+ if (!isMultiplierString(minPrice)) {
896
+ const minPriceValue = typeof minPrice === 'string' ? parseFloat(minPrice) : minPrice;
897
+ if (minPriceValue != null && parsed <= minPriceValue) {
898
+ return { error: `Invalid ${promptText}: ${parsed}. Must be > minPrice (${minPriceValue})` };
899
+ }
900
+ }
901
+ return { value: parsed };
902
+ },
903
+ });
914
904
  }
915
905
  /**
916
906
  * Normalizes a percentage string input.
@@ -935,21 +925,21 @@ function normalizePercentageInput(value) {
935
925
  * @returns {Promise<number|string>} The value or '\x1b' if ESC.
936
926
  */
937
927
  async function askNumberOrPercentage(promptText, defaultValue) {
938
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${colorPercentageInput(defaultValue)}]` : '';
939
- const raw = (await readInput(`${promptText}${suffix}: `, { colorize: (input) => colorPercentageInput(input) })).trim();
940
- if (raw === '\x1b')
941
- return '\x1b';
942
- if (raw === '')
943
- return defaultValue;
944
- const percent = normalizePercentageInput(raw);
945
- if (percent !== null)
946
- return percent;
947
- const parsed = Number(raw);
948
- if (Number.isNaN(parsed)) {
949
- console.log('Please enter a valid number or percentage (e.g. 100, 50%).');
950
- return askNumberOrPercentage(promptText, defaultValue);
951
- }
952
- return parsed;
928
+ return askTypedInput({
929
+ promptText,
930
+ defaultValue,
931
+ formatDefault: colorPercentageInput,
932
+ colorize: colorPercentageInput,
933
+ parse: (raw) => {
934
+ const percent = normalizePercentageInput(raw);
935
+ if (percent !== null)
936
+ return { value: percent };
937
+ const parsed = Number(raw);
938
+ if (Number.isNaN(parsed))
939
+ return { error: 'Please enter a valid number or percentage (e.g. 100, 50%).' };
940
+ return { value: parsed };
941
+ },
942
+ });
953
943
  }
954
944
  /**
955
945
  * Parses a raw boolean answer.
@@ -999,31 +989,22 @@ async function askBoolean(promptText, defaultValue) {
999
989
  * @returns {Promise<number|string>} The start price or '\x1b' if ESC.
1000
990
  */
1001
991
  async function askStartPrice(promptText, defaultValue) {
1002
- while (true) {
1003
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${colorStartPriceValue(defaultValue)}]` : '';
1004
- const raw = (await readInput(`${promptText}${suffix}: `, {
1005
- colorize: (input) => colorStartPriceValue(input)
1006
- })).trim();
1007
- if (raw === '\x1b')
1008
- return '\x1b';
1009
- if (!raw) {
1010
- if (defaultValue !== undefined && defaultValue !== null) {
1011
- return defaultValue;
1012
- }
1013
- return undefined;
1014
- }
1015
- const lower = raw.toLowerCase();
1016
- if (lower === 'pool')
1017
- return lower;
1018
- if (lower === 'book')
1019
- return 'book';
1020
- // Accept numeric values (including decimals)
1021
- const num = Number(raw);
1022
- if (!Number.isNaN(num) && Number.isFinite(num)) {
1023
- return num;
1024
- }
1025
- console.log('Please enter "pool", "book", or a numeric value.');
1026
- }
992
+ return askTypedInput({
993
+ promptText,
994
+ defaultValue,
995
+ formatDefault: colorStartPriceValue,
996
+ colorize: colorStartPriceValue,
997
+ parse: (raw) => {
998
+ const lower = raw.toLowerCase();
999
+ if (lower === 'pool' || lower === 'book')
1000
+ return { value: lower };
1001
+ // Accept numeric values (including decimals)
1002
+ const num = Number(raw);
1003
+ if (!Number.isNaN(num) && Number.isFinite(num))
1004
+ return { value: num };
1005
+ return { error: 'Please enter "pool", "book", or a numeric value.' };
1006
+ },
1007
+ });
1027
1008
  }
1028
1009
  /**
1029
1010
  * Spellings that clear a `poolRef` pin, leaving the runtime to auto-select
@@ -151,6 +151,19 @@ declare class AccountOrders {
151
151
  * @private
152
152
  */
153
153
  _loadData(): BotData | null;
154
+ /**
155
+ * Reload `this.data` from disk, falling back to empty state on a miss.
156
+ * Single home for the read-modify-write preamble inside the persistence lock.
157
+ * @private
158
+ */
159
+ _reload(): void;
160
+ /**
161
+ * Reload `this.data` from disk when `forceReload` is set. Shared preamble of
162
+ * every `loadX(forceReload)` accessor.
163
+ * @param {boolean} [forceReload=false]
164
+ * @private
165
+ */
166
+ _ensureLoaded(forceReload?: boolean): void;
154
167
  /**
155
168
  * Reads and parses a JSON file.
156
169
  * @param {string} filePath - The path to the file.
@@ -194,7 +194,7 @@ class AccountOrders {
194
194
  // AsyncLock prevents concurrent read-modify-write races on file I/O
195
195
  this._persistenceLock = new AsyncLock();
196
196
  this._needsBootstrapSave = !storage.exists(this.profilesPath);
197
- this.data = this._loadData() || emptyData();
197
+ this._reload();
198
198
  if (this._needsBootstrapSave) {
199
199
  this._persist();
200
200
  }
@@ -208,6 +208,24 @@ class AccountOrders {
208
208
  // Load the file directly - per-bot files only contain their own bot's data
209
209
  return this._readFile(this.profilesPath);
210
210
  }
211
+ /**
212
+ * Reload `this.data` from disk, falling back to empty state on a miss.
213
+ * Single home for the read-modify-write preamble inside the persistence lock.
214
+ * @private
215
+ */
216
+ _reload() {
217
+ this.data = this._loadData() || emptyData();
218
+ }
219
+ /**
220
+ * Reload `this.data` from disk when `forceReload` is set. Shared preamble of
221
+ * every `loadX(forceReload)` accessor.
222
+ * @param {boolean} [forceReload=false]
223
+ * @private
224
+ */
225
+ _ensureLoaded(forceReload = false) {
226
+ if (forceReload)
227
+ this._reload();
228
+ }
211
229
  /**
212
230
  * Reads and parses a JSON file.
213
231
  * @param {string} filePath - The path to the file.
@@ -252,7 +270,7 @@ class AccountOrders {
252
270
  return;
253
271
  await this._persistenceLock.acquire(async () => {
254
272
  // Reload from disk to ensure we have the latest state
255
- this.data = this._loadData() || emptyData();
273
+ this._reload();
256
274
  const cfg = botConfig;
257
275
  const newMeta = this._buildMeta(botConfig, this.botKey, typeof cfg.botIndex === 'number' ? cfg.botIndex : 0, this.data.meta);
258
276
  const prevMeta = this.data.meta;
@@ -325,7 +343,7 @@ class AccountOrders {
325
343
  // Use AsyncLock to serialize read-modify-write operations
326
344
  await this._persistenceLock.acquire(async () => {
327
345
  // Reload from disk before writing to prevent race conditions
328
- this.data = this._loadData() || emptyData();
346
+ this._reload();
329
347
  const snapshot = Array.isArray(orders) ? orders.map((order) => this._serializeOrder(order)) : [];
330
348
  const debugSnapshot = debugInputs ? cloneForDebug(debugInputs) : null;
331
349
  this.data.grid = snapshot;
@@ -443,7 +461,7 @@ class AccountOrders {
443
461
  */
444
462
  async clearPersistedBoundary() {
445
463
  await this._persistenceLock.acquire(async () => {
446
- this.data = this._loadData() || emptyData();
464
+ this._reload();
447
465
  this.data.boundaryIdx = null;
448
466
  this._persist();
449
467
  });
@@ -461,7 +479,7 @@ class AccountOrders {
461
479
  */
462
480
  async clearPersistedLastFillPivot() {
463
481
  await this._persistenceLock.acquire(async () => {
464
- this.data = this._loadData() || emptyData();
482
+ this._reload();
465
483
  delete this.data.lastFillPivot;
466
484
  this.data.lastUpdated = nowIso();
467
485
  this._persist();
@@ -473,9 +491,7 @@ class AccountOrders {
473
491
  * @returns {Array|null} Order grid array or null if not found
474
492
  */
475
493
  loadGrid(forceReload = false) {
476
- if (forceReload) {
477
- this.data = this._loadData() || emptyData();
478
- }
494
+ this._ensureLoaded(forceReload);
479
495
  return (this.data && Array.isArray(this.data.grid)) ? this.data.grid : null;
480
496
  }
481
497
  /**
@@ -496,9 +512,7 @@ class AccountOrders {
496
512
  * @returns {Object|null} The genesis object, or null when absent/invalid
497
513
  */
498
514
  loadGenesis(forceReload = false) {
499
- if (forceReload) {
500
- this.data = this._loadData() || emptyData();
501
- }
515
+ this._ensureLoaded(forceReload);
502
516
  const genesis = this.data?.genesis;
503
517
  // Same predicate as loadGrid/genesis_policy: one definition of "usable
504
518
  // ladder", so the schema gate cannot diverge from the load-time gate.
@@ -531,18 +545,14 @@ class AccountOrders {
531
545
  * @returns {Object|null} {slotId: count} map or null when absent
532
546
  */
533
547
  loadGapEvacStreaks(forceReload = false) {
534
- if (forceReload) {
535
- this.data = this._loadData() || emptyData();
536
- }
548
+ this._ensureLoaded(forceReload);
537
549
  if (this.data && this.data.gapEvacStreaks && typeof this.data.gapEvacStreaks === 'object') {
538
550
  return this.data.gapEvacStreaks;
539
551
  }
540
552
  return null;
541
553
  }
542
554
  loadLastFillPivot(forceReload = false) {
543
- if (forceReload) {
544
- this.data = this._loadData() || emptyData();
545
- }
555
+ this._ensureLoaded(forceReload);
546
556
  // Shared row gate (normalizeLastFillPivot): identical validation to the
547
557
  // storeMasterGrid sanitizer, one shape contract for the whole ledger.
548
558
  return normalizeLastFillPivot(this.data && this.data.lastFillPivot);
@@ -553,9 +563,7 @@ class AccountOrders {
553
563
  * @returns {Array} Sanitized pending crawl entries (possibly empty)
554
564
  */
555
565
  loadPendingFillCrawls(forceReload = false) {
556
- if (forceReload) {
557
- this.data = this._loadData() || emptyData();
558
- }
566
+ this._ensureLoaded(forceReload);
559
567
  const out = [];
560
568
  const stored = this.data && this.data.pendingFillCrawls;
561
569
  if (Array.isArray(stored)) {
@@ -574,9 +582,7 @@ class AccountOrders {
574
582
  * @returns {Object|null} Recent fill keys map or null if not found
575
583
  */
576
584
  loadRecentFillKeys(forceReload = false) {
577
- if (forceReload) {
578
- this.data = this._loadData() || emptyData();
579
- }
585
+ this._ensureLoaded(forceReload);
580
586
  if (this.data && this.data.recentFillKeys) {
581
587
  return this.data.recentFillKeys;
582
588
  }
@@ -588,9 +594,7 @@ class AccountOrders {
588
594
  * @returns {Object|null} Asset metadata { assetA, assetB } or null if not found
589
595
  */
590
596
  loadPersistedAssets(forceReload = false) {
591
- if (forceReload) {
592
- this.data = this._loadData() || emptyData();
593
- }
597
+ this._ensureLoaded(forceReload);
594
598
  if (this.data && this.data.assets) {
595
599
  return this.data.assets;
596
600
  }
@@ -602,9 +606,7 @@ class AccountOrders {
602
606
  * @returns {number|null} Boundary index or null if not found
603
607
  */
604
608
  loadBoundaryIdx(forceReload = false) {
605
- if (forceReload) {
606
- this.data = this._loadData() || emptyData();
607
- }
609
+ this._ensureLoaded(forceReload);
608
610
  if (this.data) {
609
611
  const idx = this.data.boundaryIdx;
610
612
  if (typeof idx === 'number' && Number.isFinite(idx)) {
@@ -619,9 +621,7 @@ class AccountOrders {
619
621
  * @returns {Object|null} BTS balance { free, total, locked } or null if not found
620
622
  */
621
623
  loadBtsBalance(forceReload = false) {
622
- if (forceReload) {
623
- this.data = this._loadData() || emptyData();
624
- }
624
+ this._ensureLoaded(forceReload);
625
625
  if (this.data && this.data.btsBalance && typeof this.data.btsBalance === 'object') {
626
626
  return this.data.btsBalance;
627
627
  }
@@ -635,9 +635,7 @@ class AccountOrders {
635
635
  * @returns {number} BTS fees owed or 0 if not found
636
636
  */
637
637
  loadBtsFeesOwed(forceReload = false) {
638
- if (forceReload) {
639
- this.data = this._loadData() || emptyData();
640
- }
638
+ this._ensureLoaded(forceReload);
641
639
  if (this.data) {
642
640
  const fees = this.data.btsFeesOwed;
643
641
  if (typeof fees === 'number' && Number.isFinite(fees)) {
@@ -652,7 +650,7 @@ class AccountOrders {
652
650
  */
653
651
  async clearGrid() {
654
652
  return await this._persistenceLock.acquire(async () => {
655
- this.data = this._loadData() || emptyData();
653
+ this._reload();
656
654
  this.data.grid = [];
657
655
  this.data.btsFeesOwed = 0;
658
656
  this.data.boundaryIdx = null;
@@ -680,9 +678,7 @@ class AccountOrders {
680
678
  const minTimestamp = typeof options === 'object' && options !== null && Number.isFinite(options.minTimestamp)
681
679
  ? options.minTimestamp
682
680
  : null;
683
- if (forceReload) {
684
- this.data = this._loadData() || emptyData();
685
- }
681
+ this._ensureLoaded(forceReload);
686
682
  if (this.data) {
687
683
  const fills = this.data.processedFills || {};
688
684
  const entries = Object.entries(fills).filter(([, timestamp]) => minTimestamp == null || (Number.isFinite(timestamp) && timestamp >= minTimestamp));
@@ -698,7 +694,7 @@ class AccountOrders {
698
694
  if (!(fills instanceof Map) || fills.size === 0)
699
695
  return;
700
696
  await this._persistenceLock.acquire(async () => {
701
- this.data = this._loadData() || emptyData();
697
+ this._reload();
702
698
  if (!this.data.processedFills) {
703
699
  this.data.processedFills = {};
704
700
  }
@@ -725,7 +721,7 @@ class AccountOrders {
725
721
  async cleanOldProcessedFills(olderThanMs = 3600000) {
726
722
  // Default: 1 hour (3600000ms)
727
723
  await this._persistenceLock.acquire(async () => {
728
- this.data = this._loadData() || emptyData();
724
+ this._reload();
729
725
  if (!this.data.processedFills) {
730
726
  return;
731
727
  }
@@ -751,9 +747,7 @@ class AccountOrders {
751
747
  * @returns {Object|null} Balance summary or null if no data
752
748
  */
753
749
  getAssetBalances(forceReload = false) {
754
- if (forceReload) {
755
- this.data = this._loadData() || emptyData();
756
- }
750
+ this._ensureLoaded(forceReload);
757
751
  if (!this.data)
758
752
  return null;
759
753
  const meta = this.data.meta || {};
@@ -26,7 +26,7 @@ interface ChainConfig {
26
26
  * again, but a recovery attempt is in flight/recent.
27
27
  * - `unavailable` no live socket to tear down, so no recovery attempt exists.
28
28
  */
29
- export type ForcedReconnectOutcome = 'issued' | 'coalesced' | 'unavailable';
29
+ type ForcedReconnectOutcome = 'issued' | 'coalesced' | 'unavailable';
30
30
  declare function createChainClient(config?: ChainClientConfig): {
31
31
  transport: {
32
32
  connect: (servers?: string[], autoReconnect?: boolean) => Promise<void>;
@@ -265,15 +265,16 @@ function createChainClient(config = {}) {
265
265
  function noteStaleApiError(apiName) {
266
266
  staleApiEscalation.note(apiName);
267
267
  }
268
- async function dbCall(method, args) {
269
- return callWithApiRecovery('database', toRpcMethodName(method), args || [], () => _dbApiId, (id) => { _dbApiId = id; });
270
- }
271
- async function historyCall(method, args) {
272
- return callWithApiRecovery('history', toRpcMethodName(method), args || [], () => _historyApiId, (id) => { _historyApiId = id; });
273
- }
274
- async function broadcastCall(method, args) {
275
- return callWithApiRecovery('network_broadcast', method, args || [], () => _broadcastApiId, (id) => { _broadcastApiId = id; });
268
+ /**
269
+ * Bind a login_api namespace to its cached api-id slot. Centralizes the
270
+ * `callWithApiRecovery` wiring shared by dbCall/historyCall/broadcastCall.
271
+ */
272
+ function apiCaller(apiName, normalizeMethod, getApiId, setApiId) {
273
+ return (method, args) => callWithApiRecovery(apiName, normalizeMethod(method), args || [], getApiId, setApiId);
276
274
  }
275
+ const dbCall = apiCaller('database', toRpcMethodName, () => _dbApiId, (id) => { _dbApiId = id; });
276
+ const historyCall = apiCaller('history', toRpcMethodName, () => _historyApiId, (id) => { _historyApiId = id; });
277
+ const broadcastCall = apiCaller('network_broadcast', (method) => method, () => _broadcastApiId, (id) => { _broadcastApiId = id; });
277
278
  async function broadcastTx(signedTx) {
278
279
  return broadcastCall('broadcast_transaction', [signedTx]);
279
280
  }
@@ -464,12 +465,12 @@ function createReadOnlyClient(config = {}) {
464
465
  function noteStaleApiError() {
465
466
  staleApiEscalation.note();
466
467
  }
467
- async function db(method, args) {
468
- return callWithRecovery(toRpcMethodName(method), args || [], () => _dbApiId, (id) => { _dbApiId = id; });
469
- }
470
- async function history(method, args) {
471
- return callWithRecovery(toRpcMethodName(method), args || [], () => _historyApiId, (id) => { _historyApiId = id; });
468
+ /** Read-channel caller: wraps `callWithRecovery` for a bound api-id slot. */
469
+ function recoveredCaller(getApiId, setApiId) {
470
+ return (method, args) => callWithRecovery(toRpcMethodName(method), args || [], getApiId, setApiId);
472
471
  }
472
+ const db = recoveredCaller(() => _dbApiId, (id) => { _dbApiId = id; });
473
+ const history = recoveredCaller(() => _historyApiId, (id) => { _historyApiId = id; });
473
474
  function setNodes(servers) {
474
475
  transport._setNodes(servers);
475
476
  }
@@ -73,37 +73,34 @@ function createResolvers(chainClient) {
73
73
  throw err;
74
74
  }
75
75
  }
76
- async function resolveAccountId(name) {
77
- if (!name)
78
- throw new Error('account name required');
79
- if (/^1\.2\./.test(String(name)))
80
- return name;
81
- const cacheKey = `id:${name}`;
76
+ /**
77
+ * Resolve an account reference to the requested field, caching through
78
+ * `accountIdCache`. `direction` selects the returned field ('id' or
79
+ * 'name'); a reference already shaped as the target is returned untouched.
80
+ */
81
+ async function resolveAccountField(ref, direction) {
82
+ if (!ref)
83
+ throw new Error(`account ${direction === 'id' ? 'name' : 'id'} required`);
84
+ const isChainId = /^1\.2\./.test(String(ref));
85
+ if (direction === 'id' ? isChainId : !isChainId)
86
+ return ref;
87
+ const cacheKey = `${direction}:${ref}`;
82
88
  const cached = accountIdCache.get(cacheKey);
83
89
  if (cached)
84
90
  return cached;
85
- const account = await resolveAccount(name);
86
- if (account && account.id) {
87
- accountIdCache.set(cacheKey, account.id);
88
- return account.id;
91
+ const account = await resolveAccount(ref);
92
+ const result = direction === 'id' ? account?.id : account?.name;
93
+ if (result) {
94
+ accountIdCache.set(cacheKey, result);
95
+ return result;
89
96
  }
90
- throw new Error(`Could not resolve account ID for: ${name}`);
97
+ throw new Error(`Could not resolve account ${direction === 'id' ? 'ID' : 'name'} for: ${ref}`);
98
+ }
99
+ async function resolveAccountId(name) {
100
+ return resolveAccountField(name, 'id');
91
101
  }
92
102
  async function resolveAccountName(id) {
93
- if (!id)
94
- throw new Error('account id required');
95
- if (!/^1\.2\./.test(String(id)))
96
- return id;
97
- const cacheKey = `name:${id}`;
98
- const cached = accountIdCache.get(cacheKey);
99
- if (cached)
100
- return cached;
101
- const account = await resolveAccount(id);
102
- if (account && account.name) {
103
- accountIdCache.set(cacheKey, account.name);
104
- return account.name;
105
- }
106
- throw new Error(`Could not resolve account name for: ${id}`);
103
+ return resolveAccountField(id, 'name');
107
104
  }
108
105
  function invalidateAsset(assetId) {
109
106
  const cached = assetCache.get(`asset:${assetId}`);