dexbot 1.1.10

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 (807) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +287 -0
  3. package/claw/README.md +513 -0
  4. package/claw/scripts/memu_runner.py +385 -0
  5. package/claw/skills/bitshares-guide/SKILL.md +14 -0
  6. package/claw/skills/bitshares-guide/references/example-skill-shells.md +18 -0
  7. package/claw/skills/bitshares-guide/references/presentation-patterns.md +19 -0
  8. package/claw/skills/bitshares-guide/references/scope-guardrails.md +9 -0
  9. package/claw/skills/launcher-ops/SKILL.md +18 -0
  10. package/claw/skills/launcher-ops/references/launcher-workflow.md +23 -0
  11. package/claw/skills/margin-trading/SKILL.md +23 -0
  12. package/claw/skills/margin-trading/references/honest-asset-list.md +74 -0
  13. package/claw/skills/margin-trading/references/honest-assets.md +44 -0
  14. package/claw/skills/margin-trading/references/position-management.md +203 -0
  15. package/claw/skills/margin-trading/references/trading-concepts.md +80 -0
  16. package/claw/skills/memu-memory/SKILL.md +218 -0
  17. package/claw/skills/shared/references/js-automation-overview.md +24 -0
  18. package/claw/skills/shared/references/safety-and-staleness.md +11 -0
  19. package/claw/skills/shared/references/skill-boundaries.md +17 -0
  20. package/claw/skills/trend-detection/SKILL.md +33 -0
  21. package/claw/skills/trend-detection/agents/openai.yaml +3 -0
  22. package/claw/skills/trend-detection/references/service.md +45 -0
  23. package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts +3 -0
  24. package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts.map +1 -0
  25. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +149 -0
  26. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js.map +1 -0
  27. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts +3 -0
  28. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts.map +1 -0
  29. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +387 -0
  30. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +1 -0
  31. package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts +3 -0
  32. package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts.map +1 -0
  33. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +200 -0
  34. package/dist/analysis/ama_fitting/calibrate_convergence_er.js.map +1 -0
  35. package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts +3 -0
  36. package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts.map +1 -0
  37. package/dist/analysis/ama_fitting/fetch_lp_candles.js +212 -0
  38. package/dist/analysis/ama_fitting/fetch_lp_candles.js.map +1 -0
  39. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +31 -0
  40. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts.map +1 -0
  41. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +249 -0
  42. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js.map +1 -0
  43. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +2 -0
  44. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts.map +1 -0
  45. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +782 -0
  46. package/dist/analysis/ama_fitting/optimizer_high_resolution.js.map +1 -0
  47. package/dist/analysis/analyze_derivatives.d.ts +95 -0
  48. package/dist/analysis/analyze_derivatives.d.ts.map +1 -0
  49. package/dist/analysis/analyze_derivatives.js +295 -0
  50. package/dist/analysis/analyze_derivatives.js.map +1 -0
  51. package/dist/analysis/analyze_dynamic_weight.d.ts +14 -0
  52. package/dist/analysis/analyze_dynamic_weight.d.ts.map +1 -0
  53. package/dist/analysis/analyze_dynamic_weight.js +208 -0
  54. package/dist/analysis/analyze_dynamic_weight.js.map +1 -0
  55. package/dist/analysis/analyze_kalman.d.ts +13 -0
  56. package/dist/analysis/analyze_kalman.d.ts.map +1 -0
  57. package/dist/analysis/analyze_kalman.js +123 -0
  58. package/dist/analysis/analyze_kalman.js.map +1 -0
  59. package/dist/analysis/analyze_regime.d.ts +20 -0
  60. package/dist/analysis/analyze_regime.d.ts.map +1 -0
  61. package/dist/analysis/analyze_regime.js +139 -0
  62. package/dist/analysis/analyze_regime.js.map +1 -0
  63. package/dist/analysis/analyze_regime_windows.d.ts +19 -0
  64. package/dist/analysis/analyze_regime_windows.d.ts.map +1 -0
  65. package/dist/analysis/analyze_regime_windows.js +413 -0
  66. package/dist/analysis/analyze_regime_windows.js.map +1 -0
  67. package/dist/analysis/analyze_risk_profile.d.ts +3 -0
  68. package/dist/analysis/analyze_risk_profile.d.ts.map +1 -0
  69. package/dist/analysis/analyze_risk_profile.js +159 -0
  70. package/dist/analysis/analyze_risk_profile.js.map +1 -0
  71. package/dist/analysis/analyze_trade_heatmap.d.ts +3 -0
  72. package/dist/analysis/analyze_trade_heatmap.d.ts.map +1 -0
  73. package/dist/analysis/analyze_trade_heatmap.js +367 -0
  74. package/dist/analysis/analyze_trade_heatmap.js.map +1 -0
  75. package/dist/analysis/analyze_volatility.d.ts +22 -0
  76. package/dist/analysis/analyze_volatility.d.ts.map +1 -0
  77. package/dist/analysis/analyze_volatility.js +172 -0
  78. package/dist/analysis/analyze_volatility.js.map +1 -0
  79. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +99 -0
  80. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts.map +1 -0
  81. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +804 -0
  82. package/dist/analysis/bot_fitting/backtest_ama_sweep.js.map +1 -0
  83. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +2 -0
  84. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts.map +1 -0
  85. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +347 -0
  86. package/dist/analysis/bot_fitting/backtest_bot_fitting.js.map +1 -0
  87. package/dist/analysis/bot_fitting/shared_utils.d.ts +15 -0
  88. package/dist/analysis/bot_fitting/shared_utils.d.ts.map +1 -0
  89. package/dist/analysis/bot_fitting/shared_utils.js +48 -0
  90. package/dist/analysis/bot_fitting/shared_utils.js.map +1 -0
  91. package/dist/analysis/bot_key_utils.d.ts +16 -0
  92. package/dist/analysis/bot_key_utils.d.ts.map +1 -0
  93. package/dist/analysis/bot_key_utils.js +61 -0
  94. package/dist/analysis/bot_key_utils.js.map +1 -0
  95. package/dist/analysis/bot_usage/discover_bot_accounts.d.ts +3 -0
  96. package/dist/analysis/bot_usage/discover_bot_accounts.d.ts.map +1 -0
  97. package/dist/analysis/bot_usage/discover_bot_accounts.js +498 -0
  98. package/dist/analysis/bot_usage/discover_bot_accounts.js.map +1 -0
  99. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +546 -0
  100. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +1 -0
  101. package/dist/analysis/bot_usage/kibana_bot_queries.js +427 -0
  102. package/dist/analysis/bot_usage/kibana_bot_queries.js.map +1 -0
  103. package/dist/analysis/chart_utils.d.ts +13 -0
  104. package/dist/analysis/chart_utils.d.ts.map +1 -0
  105. package/dist/analysis/chart_utils.js +142 -0
  106. package/dist/analysis/chart_utils.js.map +1 -0
  107. package/dist/analysis/derivative_chart_generator.d.ts +18 -0
  108. package/dist/analysis/derivative_chart_generator.d.ts.map +1 -0
  109. package/dist/analysis/derivative_chart_generator.js +896 -0
  110. package/dist/analysis/derivative_chart_generator.js.map +1 -0
  111. package/dist/analysis/math_utils.d.ts +35 -0
  112. package/dist/analysis/math_utils.d.ts.map +1 -0
  113. package/dist/analysis/math_utils.js +121 -0
  114. package/dist/analysis/math_utils.js.map +1 -0
  115. package/dist/analysis/price_sources.d.ts +34 -0
  116. package/dist/analysis/price_sources.d.ts.map +1 -0
  117. package/dist/analysis/price_sources.js +103 -0
  118. package/dist/analysis/price_sources.js.map +1 -0
  119. package/dist/analysis/trade_profitability.d.ts +115 -0
  120. package/dist/analysis/trade_profitability.d.ts.map +1 -0
  121. package/dist/analysis/trade_profitability.js +1247 -0
  122. package/dist/analysis/trade_profitability.js.map +1 -0
  123. package/dist/analysis/tradingview/analyze_tradingview.d.ts +38 -0
  124. package/dist/analysis/tradingview/analyze_tradingview.d.ts.map +1 -0
  125. package/dist/analysis/tradingview/analyze_tradingview.js +212 -0
  126. package/dist/analysis/tradingview/analyze_tradingview.js.map +1 -0
  127. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +9 -0
  128. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts.map +1 -0
  129. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +1717 -0
  130. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js.map +1 -0
  131. package/dist/analysis/trend_detection/derivative_analyzer.d.ts +250 -0
  132. package/dist/analysis/trend_detection/derivative_analyzer.d.ts.map +1 -0
  133. package/dist/analysis/trend_detection/derivative_analyzer.js +903 -0
  134. package/dist/analysis/trend_detection/derivative_analyzer.js.map +1 -0
  135. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +6 -0
  136. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +1 -0
  137. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +1449 -0
  138. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +1 -0
  139. package/dist/analysis/trend_detection/hurst_analyzer.d.ts +42 -0
  140. package/dist/analysis/trend_detection/hurst_analyzer.d.ts.map +1 -0
  141. package/dist/analysis/trend_detection/hurst_analyzer.js +159 -0
  142. package/dist/analysis/trend_detection/hurst_analyzer.js.map +1 -0
  143. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +6 -0
  144. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts.map +1 -0
  145. package/dist/analysis/trend_detection/kalman_chart_generator.js +408 -0
  146. package/dist/analysis/trend_detection/kalman_chart_generator.js.map +1 -0
  147. package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts +103 -0
  148. package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts.map +1 -0
  149. package/dist/analysis/trend_detection/kalman_trend_analyzer.js +229 -0
  150. package/dist/analysis/trend_detection/kalman_trend_analyzer.js.map +1 -0
  151. package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts +34 -0
  152. package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts.map +1 -0
  153. package/dist/analysis/trend_detection/kalman_velocity_smoothing.js +89 -0
  154. package/dist/analysis/trend_detection/kalman_velocity_smoothing.js.map +1 -0
  155. package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts +39 -0
  156. package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts.map +1 -0
  157. package/dist/analysis/trend_detection/permutation_entropy_analyzer.js +132 -0
  158. package/dist/analysis/trend_detection/permutation_entropy_analyzer.js.map +1 -0
  159. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +6 -0
  160. package/dist/analysis/trend_detection/regime_chart_generator.d.ts.map +1 -0
  161. package/dist/analysis/trend_detection/regime_chart_generator.js +345 -0
  162. package/dist/analysis/trend_detection/regime_chart_generator.js.map +1 -0
  163. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts +2 -0
  164. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts.map +1 -0
  165. package/dist/analysis/trend_detection/tests/test_kalman_trend.js +130 -0
  166. package/dist/analysis/trend_detection/tests/test_kalman_trend.js.map +1 -0
  167. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts +2 -0
  168. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts.map +1 -0
  169. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js +38 -0
  170. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js.map +1 -0
  171. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +6 -0
  172. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts.map +1 -0
  173. package/dist/analysis/trend_detection/volatility_chart_generator.js +732 -0
  174. package/dist/analysis/trend_detection/volatility_chart_generator.js.map +1 -0
  175. package/dist/bot.d.ts +49 -0
  176. package/dist/bot.d.ts.map +1 -0
  177. package/dist/bot.js +221 -0
  178. package/dist/bot.js.map +1 -0
  179. package/dist/credential-daemon.d.ts +64 -0
  180. package/dist/credential-daemon.d.ts.map +1 -0
  181. package/dist/credential-daemon.js +987 -0
  182. package/dist/credential-daemon.js.map +1 -0
  183. package/dist/dexbot.d.ts +87 -0
  184. package/dist/dexbot.d.ts.map +1 -0
  185. package/dist/dexbot.js +1222 -0
  186. package/dist/dexbot.js.map +1 -0
  187. package/dist/market_adapter/ama_signal_runner.d.ts +3 -0
  188. package/dist/market_adapter/ama_signal_runner.d.ts.map +1 -0
  189. package/dist/market_adapter/ama_signal_runner.js +175 -0
  190. package/dist/market_adapter/ama_signal_runner.js.map +1 -0
  191. package/dist/market_adapter/candle_utils.d.ts +57 -0
  192. package/dist/market_adapter/candle_utils.d.ts.map +1 -0
  193. package/dist/market_adapter/candle_utils.js +252 -0
  194. package/dist/market_adapter/candle_utils.js.map +1 -0
  195. package/dist/market_adapter/core/asymmetric_bounds.d.ts +20 -0
  196. package/dist/market_adapter/core/asymmetric_bounds.d.ts.map +1 -0
  197. package/dist/market_adapter/core/asymmetric_bounds.js +88 -0
  198. package/dist/market_adapter/core/asymmetric_bounds.js.map +1 -0
  199. package/dist/market_adapter/core/config_normalizers.d.ts +10 -0
  200. package/dist/market_adapter/core/config_normalizers.d.ts.map +1 -0
  201. package/dist/market_adapter/core/config_normalizers.js +24 -0
  202. package/dist/market_adapter/core/config_normalizers.js.map +1 -0
  203. package/dist/market_adapter/core/kibana_candles.d.ts +74 -0
  204. package/dist/market_adapter/core/kibana_candles.d.ts.map +1 -0
  205. package/dist/market_adapter/core/kibana_candles.js +249 -0
  206. package/dist/market_adapter/core/kibana_candles.js.map +1 -0
  207. package/dist/market_adapter/core/kibana_client.d.ts +27 -0
  208. package/dist/market_adapter/core/kibana_client.d.ts.map +1 -0
  209. package/dist/market_adapter/core/kibana_client.js +120 -0
  210. package/dist/market_adapter/core/kibana_client.js.map +1 -0
  211. package/dist/market_adapter/core/kibana_market_candles.d.ts +143 -0
  212. package/dist/market_adapter/core/kibana_market_candles.d.ts.map +1 -0
  213. package/dist/market_adapter/core/kibana_market_candles.js +170 -0
  214. package/dist/market_adapter/core/kibana_market_candles.js.map +1 -0
  215. package/dist/market_adapter/core/market_adapter_service.d.ts +210 -0
  216. package/dist/market_adapter/core/market_adapter_service.d.ts.map +1 -0
  217. package/dist/market_adapter/core/market_adapter_service.js +2328 -0
  218. package/dist/market_adapter/core/market_adapter_service.js.map +1 -0
  219. package/dist/market_adapter/core/strategies/ama.d.ts +2 -0
  220. package/dist/market_adapter/core/strategies/ama.d.ts.map +1 -0
  221. package/dist/market_adapter/core/strategies/ama.js +138 -0
  222. package/dist/market_adapter/core/strategies/ama.js.map +1 -0
  223. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +50 -0
  224. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts.map +1 -0
  225. package/dist/market_adapter/core/strategies/ama_slope_model.js +143 -0
  226. package/dist/market_adapter/core/strategies/ama_slope_model.js.map +1 -0
  227. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +12 -0
  228. package/dist/market_adapter/core/strategies/atr/calculator.d.ts.map +1 -0
  229. package/dist/market_adapter/core/strategies/atr/calculator.js +47 -0
  230. package/dist/market_adapter/core/strategies/atr/calculator.js.map +1 -0
  231. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +32 -0
  232. package/dist/market_adapter/core/strategies/collateral_manager.d.ts.map +1 -0
  233. package/dist/market_adapter/core/strategies/collateral_manager.js +68 -0
  234. package/dist/market_adapter/core/strategies/collateral_manager.js.map +1 -0
  235. package/dist/market_adapter/core/strategies/regime_gate.d.ts +66 -0
  236. package/dist/market_adapter/core/strategies/regime_gate.d.ts.map +1 -0
  237. package/dist/market_adapter/core/strategies/regime_gate.js +189 -0
  238. package/dist/market_adapter/core/strategies/regime_gate.js.map +1 -0
  239. package/dist/market_adapter/index.d.ts +10 -0
  240. package/dist/market_adapter/index.d.ts.map +1 -0
  241. package/dist/market_adapter/index.js +71 -0
  242. package/dist/market_adapter/index.js.map +1 -0
  243. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.d.ts +3 -0
  244. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.d.ts.map +1 -0
  245. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +1165 -0
  246. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js.map +1 -0
  247. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +54 -0
  248. package/dist/market_adapter/inputs/fetch_lp_data.d.ts.map +1 -0
  249. package/dist/market_adapter/inputs/fetch_lp_data.js +743 -0
  250. package/dist/market_adapter/inputs/fetch_lp_data.js.map +1 -0
  251. package/dist/market_adapter/inputs/kibana_source.d.ts +68 -0
  252. package/dist/market_adapter/inputs/kibana_source.d.ts.map +1 -0
  253. package/dist/market_adapter/inputs/kibana_source.js +143 -0
  254. package/dist/market_adapter/inputs/kibana_source.js.map +1 -0
  255. package/dist/market_adapter/interval_utils.d.ts +6 -0
  256. package/dist/market_adapter/interval_utils.d.ts.map +1 -0
  257. package/dist/market_adapter/interval_utils.js +14 -0
  258. package/dist/market_adapter/interval_utils.js.map +1 -0
  259. package/dist/market_adapter/log_format.d.ts +16 -0
  260. package/dist/market_adapter/log_format.d.ts.map +1 -0
  261. package/dist/market_adapter/log_format.js +72 -0
  262. package/dist/market_adapter/log_format.js.map +1 -0
  263. package/dist/market_adapter/lp_chart_core.d.ts +6 -0
  264. package/dist/market_adapter/lp_chart_core.d.ts.map +1 -0
  265. package/dist/market_adapter/lp_chart_core.js +874 -0
  266. package/dist/market_adapter/lp_chart_core.js.map +1 -0
  267. package/dist/market_adapter/lp_chart_runner.d.ts +135 -0
  268. package/dist/market_adapter/lp_chart_runner.d.ts.map +1 -0
  269. package/dist/market_adapter/lp_chart_runner.js +337 -0
  270. package/dist/market_adapter/lp_chart_runner.js.map +1 -0
  271. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +23 -0
  272. package/dist/market_adapter/lp_chart_strategy_loader.d.ts.map +1 -0
  273. package/dist/market_adapter/lp_chart_strategy_loader.js +169 -0
  274. package/dist/market_adapter/lp_chart_strategy_loader.js.map +1 -0
  275. package/dist/market_adapter/market_adapter.d.ts +133 -0
  276. package/dist/market_adapter/market_adapter.d.ts.map +1 -0
  277. package/dist/market_adapter/market_adapter.js +1331 -0
  278. package/dist/market_adapter/market_adapter.js.map +1 -0
  279. package/dist/market_adapter/merge_lp_data.d.ts +3 -0
  280. package/dist/market_adapter/merge_lp_data.d.ts.map +1 -0
  281. package/dist/market_adapter/merge_lp_data.js +125 -0
  282. package/dist/market_adapter/merge_lp_data.js.map +1 -0
  283. package/dist/market_adapter/test_helpers.d.ts +14 -0
  284. package/dist/market_adapter/test_helpers.d.ts.map +1 -0
  285. package/dist/market_adapter/test_helpers.js +22 -0
  286. package/dist/market_adapter/test_helpers.js.map +1 -0
  287. package/dist/market_adapter/utils/adapter_client.d.ts +20 -0
  288. package/dist/market_adapter/utils/adapter_client.d.ts.map +1 -0
  289. package/dist/market_adapter/utils/adapter_client.js +88 -0
  290. package/dist/market_adapter/utils/adapter_client.js.map +1 -0
  291. package/dist/market_adapter/utils/atomic_write.d.ts +9 -0
  292. package/dist/market_adapter/utils/atomic_write.d.ts.map +1 -0
  293. package/dist/market_adapter/utils/atomic_write.js +13 -0
  294. package/dist/market_adapter/utils/atomic_write.js.map +1 -0
  295. package/dist/market_adapter/utils/chain.d.ts +50 -0
  296. package/dist/market_adapter/utils/chain.d.ts.map +1 -0
  297. package/dist/market_adapter/utils/chain.js +196 -0
  298. package/dist/market_adapter/utils/chain.js.map +1 -0
  299. package/dist/market_adapter/utils/data_discovery.d.ts +6 -0
  300. package/dist/market_adapter/utils/data_discovery.d.ts.map +1 -0
  301. package/dist/market_adapter/utils/data_discovery.js +35 -0
  302. package/dist/market_adapter/utils/data_discovery.js.map +1 -0
  303. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +15 -0
  304. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts.map +1 -0
  305. package/dist/market_adapter/utils/dynamic_grid_snapshot.js +60 -0
  306. package/dist/market_adapter/utils/dynamic_grid_snapshot.js.map +1 -0
  307. package/dist/market_adapter/utils/file_lock.d.ts +19 -0
  308. package/dist/market_adapter/utils/file_lock.d.ts.map +1 -0
  309. package/dist/market_adapter/utils/file_lock.js +191 -0
  310. package/dist/market_adapter/utils/file_lock.js.map +1 -0
  311. package/dist/market_adapter/utils/native_history.d.ts +19 -0
  312. package/dist/market_adapter/utils/native_history.d.ts.map +1 -0
  313. package/dist/market_adapter/utils/native_history.js +172 -0
  314. package/dist/market_adapter/utils/native_history.js.map +1 -0
  315. package/dist/market_adapter/utils/paths.d.ts +5 -0
  316. package/dist/market_adapter/utils/paths.d.ts.map +1 -0
  317. package/dist/market_adapter/utils/paths.js +7 -0
  318. package/dist/market_adapter/utils/paths.js.map +1 -0
  319. package/dist/modules/account_bots.d.ts +112 -0
  320. package/dist/modules/account_bots.d.ts.map +1 -0
  321. package/dist/modules/account_bots.js +1259 -0
  322. package/dist/modules/account_bots.js.map +1 -0
  323. package/dist/modules/account_orders.d.ts +273 -0
  324. package/dist/modules/account_orders.d.ts.map +1 -0
  325. package/dist/modules/account_orders.js +662 -0
  326. package/dist/modules/account_orders.js.map +1 -0
  327. package/dist/modules/authority_resolver.d.ts +2 -0
  328. package/dist/modules/authority_resolver.d.ts.map +1 -0
  329. package/dist/modules/authority_resolver.js +231 -0
  330. package/dist/modules/authority_resolver.js.map +1 -0
  331. package/dist/modules/bitshares-native/chain_client.d.ts +38 -0
  332. package/dist/modules/bitshares-native/chain_client.d.ts.map +1 -0
  333. package/dist/modules/bitshares-native/chain_client.js +322 -0
  334. package/dist/modules/bitshares-native/chain_client.js.map +1 -0
  335. package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts +59 -0
  336. package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts.map +1 -0
  337. package/dist/modules/bitshares-native/crypto/ecc.browser.js +456 -0
  338. package/dist/modules/bitshares-native/crypto/ecc.browser.js.map +1 -0
  339. package/dist/modules/bitshares-native/crypto/ecc.d.ts +66 -0
  340. package/dist/modules/bitshares-native/crypto/ecc.d.ts.map +1 -0
  341. package/dist/modules/bitshares-native/crypto/ecc.js +557 -0
  342. package/dist/modules/bitshares-native/crypto/ecc.js.map +1 -0
  343. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -0
  344. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts.map +1 -0
  345. package/dist/modules/bitshares-native/crypto/ecc_selector.js +20 -0
  346. package/dist/modules/bitshares-native/crypto/ecc_selector.js.map +1 -0
  347. package/dist/modules/bitshares-native/index.d.ts +3 -0
  348. package/dist/modules/bitshares-native/index.d.ts.map +1 -0
  349. package/dist/modules/bitshares-native/index.js +32 -0
  350. package/dist/modules/bitshares-native/index.js.map +1 -0
  351. package/dist/modules/bitshares-native/resolvers.d.ts +40 -0
  352. package/dist/modules/bitshares-native/resolvers.d.ts.map +1 -0
  353. package/dist/modules/bitshares-native/resolvers.js +161 -0
  354. package/dist/modules/bitshares-native/resolvers.js.map +1 -0
  355. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +56 -0
  356. package/dist/modules/bitshares-native/serial/chain_constants.d.ts.map +1 -0
  357. package/dist/modules/bitshares-native/serial/chain_constants.js +92 -0
  358. package/dist/modules/bitshares-native/serial/chain_constants.js.map +1 -0
  359. package/dist/modules/bitshares-native/serial/index.d.ts +10 -0
  360. package/dist/modules/bitshares-native/serial/index.d.ts.map +1 -0
  361. package/dist/modules/bitshares-native/serial/index.js +14 -0
  362. package/dist/modules/bitshares-native/serial/index.js.map +1 -0
  363. package/dist/modules/bitshares-native/serial/operations.d.ts +102 -0
  364. package/dist/modules/bitshares-native/serial/operations.d.ts.map +1 -0
  365. package/dist/modules/bitshares-native/serial/operations.js +615 -0
  366. package/dist/modules/bitshares-native/serial/operations.js.map +1 -0
  367. package/dist/modules/bitshares-native/serial/serializer.d.ts +64 -0
  368. package/dist/modules/bitshares-native/serial/serializer.d.ts.map +1 -0
  369. package/dist/modules/bitshares-native/serial/serializer.js +252 -0
  370. package/dist/modules/bitshares-native/serial/serializer.js.map +1 -0
  371. package/dist/modules/bitshares-native/serial/types.d.ts +120 -0
  372. package/dist/modules/bitshares-native/serial/types.d.ts.map +1 -0
  373. package/dist/modules/bitshares-native/serial/types.js +837 -0
  374. package/dist/modules/bitshares-native/serial/types.js.map +1 -0
  375. package/dist/modules/bitshares-native/signing_client.d.ts +6 -0
  376. package/dist/modules/bitshares-native/signing_client.d.ts.map +1 -0
  377. package/dist/modules/bitshares-native/signing_client.js +141 -0
  378. package/dist/modules/bitshares-native/signing_client.js.map +1 -0
  379. package/dist/modules/bitshares-native/subscriptions.d.ts +6 -0
  380. package/dist/modules/bitshares-native/subscriptions.d.ts.map +1 -0
  381. package/dist/modules/bitshares-native/subscriptions.js +865 -0
  382. package/dist/modules/bitshares-native/subscriptions.js.map +1 -0
  383. package/dist/modules/bitshares-native/transport.d.ts +51 -0
  384. package/dist/modules/bitshares-native/transport.d.ts.map +1 -0
  385. package/dist/modules/bitshares-native/transport.js +447 -0
  386. package/dist/modules/bitshares-native/transport.js.map +1 -0
  387. package/dist/modules/bitshares-native/tx/builder.d.ts +30 -0
  388. package/dist/modules/bitshares-native/tx/builder.d.ts.map +1 -0
  389. package/dist/modules/bitshares-native/tx/builder.js +262 -0
  390. package/dist/modules/bitshares-native/tx/builder.js.map +1 -0
  391. package/dist/modules/bitshares_client.d.ts +129 -0
  392. package/dist/modules/bitshares_client.d.ts.map +1 -0
  393. package/dist/modules/bitshares_client.js +627 -0
  394. package/dist/modules/bitshares_client.js.map +1 -0
  395. package/dist/modules/bot_settings.d.ts +33 -0
  396. package/dist/modules/bot_settings.d.ts.map +1 -0
  397. package/dist/modules/bot_settings.js +328 -0
  398. package/dist/modules/bot_settings.js.map +1 -0
  399. package/dist/modules/bots_file_lock.d.ts +88 -0
  400. package/dist/modules/bots_file_lock.d.ts.map +1 -0
  401. package/dist/modules/bots_file_lock.js +161 -0
  402. package/dist/modules/bots_file_lock.js.map +1 -0
  403. package/dist/modules/chain_keys.d.ts +302 -0
  404. package/dist/modules/chain_keys.d.ts.map +1 -0
  405. package/dist/modules/chain_keys.js +1095 -0
  406. package/dist/modules/chain_keys.js.map +1 -0
  407. package/dist/modules/chain_orders.d.ts +423 -0
  408. package/dist/modules/chain_orders.d.ts.map +1 -0
  409. package/dist/modules/chain_orders.js +1201 -0
  410. package/dist/modules/chain_orders.js.map +1 -0
  411. package/dist/modules/cli_whitelist_args.d.ts +6 -0
  412. package/dist/modules/cli_whitelist_args.d.ts.map +1 -0
  413. package/dist/modules/cli_whitelist_args.js +13 -0
  414. package/dist/modules/cli_whitelist_args.js.map +1 -0
  415. package/dist/modules/config.d.ts +57 -0
  416. package/dist/modules/config.d.ts.map +1 -0
  417. package/dist/modules/config.js +107 -0
  418. package/dist/modules/config.js.map +1 -0
  419. package/dist/modules/constants.d.ts +635 -0
  420. package/dist/modules/constants.d.ts.map +1 -0
  421. package/dist/modules/constants.js +1464 -0
  422. package/dist/modules/constants.js.map +1 -0
  423. package/dist/modules/cr_planner.d.ts +51 -0
  424. package/dist/modules/cr_planner.d.ts.map +1 -0
  425. package/dist/modules/cr_planner.js +299 -0
  426. package/dist/modules/cr_planner.js.map +1 -0
  427. package/dist/modules/credential_policy.d.ts +188 -0
  428. package/dist/modules/credential_policy.d.ts.map +1 -0
  429. package/dist/modules/credential_policy.js +1452 -0
  430. package/dist/modules/credential_policy.js.map +1 -0
  431. package/dist/modules/credential_runtime.d.ts +42 -0
  432. package/dist/modules/credential_runtime.d.ts.map +1 -0
  433. package/dist/modules/credential_runtime.js +148 -0
  434. package/dist/modules/credential_runtime.js.map +1 -0
  435. package/dist/modules/credential_session_cache.d.ts +36 -0
  436. package/dist/modules/credential_session_cache.d.ts.map +1 -0
  437. package/dist/modules/credential_session_cache.js +106 -0
  438. package/dist/modules/credential_session_cache.js.map +1 -0
  439. package/dist/modules/credit_runtime.d.ts +412 -0
  440. package/dist/modules/credit_runtime.d.ts.map +1 -0
  441. package/dist/modules/credit_runtime.js +2866 -0
  442. package/dist/modules/credit_runtime.js.map +1 -0
  443. package/dist/modules/crypto/browser_provider.d.ts +15 -0
  444. package/dist/modules/crypto/browser_provider.d.ts.map +1 -0
  445. package/dist/modules/crypto/browser_provider.js +113 -0
  446. package/dist/modules/crypto/browser_provider.js.map +1 -0
  447. package/dist/modules/crypto/index.d.ts +9 -0
  448. package/dist/modules/crypto/index.d.ts.map +1 -0
  449. package/dist/modules/crypto/index.js +44 -0
  450. package/dist/modules/crypto/index.js.map +1 -0
  451. package/dist/modules/crypto/node_provider.d.ts +15 -0
  452. package/dist/modules/crypto/node_provider.d.ts.map +1 -0
  453. package/dist/modules/crypto/node_provider.js +74 -0
  454. package/dist/modules/crypto/node_provider.js.map +1 -0
  455. package/dist/modules/crypto/provider.d.ts +34 -0
  456. package/dist/modules/crypto/provider.d.ts.map +1 -0
  457. package/dist/modules/crypto/provider.js +3 -0
  458. package/dist/modules/crypto/provider.js.map +1 -0
  459. package/dist/modules/crypto/pure_ripemd160.d.ts +8 -0
  460. package/dist/modules/crypto/pure_ripemd160.d.ts.map +1 -0
  461. package/dist/modules/crypto/pure_ripemd160.js +142 -0
  462. package/dist/modules/crypto/pure_ripemd160.js.map +1 -0
  463. package/dist/modules/crypto/pure_scrypt.d.ts +23 -0
  464. package/dist/modules/crypto/pure_scrypt.d.ts.map +1 -0
  465. package/dist/modules/crypto/pure_scrypt.js +161 -0
  466. package/dist/modules/crypto/pure_scrypt.js.map +1 -0
  467. package/dist/modules/crypto/pure_secp256k1.d.ts +29 -0
  468. package/dist/modules/crypto/pure_secp256k1.d.ts.map +1 -0
  469. package/dist/modules/crypto/pure_secp256k1.js +195 -0
  470. package/dist/modules/crypto/pure_secp256k1.js.map +1 -0
  471. package/dist/modules/crypto/sync.d.ts +13 -0
  472. package/dist/modules/crypto/sync.d.ts.map +1 -0
  473. package/dist/modules/crypto/sync.js +37 -0
  474. package/dist/modules/crypto/sync.js.map +1 -0
  475. package/dist/modules/dexbot_class.d.ts +1074 -0
  476. package/dist/modules/dexbot_class.d.ts.map +1 -0
  477. package/dist/modules/dexbot_class.js +4613 -0
  478. package/dist/modules/dexbot_class.js.map +1 -0
  479. package/dist/modules/dexbot_credential_client.d.ts +71 -0
  480. package/dist/modules/dexbot_credential_client.d.ts.map +1 -0
  481. package/dist/modules/dexbot_credential_client.js +224 -0
  482. package/dist/modules/dexbot_credential_client.js.map +1 -0
  483. package/dist/modules/dexbot_fill_runtime.d.ts +173 -0
  484. package/dist/modules/dexbot_fill_runtime.d.ts.map +1 -0
  485. package/dist/modules/dexbot_fill_runtime.js +217 -0
  486. package/dist/modules/dexbot_fill_runtime.js.map +1 -0
  487. package/dist/modules/dexbot_maintenance_runtime.d.ts +279 -0
  488. package/dist/modules/dexbot_maintenance_runtime.d.ts.map +1 -0
  489. package/dist/modules/dexbot_maintenance_runtime.js +1613 -0
  490. package/dist/modules/dexbot_maintenance_runtime.js.map +1 -0
  491. package/dist/modules/env.d.ts +12 -0
  492. package/dist/modules/env.d.ts.map +1 -0
  493. package/dist/modules/env.js +57 -0
  494. package/dist/modules/env.js.map +1 -0
  495. package/dist/modules/fund_registry.d.ts +96 -0
  496. package/dist/modules/fund_registry.d.ts.map +1 -0
  497. package/dist/modules/fund_registry.js +261 -0
  498. package/dist/modules/fund_registry.js.map +1 -0
  499. package/dist/modules/general_settings.d.ts +36 -0
  500. package/dist/modules/general_settings.d.ts.map +1 -0
  501. package/dist/modules/general_settings.js +63 -0
  502. package/dist/modules/general_settings.js.map +1 -0
  503. package/dist/modules/graceful_shutdown.d.ts +86 -0
  504. package/dist/modules/graceful_shutdown.d.ts.map +1 -0
  505. package/dist/modules/graceful_shutdown.js +164 -0
  506. package/dist/modules/graceful_shutdown.js.map +1 -0
  507. package/dist/modules/key_store.d.ts +60 -0
  508. package/dist/modules/key_store.d.ts.map +1 -0
  509. package/dist/modules/key_store.js +215 -0
  510. package/dist/modules/key_store.js.map +1 -0
  511. package/dist/modules/launcher/bot_supervisor.d.ts +84 -0
  512. package/dist/modules/launcher/bot_supervisor.d.ts.map +1 -0
  513. package/dist/modules/launcher/bot_supervisor.js +1067 -0
  514. package/dist/modules/launcher/bot_supervisor.js.map +1 -0
  515. package/dist/modules/launcher/child_env.d.ts +9 -0
  516. package/dist/modules/launcher/child_env.d.ts.map +1 -0
  517. package/dist/modules/launcher/child_env.js +78 -0
  518. package/dist/modules/launcher/child_env.js.map +1 -0
  519. package/dist/modules/launcher/credential_bootstrap.d.ts +22 -0
  520. package/dist/modules/launcher/credential_bootstrap.d.ts.map +1 -0
  521. package/dist/modules/launcher/credential_bootstrap.js +303 -0
  522. package/dist/modules/launcher/credential_bootstrap.js.map +1 -0
  523. package/dist/modules/launcher/credential_daemon.d.ts +32 -0
  524. package/dist/modules/launcher/credential_daemon.d.ts.map +1 -0
  525. package/dist/modules/launcher/credential_daemon.js +173 -0
  526. package/dist/modules/launcher/credential_daemon.js.map +1 -0
  527. package/dist/modules/launcher/credential_secret.d.ts +6 -0
  528. package/dist/modules/launcher/credential_secret.d.ts.map +1 -0
  529. package/dist/modules/launcher/credential_secret.js +15 -0
  530. package/dist/modules/launcher/credential_secret.js.map +1 -0
  531. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -0
  532. package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +1 -0
  533. package/dist/modules/launcher/foreign_cred_daemon.js +166 -0
  534. package/dist/modules/launcher/foreign_cred_daemon.js.map +1 -0
  535. package/dist/modules/launcher/headless_password.d.ts +8 -0
  536. package/dist/modules/launcher/headless_password.d.ts.map +1 -0
  537. package/dist/modules/launcher/headless_password.js +33 -0
  538. package/dist/modules/launcher/headless_password.js.map +1 -0
  539. package/dist/modules/launcher/launch_modes.d.ts +36 -0
  540. package/dist/modules/launcher/launch_modes.d.ts.map +1 -0
  541. package/dist/modules/launcher/launch_modes.js +129 -0
  542. package/dist/modules/launcher/launch_modes.js.map +1 -0
  543. package/dist/modules/launcher/market_adapter_runtime.d.ts +43 -0
  544. package/dist/modules/launcher/market_adapter_runtime.d.ts.map +1 -0
  545. package/dist/modules/launcher/market_adapter_runtime.js +217 -0
  546. package/dist/modules/launcher/market_adapter_runtime.js.map +1 -0
  547. package/dist/modules/launcher/market_adapter_watchdog.d.ts +26 -0
  548. package/dist/modules/launcher/market_adapter_watchdog.d.ts.map +1 -0
  549. package/dist/modules/launcher/market_adapter_watchdog.js +214 -0
  550. package/dist/modules/launcher/market_adapter_watchdog.js.map +1 -0
  551. package/dist/modules/launcher/monolithic_runtime.d.ts +89 -0
  552. package/dist/modules/launcher/monolithic_runtime.d.ts.map +1 -0
  553. package/dist/modules/launcher/monolithic_runtime.js +425 -0
  554. package/dist/modules/launcher/monolithic_runtime.js.map +1 -0
  555. package/dist/modules/launcher/runtime_entry.d.ts +26 -0
  556. package/dist/modules/launcher/runtime_entry.d.ts.map +1 -0
  557. package/dist/modules/launcher/runtime_entry.js +49 -0
  558. package/dist/modules/launcher/runtime_entry.js.map +1 -0
  559. package/dist/modules/launcher/status_reporting.d.ts +48 -0
  560. package/dist/modules/launcher/status_reporting.d.ts.map +1 -0
  561. package/dist/modules/launcher/status_reporting.js +113 -0
  562. package/dist/modules/launcher/status_reporting.js.map +1 -0
  563. package/dist/modules/launcher/supervisor_control.d.ts +6 -0
  564. package/dist/modules/launcher/supervisor_control.d.ts.map +1 -0
  565. package/dist/modules/launcher/supervisor_control.js +59 -0
  566. package/dist/modules/launcher/supervisor_control.js.map +1 -0
  567. package/dist/modules/logger.d.ts +2 -0
  568. package/dist/modules/logger.d.ts.map +1 -0
  569. package/dist/modules/logger.js +71 -0
  570. package/dist/modules/logger.js.map +1 -0
  571. package/dist/modules/market_adapter_whitelist.d.ts +22 -0
  572. package/dist/modules/market_adapter_whitelist.d.ts.map +1 -0
  573. package/dist/modules/market_adapter_whitelist.js +82 -0
  574. package/dist/modules/market_adapter_whitelist.js.map +1 -0
  575. package/dist/modules/node_health_cache.d.ts +55 -0
  576. package/dist/modules/node_health_cache.d.ts.map +1 -0
  577. package/dist/modules/node_health_cache.js +134 -0
  578. package/dist/modules/node_health_cache.js.map +1 -0
  579. package/dist/modules/node_manager.d.ts +215 -0
  580. package/dist/modules/node_manager.d.ts.map +1 -0
  581. package/dist/modules/node_manager.js +628 -0
  582. package/dist/modules/node_manager.js.map +1 -0
  583. package/dist/modules/order/accounting.d.ts +349 -0
  584. package/dist/modules/order/accounting.d.ts.map +1 -0
  585. package/dist/modules/order/accounting.js +1191 -0
  586. package/dist/modules/order/accounting.js.map +1 -0
  587. package/dist/modules/order/async_lock.d.ts +126 -0
  588. package/dist/modules/order/async_lock.d.ts.map +1 -0
  589. package/dist/modules/order/async_lock.js +195 -0
  590. package/dist/modules/order/async_lock.js.map +1 -0
  591. package/dist/modules/order/export.d.ts +129 -0
  592. package/dist/modules/order/export.d.ts.map +1 -0
  593. package/dist/modules/order/export.js +316 -0
  594. package/dist/modules/order/export.js.map +1 -0
  595. package/dist/modules/order/format.d.ts +158 -0
  596. package/dist/modules/order/format.d.ts.map +1 -0
  597. package/dist/modules/order/format.js +232 -0
  598. package/dist/modules/order/format.js.map +1 -0
  599. package/dist/modules/order/grid.d.ts +549 -0
  600. package/dist/modules/order/grid.d.ts.map +1 -0
  601. package/dist/modules/order/grid.js +1746 -0
  602. package/dist/modules/order/grid.js.map +1 -0
  603. package/dist/modules/order/grid_reconcile.d.ts +154 -0
  604. package/dist/modules/order/grid_reconcile.d.ts.map +1 -0
  605. package/dist/modules/order/grid_reconcile.js +1192 -0
  606. package/dist/modules/order/grid_reconcile.js.map +1 -0
  607. package/dist/modules/order/index.d.ts +55 -0
  608. package/dist/modules/order/index.d.ts.map +1 -0
  609. package/dist/modules/order/index.js +79 -0
  610. package/dist/modules/order/index.js.map +1 -0
  611. package/dist/modules/order/logger.d.ts +136 -0
  612. package/dist/modules/order/logger.d.ts.map +1 -0
  613. package/dist/modules/order/logger.js +614 -0
  614. package/dist/modules/order/logger.js.map +1 -0
  615. package/dist/modules/order/logger_state.d.ts +133 -0
  616. package/dist/modules/order/logger_state.d.ts.map +1 -0
  617. package/dist/modules/order/logger_state.js +170 -0
  618. package/dist/modules/order/logger_state.js.map +1 -0
  619. package/dist/modules/order/manager.d.ts +413 -0
  620. package/dist/modules/order/manager.d.ts.map +1 -0
  621. package/dist/modules/order/manager.js +1605 -0
  622. package/dist/modules/order/manager.js.map +1 -0
  623. package/dist/modules/order/processed_fill_store.d.ts +135 -0
  624. package/dist/modules/order/processed_fill_store.d.ts.map +1 -0
  625. package/dist/modules/order/processed_fill_store.js +288 -0
  626. package/dist/modules/order/processed_fill_store.js.map +1 -0
  627. package/dist/modules/order/runner.d.ts +70 -0
  628. package/dist/modules/order/runner.d.ts.map +1 -0
  629. package/dist/modules/order/runner.js +140 -0
  630. package/dist/modules/order/runner.js.map +1 -0
  631. package/dist/modules/order/strategy.d.ts +196 -0
  632. package/dist/modules/order/strategy.d.ts.map +1 -0
  633. package/dist/modules/order/strategy.js +398 -0
  634. package/dist/modules/order/strategy.js.map +1 -0
  635. package/dist/modules/order/sync_engine.d.ts +386 -0
  636. package/dist/modules/order/sync_engine.d.ts.map +1 -0
  637. package/dist/modules/order/sync_engine.js +1459 -0
  638. package/dist/modules/order/sync_engine.js.map +1 -0
  639. package/dist/modules/order/utils/math.d.ts +677 -0
  640. package/dist/modules/order/utils/math.d.ts.map +1 -0
  641. package/dist/modules/order/utils/math.js +1172 -0
  642. package/dist/modules/order/utils/math.js.map +1 -0
  643. package/dist/modules/order/utils/order.d.ts +572 -0
  644. package/dist/modules/order/utils/order.d.ts.map +1 -0
  645. package/dist/modules/order/utils/order.js +1145 -0
  646. package/dist/modules/order/utils/order.js.map +1 -0
  647. package/dist/modules/order/utils/system.d.ts +268 -0
  648. package/dist/modules/order/utils/system.d.ts.map +1 -0
  649. package/dist/modules/order/utils/system.js +1261 -0
  650. package/dist/modules/order/utils/system.js.map +1 -0
  651. package/dist/modules/order/utils/validate.d.ts +280 -0
  652. package/dist/modules/order/utils/validate.d.ts.map +1 -0
  653. package/dist/modules/order/utils/validate.js +918 -0
  654. package/dist/modules/order/utils/validate.js.map +1 -0
  655. package/dist/modules/order/working_grid.d.ts +212 -0
  656. package/dist/modules/order/working_grid.d.ts.map +1 -0
  657. package/dist/modules/order/working_grid.js +279 -0
  658. package/dist/modules/order/working_grid.js.map +1 -0
  659. package/dist/modules/path_api.d.ts +32 -0
  660. package/dist/modules/path_api.d.ts.map +1 -0
  661. package/dist/modules/path_api.js +148 -0
  662. package/dist/modules/path_api.js.map +1 -0
  663. package/dist/modules/paths.d.ts +58 -0
  664. package/dist/modules/paths.d.ts.map +1 -0
  665. package/dist/modules/paths.js +82 -0
  666. package/dist/modules/paths.js.map +1 -0
  667. package/dist/modules/process_discovery.d.ts +58 -0
  668. package/dist/modules/process_discovery.d.ts.map +1 -0
  669. package/dist/modules/process_discovery.js +265 -0
  670. package/dist/modules/process_discovery.js.map +1 -0
  671. package/dist/modules/runtime.d.ts +34 -0
  672. package/dist/modules/runtime.d.ts.map +1 -0
  673. package/dist/modules/runtime.js +98 -0
  674. package/dist/modules/runtime.js.map +1 -0
  675. package/dist/modules/runtime_settings.d.ts +12 -0
  676. package/dist/modules/runtime_settings.d.ts.map +1 -0
  677. package/dist/modules/runtime_settings.js +122 -0
  678. package/dist/modules/runtime_settings.js.map +1 -0
  679. package/dist/modules/settings_merge.d.ts +38 -0
  680. package/dist/modules/settings_merge.d.ts.map +1 -0
  681. package/dist/modules/settings_merge.js +246 -0
  682. package/dist/modules/settings_merge.js.map +1 -0
  683. package/dist/modules/storage/browser_adapter.d.ts +56 -0
  684. package/dist/modules/storage/browser_adapter.d.ts.map +1 -0
  685. package/dist/modules/storage/browser_adapter.js +231 -0
  686. package/dist/modules/storage/browser_adapter.js.map +1 -0
  687. package/dist/modules/storage/index.d.ts +28 -0
  688. package/dist/modules/storage/index.d.ts.map +1 -0
  689. package/dist/modules/storage/index.js +52 -0
  690. package/dist/modules/storage/index.js.map +1 -0
  691. package/dist/modules/storage/node_adapter.d.ts +49 -0
  692. package/dist/modules/storage/node_adapter.d.ts.map +1 -0
  693. package/dist/modules/storage/node_adapter.js +167 -0
  694. package/dist/modules/storage/node_adapter.js.map +1 -0
  695. package/dist/modules/storage/types.d.ts +92 -0
  696. package/dist/modules/storage/types.d.ts.map +1 -0
  697. package/dist/modules/storage/types.js +3 -0
  698. package/dist/modules/storage/types.js.map +1 -0
  699. package/dist/modules/types.d.ts +1382 -0
  700. package/dist/modules/types.d.ts.map +1 -0
  701. package/dist/modules/types.js +11 -0
  702. package/dist/modules/types.js.map +1 -0
  703. package/dist/modules/utils/base58check.d.ts +12 -0
  704. package/dist/modules/utils/base58check.d.ts.map +1 -0
  705. package/dist/modules/utils/base58check.js +112 -0
  706. package/dist/modules/utils/base58check.js.map +1 -0
  707. package/dist/modules/utils/build_dir.d.ts +7 -0
  708. package/dist/modules/utils/build_dir.d.ts.map +1 -0
  709. package/dist/modules/utils/build_dir.js +8 -0
  710. package/dist/modules/utils/build_dir.js.map +1 -0
  711. package/dist/modules/utils/fs_utils.d.ts +25 -0
  712. package/dist/modules/utils/fs_utils.d.ts.map +1 -0
  713. package/dist/modules/utils/fs_utils.js +27 -0
  714. package/dist/modules/utils/fs_utils.js.map +1 -0
  715. package/dist/modules/utils/math_utils.d.ts +10 -0
  716. package/dist/modules/utils/math_utils.d.ts.map +1 -0
  717. package/dist/modules/utils/math_utils.js +17 -0
  718. package/dist/modules/utils/math_utils.js.map +1 -0
  719. package/dist/modules/validate_profiles.d.ts +37 -0
  720. package/dist/modules/validate_profiles.d.ts.map +1 -0
  721. package/dist/modules/validate_profiles.js +369 -0
  722. package/dist/modules/validate_profiles.js.map +1 -0
  723. package/dist/pm2.d.ts +167 -0
  724. package/dist/pm2.d.ts.map +1 -0
  725. package/dist/pm2.js +998 -0
  726. package/dist/pm2.js.map +1 -0
  727. package/dist/scripts/analyze-git.d.ts +11 -0
  728. package/dist/scripts/analyze-git.d.ts.map +1 -0
  729. package/dist/scripts/analyze-git.js +851 -0
  730. package/dist/scripts/analyze-git.js.map +1 -0
  731. package/dist/scripts/analyze-orders.d.ts +17 -0
  732. package/dist/scripts/analyze-orders.d.ts.map +1 -0
  733. package/dist/scripts/analyze-orders.js +1568 -0
  734. package/dist/scripts/analyze-orders.js.map +1 -0
  735. package/dist/scripts/diagnose-kibana-candles.d.ts +3 -0
  736. package/dist/scripts/diagnose-kibana-candles.d.ts.map +1 -0
  737. package/dist/scripts/diagnose-kibana-candles.js +82 -0
  738. package/dist/scripts/diagnose-kibana-candles.js.map +1 -0
  739. package/dist/scripts/diagnose-pool-history.d.ts +3 -0
  740. package/dist/scripts/diagnose-pool-history.d.ts.map +1 -0
  741. package/dist/scripts/diagnose-pool-history.js +296 -0
  742. package/dist/scripts/diagnose-pool-history.js.map +1 -0
  743. package/dist/scripts/divergence-calc.d.ts +26 -0
  744. package/dist/scripts/divergence-calc.d.ts.map +1 -0
  745. package/dist/scripts/divergence-calc.js +119 -0
  746. package/dist/scripts/divergence-calc.js.map +1 -0
  747. package/dist/scripts/generate_lp_chart.d.ts +31 -0
  748. package/dist/scripts/generate_lp_chart.d.ts.map +1 -0
  749. package/dist/scripts/generate_lp_chart.js +92 -0
  750. package/dist/scripts/generate_lp_chart.js.map +1 -0
  751. package/dist/scripts/generate_mainnet_corpus_report.d.ts +24 -0
  752. package/dist/scripts/generate_mainnet_corpus_report.d.ts.map +1 -0
  753. package/dist/scripts/generate_mainnet_corpus_report.js +237 -0
  754. package/dist/scripts/generate_mainnet_corpus_report.js.map +1 -0
  755. package/dist/scripts/generate_market_adapter_whitelist.d.ts +2 -0
  756. package/dist/scripts/generate_market_adapter_whitelist.d.ts.map +1 -0
  757. package/dist/scripts/generate_market_adapter_whitelist.js +111 -0
  758. package/dist/scripts/generate_market_adapter_whitelist.js.map +1 -0
  759. package/dist/scripts/migrate_bot_keys.d.ts +6 -0
  760. package/dist/scripts/migrate_bot_keys.d.ts.map +1 -0
  761. package/dist/scripts/migrate_bot_keys.js +301 -0
  762. package/dist/scripts/migrate_bot_keys.js.map +1 -0
  763. package/dist/scripts/native_release_gates.d.ts +3 -0
  764. package/dist/scripts/native_release_gates.d.ts.map +1 -0
  765. package/dist/scripts/native_release_gates.js +52 -0
  766. package/dist/scripts/native_release_gates.js.map +1 -0
  767. package/dist/scripts/print_grid.d.ts +16 -0
  768. package/dist/scripts/print_grid.d.ts.map +1 -0
  769. package/dist/scripts/print_grid.js +80 -0
  770. package/dist/scripts/print_grid.js.map +1 -0
  771. package/dist/scripts/run-tests.d.ts +2 -0
  772. package/dist/scripts/run-tests.d.ts.map +1 -0
  773. package/dist/scripts/run-tests.js +49 -0
  774. package/dist/scripts/run-tests.js.map +1 -0
  775. package/dist/scripts/sync-version.d.ts +14 -0
  776. package/dist/scripts/sync-version.d.ts.map +1 -0
  777. package/dist/scripts/sync-version.js +158 -0
  778. package/dist/scripts/sync-version.js.map +1 -0
  779. package/dist/scripts/test-credit-renewal.d.ts +2 -0
  780. package/dist/scripts/test-credit-renewal.d.ts.map +1 -0
  781. package/dist/scripts/test-credit-renewal.js +329 -0
  782. package/dist/scripts/test-credit-renewal.js.map +1 -0
  783. package/dist/scripts/update.d.ts +24 -0
  784. package/dist/scripts/update.d.ts.map +1 -0
  785. package/dist/scripts/update.js +650 -0
  786. package/dist/scripts/update.js.map +1 -0
  787. package/dist/scripts/validate_bots.d.ts +16 -0
  788. package/dist/scripts/validate_bots.d.ts.map +1 -0
  789. package/dist/scripts/validate_bots.js +106 -0
  790. package/dist/scripts/validate_bots.js.map +1 -0
  791. package/dist/scripts/verify-browser-bundle.d.ts +22 -0
  792. package/dist/scripts/verify-browser-bundle.d.ts.map +1 -0
  793. package/dist/scripts/verify-browser-bundle.js +339 -0
  794. package/dist/scripts/verify-browser-bundle.js.map +1 -0
  795. package/dist/unlock.d.ts +48 -0
  796. package/dist/unlock.d.ts.map +1 -0
  797. package/dist/unlock.js +925 -0
  798. package/dist/unlock.js.map +1 -0
  799. package/package.json +112 -0
  800. package/scripts/README.md +356 -0
  801. package/scripts/clear-all.sh +195 -0
  802. package/scripts/clear-logs.sh +95 -0
  803. package/scripts/clear-market-adapter.sh +196 -0
  804. package/scripts/clear-orders.sh +113 -0
  805. package/scripts/create-bot-symlinks.sh +51 -0
  806. package/scripts/postinstall.js +9 -0
  807. package/scripts/reset-settings.sh +118 -0
@@ -0,0 +1,1261 @@
1
+ "use strict";
2
+ /**
3
+ * modules/order/utils/system.ts - System and I/O Utilities
4
+ *
5
+ * Price derivation, persistence, grid correction, and UI/interactive utilities.
6
+ *
7
+ * ===============================================================================
8
+ * TABLE OF CONTENTS (23 exported functions)
9
+ * ===============================================================================
10
+ *
11
+ * SECTION 1: PRICE DERIVATION (8 functions)
12
+ * - lookupAsset(BitShares, symbol) - Lookup asset metadata from blockchain
13
+ * - deriveMarketPrice(BitShares, symA, symB) - Derive price from order book
14
+ * - derivePoolPrice(BitShares, symA, symB) - Derive price from liquidity pool
15
+ * - derivePrice(BitShares, symA, symB, mode) - Derive price with fallback chain
16
+ * - resolveLiquidityPoolByShareAsset(BitShares, shareAsset) - Resolve LP by share asset
17
+ * - deriveLiquidityPoolTokenValue(BitShares, symA, symB) - Derive LP token value
18
+ * - loadAmaCenterPrice(manager) - Load AMA center price
19
+ * - loadAmaCenterSnapshot(manager) - Load AMA center snapshot
20
+ *
21
+ * SECTION 2: FEE MANAGEMENT (1 function)
22
+ * - initializeFeeCache(botsConfig, BitShares) - Initialize fee cache from blockchain
23
+ *
24
+ * SECTION 3: GRID STATE MANAGEMENT (3 functions)
25
+ * - persistGridSnapshot(manager, accountOrders) - Persist grid to storage
26
+ * - retryPersistenceIfNeeded(manager) - Retry persistence if previous failed
27
+ * - applyGridDivergenceCorrections(manager, ...) - Apply grid divergence corrections
28
+ *
29
+ * SECTION 4: GRID UTILITIES (1 function)
30
+ * - syncBoundaryToFunds(manager) - Sync boundary position to available funds
31
+ *
32
+ * SECTION 5: UI & INTERACTIVE UTILITIES (5 functions)
33
+ * - ensureProfilesDirectory(profilesDir) - Ensure profiles directory exists
34
+ * - sleep(ms) - Pause execution for specified duration
35
+ * - readInput(prompt, options) - Read user input from stdin
36
+ * - readPassword(prompt) - Read password with masked echo
37
+ * - withRetry(fn, options) - Execute async function with exponential backoff
38
+ *
39
+ * SECTION 6: GENERAL UTILITIES (5 functions)
40
+ * - resolveAccountRef(manager, account) - Resolve best account reference
41
+ * - deepFreeze(obj) - Recursively freeze object for immutability
42
+ * - cloneMap(map) - Create shallow clone of Map
43
+ * - ensureDir(dirPath) - Ensure directory exists, creating recursively
44
+ * - parseJsonWithComments(raw) - Parse JSON with comment stripping
45
+ *
46
+ * ===============================================================================
47
+ */
48
+ const { path } = require('../../path_api');
49
+ const { getStorage } = require('../../storage');
50
+ const { hasProcess, isBrowser } = require('../../env');
51
+ const storage = getStorage();
52
+ const { API_LIMITS, TIMING, ORDER_TYPES, ORDER_STATES, COW_ACTIONS, FEE_PARAMETERS, BTS_PRECISION, PIPELINE_TIMING } = require('../../constants');
53
+ const { PATHS } = require('../../paths');
54
+ const Format = require('../format');
55
+ const { toFiniteNumber, isValidNumber } = Format;
56
+ const MathUtils = require('./math');
57
+ const OrderUtils = require('./order');
58
+ const Logger = require('../../logger');
59
+ const { runtime } = require('../../runtime');
60
+ const { ensureDir, readJSON } = require('../../utils/fs_utils');
61
+ const systemLogger = new Logger('System');
62
+ function _debugLogAndNull(method, symA, symB) {
63
+ return (err) => {
64
+ // debug level: underlying derivePoolPrice/deriveMarketPrice already log at warn
65
+ systemLogger.debug(`derivePrice(${method}) for ${symA}/${symB}: ${err.message}`);
66
+ return null;
67
+ };
68
+ }
69
+ // ================================================================================
70
+ // SECTION 1: PRICE DERIVATION
71
+ // ================================================================================
72
+ const poolIdCache = new Map();
73
+ /**
74
+ * @private Lookup asset by symbol from BitShares blockchain.
75
+ * Tries cached assets first, then falls back to lookup API methods.
76
+ *
77
+ * @param {Object} BitShares - BitShares client instance
78
+ * @param {string} s - Asset symbol to lookup
79
+ * @returns {Promise<Object>} Asset metadata with id, symbol, precision
80
+ * @throws {Error} If asset cannot be found on blockchain
81
+ */
82
+ const lookupAsset = async (BitShares, s) => {
83
+ if (!BitShares)
84
+ return null;
85
+ let cached = null;
86
+ if (BitShares?.assets) {
87
+ try {
88
+ cached = await BitShares.assets[s];
89
+ }
90
+ catch (_) {
91
+ systemLogger.debug(`lookupAsset: cache access failed for ${s}`);
92
+ }
93
+ }
94
+ if (cached?.id && typeof cached.precision === 'number') {
95
+ return cached;
96
+ }
97
+ const methods = [
98
+ () => BitShares.db.lookup_asset_symbols([s]),
99
+ () => BitShares.db.get_assets([s])
100
+ ];
101
+ for (const method of methods) {
102
+ try {
103
+ if (typeof method !== 'function')
104
+ continue;
105
+ const r = await method();
106
+ if (r?.[0]?.id && typeof r[0].precision === 'number') {
107
+ return { ...(cached || {}), ...r[0] };
108
+ }
109
+ }
110
+ catch (e) {
111
+ systemLogger.debug(`lookupAsset: method failed for ${s}: ${e.message}`);
112
+ }
113
+ }
114
+ throw new Error(`CRITICAL: Cannot fetch asset precision for '${s}'`);
115
+ };
116
+ /**
117
+ * Derive price from BitShares DEX order book.
118
+ * Returns price in B/A format (units of asset B per 1 unit of asset A).
119
+ * Uses best bid and ask from order book, with fallback to ticker.
120
+ *
121
+ * @param {Object} BitShares - BitShares client instance
122
+ * @param {string} symA - First asset symbol
123
+ * @param {string} symB - Second asset symbol
124
+ * @returns {Promise<number|null>} Derived market price or null if unavailable
125
+ */
126
+ const deriveMarketPrice = async (BitShares, symA, symB) => {
127
+ try {
128
+ const [aMeta, bMeta] = await Promise.all([
129
+ lookupAsset(BitShares, symA),
130
+ lookupAsset(BitShares, symB)
131
+ ]);
132
+ if (!aMeta?.id || !bMeta?.id)
133
+ return null;
134
+ const baseId = aMeta.id;
135
+ const quoteId = bMeta.id;
136
+ let mid = null;
137
+ if (typeof BitShares.db?.get_order_book === 'function') {
138
+ try {
139
+ const ob = await BitShares.db.get_order_book(baseId, quoteId, API_LIMITS.ORDERBOOK_DEPTH);
140
+ const bestBid = isValidNumber(ob.bids?.[0]?.price) ? toFiniteNumber(ob.bids[0].price) : null;
141
+ const bestAsk = isValidNumber(ob.asks?.[0]?.price) ? toFiniteNumber(ob.asks[0].price) : null;
142
+ if (bestBid !== null && bestAsk !== null)
143
+ mid = (bestBid + bestAsk) / 2;
144
+ }
145
+ catch (e) {
146
+ systemLogger.debug(`deriveMarketPrice: get_order_book failed for ${symA}/${symB}: ${e.message}`);
147
+ }
148
+ }
149
+ if (mid === null && typeof BitShares.db?.get_ticker === 'function') {
150
+ try {
151
+ const t = await BitShares.db.get_ticker(baseId, quoteId);
152
+ mid = isValidNumber(t?.latest) ? toFiniteNumber(t.latest) : (isValidNumber(t?.latest_price) ? toFiniteNumber(t.latest_price) : null);
153
+ }
154
+ catch (err) {
155
+ systemLogger.debug(`deriveMarketPrice: get_ticker failed for ${symA}/${symB}: ${err.message}`);
156
+ }
157
+ }
158
+ // Return B/A orientation to match market price format
159
+ const finalPrice = (mid !== null && mid !== 0) ? 1 / mid : null;
160
+ if (finalPrice) {
161
+ systemLogger.info(`deriveMarketPrice: ${symA}/${symB} rawMid=${mid?.toFixed(8)} -> finalPrice(B/A)=${finalPrice.toFixed(8)}`);
162
+ }
163
+ return finalPrice;
164
+ }
165
+ catch (err) {
166
+ systemLogger.warn(`deriveMarketPrice failed for ${symA}/${symB}: ${err.message}`);
167
+ return null;
168
+ }
169
+ };
170
+ /**
171
+ * Derive price from BitShares Liquidity Pool (AMM).
172
+ * Returns price in B/A format (units of asset B per 1 unit of asset A).
173
+ * Handles internal BitShares ID-based asset ordering (asset_a/asset_b).
174
+ *
175
+ * @param {Object} BitShares - BitShares client instance
176
+ * @param {string} symA - First asset symbol
177
+ * @param {string} symB - Second asset symbol
178
+ * @returns {Promise<number|null>} Derived pool price or null if unavailable
179
+ */
180
+ const derivePoolPrice = async (BitShares, symA, symB) => {
181
+ try {
182
+ const [aMeta, bMeta] = await Promise.all([
183
+ lookupAsset(BitShares, symA),
184
+ lookupAsset(BitShares, symB)
185
+ ]);
186
+ if (!aMeta?.id || !bMeta?.id)
187
+ return null;
188
+ let chosen = null;
189
+ const cacheKey = [aMeta.id, bMeta.id].sort().join(':');
190
+ const cachedPoolId = poolIdCache.get(cacheKey);
191
+ if (typeof BitShares.db?.get_liquidity_pools_by_both_assets === 'function') {
192
+ try {
193
+ const pools = await BitShares.db.get_liquidity_pools_by_both_assets(aMeta.id, bMeta.id);
194
+ if (Array.isArray(pools) && pools.length > 0) {
195
+ const valid = pools.filter(p => p?.id);
196
+ if (valid.length) {
197
+ chosen = valid.sort((a, b) => {
198
+ const getBal = p => toFiniteNumber(String(p.asset_a) === String(aMeta.id) ? p.balance_a : p.balance_b);
199
+ return getBal(b) - getBal(a);
200
+ })[0];
201
+ if (chosen)
202
+ poolIdCache.set(cacheKey, chosen.id);
203
+ }
204
+ }
205
+ }
206
+ catch (e) {
207
+ systemLogger.debug(`derivePoolPrice: get_liquidity_pools_by_both_assets failed: ${e.message}`);
208
+ }
209
+ }
210
+ if (!chosen && cachedPoolId && typeof BitShares.db?.get_objects === 'function') {
211
+ try {
212
+ const [pool] = await BitShares.db.get_objects([cachedPoolId]);
213
+ if (pool)
214
+ chosen = pool;
215
+ }
216
+ catch (e) {
217
+ poolIdCache.delete(cacheKey);
218
+ }
219
+ }
220
+ if (!chosen) {
221
+ const listFn = BitShares.db?.list_liquidity_pools || BitShares.db?.get_liquidity_pools;
222
+ if (typeof listFn === 'function') {
223
+ try {
224
+ let startId = '1.19.0';
225
+ const PAGE_SIZE = 100;
226
+ const allMatches = [];
227
+ while (true) {
228
+ const pools = await listFn(PAGE_SIZE, startId);
229
+ if (!pools || pools.length === 0)
230
+ break;
231
+ // BitShares list_liquidity_pools is inclusive of startId.
232
+ // Skip the first pool in subsequent pages to avoid duplicate processing.
233
+ const effectivePools = (startId === '1.19.0') ? pools : pools.slice(1);
234
+ if (effectivePools.length === 0)
235
+ break;
236
+ const matches = effectivePools.filter(p => {
237
+ const ids = (p.asset_ids || [p.asset_a, p.asset_b]).map(String);
238
+ return ids.includes(String(aMeta.id)) && ids.includes(String(bMeta.id));
239
+ });
240
+ if (matches.length) {
241
+ allMatches.push(...matches);
242
+ }
243
+ if (pools.length < PAGE_SIZE) {
244
+ break;
245
+ }
246
+ else {
247
+ startId = pools[pools.length - 1].id;
248
+ }
249
+ }
250
+ if (allMatches.length) {
251
+ // Select pool with highest balance for our assetA
252
+ chosen = allMatches.sort((a, b) => {
253
+ const getBal = p => toFiniteNumber(String(p.asset_a) === String(aMeta.id) ? p.balance_a : p.balance_b);
254
+ return getBal(b) - getBal(a);
255
+ })[0];
256
+ poolIdCache.set(cacheKey, chosen.id);
257
+ }
258
+ }
259
+ catch (e) {
260
+ systemLogger.warn(`derivePoolPrice: pool pagination failed: ${e.message || e}`);
261
+ }
262
+ }
263
+ }
264
+ if (!chosen)
265
+ return null;
266
+ if (!chosen.reserves && !isValidNumber(chosen.balance_a) && typeof BitShares.db?.get_objects === 'function') {
267
+ try {
268
+ const [full] = await BitShares.db.get_objects([chosen.id]);
269
+ if (full)
270
+ chosen = full;
271
+ }
272
+ catch (e) {
273
+ systemLogger.debug(`derivePoolPrice: get_objects failed for pool ${chosen.id}: ${e.message}`);
274
+ }
275
+ }
276
+ let amtA = null, amtB = null;
277
+ if (isValidNumber(chosen.balance_a) && isValidNumber(chosen.balance_b)) {
278
+ // Pools store assets ordered by ID: lower ID is always first (asset_a)
279
+ const aIdNum = toFiniteNumber(String(aMeta.id).split('.')[2]);
280
+ const bIdNum = toFiniteNumber(String(bMeta.id).split('.')[2]);
281
+ const aIsFirst = aIdNum < bIdNum;
282
+ // If config's assetA has lower ID, it's the pool's first asset (asset_a)
283
+ // Otherwise, our assetA corresponds to pool's second asset (asset_b)
284
+ if (aIsFirst) {
285
+ amtA = toFiniteNumber(chosen.balance_a);
286
+ amtB = toFiniteNumber(chosen.balance_b);
287
+ }
288
+ else {
289
+ amtA = toFiniteNumber(chosen.balance_b);
290
+ amtB = toFiniteNumber(chosen.balance_a);
291
+ }
292
+ }
293
+ else if (Array.isArray(chosen.reserves)) {
294
+ const resA = chosen.reserves.find(r => String(r.asset_id) === String(aMeta.id));
295
+ const resB = chosen.reserves.find(r => String(r.asset_id) === String(bMeta.id));
296
+ if (resA && resB) {
297
+ amtA = resA.amount;
298
+ amtB = resB.amount;
299
+ }
300
+ }
301
+ if (!isValidNumber(amtA) || !isValidNumber(amtB) || toFiniteNumber(amtB) === 0)
302
+ return null;
303
+ const floatA = MathUtils.blockchainToFloat(amtA, aMeta.precision);
304
+ const floatB = MathUtils.blockchainToFloat(amtB, bMeta.precision);
305
+ // Return B/A orientation to match market price format
306
+ const finalPrice = floatB > 0 ? floatB / floatA : null;
307
+ if (finalPrice) {
308
+ systemLogger.info(`derivePoolPrice: ${symA}/${symB} pool=${chosen.id} amtA=${amtA}(prec=${aMeta.precision}) amtB=${amtB}(prec=${bMeta.precision}) -> finalPrice(B/A)=${finalPrice.toFixed(8)}`);
309
+ }
310
+ return finalPrice;
311
+ }
312
+ catch (err) {
313
+ systemLogger.warn(`derivePoolPrice failed for ${symA}/${symB}: ${err.message}`);
314
+ return null;
315
+ }
316
+ };
317
+ /**
318
+ * Derive price from blockchain using specified mode.
319
+ * Attempts pool or market derivation based on mode, with fallback chain.
320
+ *
321
+ * @param {Object} BitShares - BitShares client instance
322
+ * @param {string} symA - First asset symbol
323
+ * @param {string} symB - Second asset symbol
324
+ * @param {string} [mode='auto'] - Derivation mode: "pool", "book", or "auto" (pool → book).
325
+ * @returns {Promise<number|null>} Derived price or null if all methods fail
326
+ */
327
+ const derivePrice = async (BitShares, symA, symB, mode = 'auto') => {
328
+ mode = String(mode).toLowerCase();
329
+ const validModes = new Set(['pool', 'book', 'auto']);
330
+ if (!validModes.has(mode)) {
331
+ systemLogger.debug(`derivePrice: invalid mode "${mode}" for ${symA}/${symB}`);
332
+ return null;
333
+ }
334
+ if (mode === 'pool') {
335
+ return await derivePoolPrice(BitShares, symA, symB).catch(_debugLogAndNull('pool', symA, symB));
336
+ }
337
+ if (mode === 'book') {
338
+ return await deriveMarketPrice(BitShares, symA, symB).catch(_debugLogAndNull('book', symA, symB));
339
+ }
340
+ // mode === 'auto': pool preferred, market fallback
341
+ let poolP = null;
342
+ poolP = await derivePoolPrice(BitShares, symA, symB).catch(_debugLogAndNull('auto/pool', symA, symB));
343
+ if (poolP > 0)
344
+ return poolP;
345
+ const m = await deriveMarketPrice(BitShares, symA, symB).catch(_debugLogAndNull('auto/book', symA, symB));
346
+ if (m > 0)
347
+ return m;
348
+ systemLogger.debug(`derivePrice: all methods failed for ${symA}/${symB}`);
349
+ return null;
350
+ };
351
+ /**
352
+ * Resolve a liquidity pool from a share asset reference.
353
+ * Looks up the share asset, then queries the blockchain for associated pools.
354
+ *
355
+ * @param {Object} BitShares - BitShares client instance
356
+ * @param {string} shareAssetRef - Share asset symbol or reference
357
+ * @returns {Promise<Object|null>} Object with {shareAsset, pool} or null if not found
358
+ */
359
+ async function resolveLiquidityPoolByShareAsset(BitShares, shareAssetRef) {
360
+ if (!BitShares?.db || typeof BitShares.db.get_liquidity_pools_by_share_asset !== 'function') {
361
+ return null;
362
+ }
363
+ const shareAsset = await lookupAsset(BitShares, shareAssetRef).catch((e) => {
364
+ systemLogger.debug(`resolveLiquidityPoolByShareAsset: lookupAsset failed for ${shareAssetRef}: ${e.message}`);
365
+ return null;
366
+ });
367
+ if (!shareAsset?.id) {
368
+ return null;
369
+ }
370
+ const response = await BitShares.db.get_liquidity_pools_by_share_asset([shareAsset.id], false, false).catch((e) => {
371
+ systemLogger.debug(`resolveLiquidityPoolByShareAsset: get_liquidity_pools_by_share_asset failed for ${shareAssetRef}: ${e.message}`);
372
+ return null;
373
+ });
374
+ if (!Array.isArray(response)) {
375
+ return null;
376
+ }
377
+ const pool = response.find((entry) => entry && (entry.id || entry.pool?.id)) || null;
378
+ if (!pool) {
379
+ return null;
380
+ }
381
+ return {
382
+ shareAsset,
383
+ pool: pool.pool || pool,
384
+ };
385
+ }
386
+ async function getAssetCurrentSupply(BitShares, assetRef) {
387
+ const asset = typeof assetRef === 'object' && assetRef !== null
388
+ ? assetRef
389
+ : await lookupAsset(BitShares, assetRef).catch((e) => {
390
+ systemLogger.debug(`getAssetCurrentSupply: lookupAsset failed for ${assetRef}: ${e.message}`);
391
+ return null;
392
+ });
393
+ if (!asset) {
394
+ return null;
395
+ }
396
+ const directSupply = toFiniteNumber(asset.current_supply?.amount ?? asset.current_supply, null);
397
+ if (Number.isFinite(directSupply) && directSupply >= 0) {
398
+ return directSupply;
399
+ }
400
+ const dynamicId = asset.dynamic_asset_data_id || asset.dynamicDataId || asset.dynamic_data_id || null;
401
+ if (!dynamicId || typeof BitShares?.db?.get_objects !== 'function') {
402
+ return null;
403
+ }
404
+ const objects = await BitShares.db.get_objects([dynamicId]).catch((e) => {
405
+ systemLogger.debug(`getAssetCurrentSupply: get_objects failed for ${dynamicId}: ${e.message}`);
406
+ return null;
407
+ });
408
+ const dynamicData = Array.isArray(objects) ? objects[0] : null;
409
+ const supply = toFiniteNumber(dynamicData?.current_supply?.amount
410
+ ?? dynamicData?.current_supply?.value
411
+ ?? dynamicData?.current_supply, null);
412
+ return Number.isFinite(supply) && supply >= 0 ? supply : null;
413
+ }
414
+ /**
415
+ * Derive the value of a liquidity pool share token in a denomination asset.
416
+ * Resolves the pool, fetches reserves and supply, then prices both pool assets
417
+ * against the denomination asset to compute total value per share.
418
+ *
419
+ * @param {Object} BitShares - BitShares client instance
420
+ * @param {string} shareAssetRef - Share asset symbol
421
+ * @param {string} denominationAssetRef - Denomination asset symbol
422
+ * @param {string} [mode='auto'] - Price derivation mode ("pool", "book", or "auto")
423
+ * @returns {Promise<number|null>} Value per share in denomination asset, or null
424
+ */
425
+ async function deriveLiquidityPoolTokenValue(BitShares, shareAssetRef, denominationAssetRef, mode = 'auto') {
426
+ try {
427
+ const [shareAsset, denominationAsset] = await Promise.all([
428
+ lookupAsset(BitShares, shareAssetRef),
429
+ lookupAsset(BitShares, denominationAssetRef),
430
+ ]);
431
+ if (!shareAsset?.id || !denominationAsset?.id) {
432
+ return null;
433
+ }
434
+ const poolInfo = await resolveLiquidityPoolByShareAsset(BitShares, shareAsset.id);
435
+ if (!poolInfo?.pool) {
436
+ return null;
437
+ }
438
+ const [assetA, assetB, supply] = await Promise.all([
439
+ lookupAsset(BitShares, poolInfo.pool.asset_a),
440
+ lookupAsset(BitShares, poolInfo.pool.asset_b),
441
+ getAssetCurrentSupply(BitShares, shareAsset),
442
+ ]);
443
+ if (!assetA?.id || !assetB?.id || !Number.isFinite(supply) || supply <= 0) {
444
+ return null;
445
+ }
446
+ const reserveA = MathUtils.blockchainToFloat(poolInfo.pool.balance_a, assetA.precision);
447
+ const reserveB = MathUtils.blockchainToFloat(poolInfo.pool.balance_b, assetB.precision);
448
+ if (!isValidNumber(reserveA) || !isValidNumber(reserveB)) {
449
+ return null;
450
+ }
451
+ const priceA = String(assetA.id) === String(denominationAsset.id)
452
+ ? 1
453
+ : await derivePrice(BitShares, assetA.id, denominationAsset.id, mode).catch((e) => {
454
+ systemLogger.debug(`deriveLiquidityPoolTokenValue: derivePrice failed for ${assetA.id}/${denominationAsset.id}: ${e.message}`);
455
+ return null;
456
+ });
457
+ const priceB = String(assetB.id) === String(denominationAsset.id)
458
+ ? 1
459
+ : await derivePrice(BitShares, assetB.id, denominationAsset.id, mode).catch((e) => {
460
+ systemLogger.debug(`deriveLiquidityPoolTokenValue: derivePrice failed for ${assetB.id}/${denominationAsset.id}: ${e.message}`);
461
+ return null;
462
+ });
463
+ if (!isValidNumber(priceA) || !isValidNumber(priceB) || priceA <= 0 || priceB <= 0) {
464
+ return null;
465
+ }
466
+ const supplyFloat = MathUtils.blockchainToFloat(supply, shareAsset.precision);
467
+ if (!isValidNumber(supplyFloat) || supplyFloat <= 0) {
468
+ return null;
469
+ }
470
+ const totalValue = reserveA * priceA + reserveB * priceB;
471
+ const valuePerShare = totalValue / supplyFloat;
472
+ return isValidNumber(valuePerShare) && valuePerShare > 0 ? valuePerShare : null;
473
+ }
474
+ catch (err) {
475
+ systemLogger.debug(`deriveLiquidityPoolTokenValue failed for ${shareAssetRef}/${denominationAssetRef}: ${err.message}`);
476
+ return null;
477
+ }
478
+ }
479
+ /**
480
+ * Load the full dynamic grid snapshot written by market_adapter for a bot.
481
+ * The snapshot is stored atomically at profiles/orders/<botKey>.dynamicgrid.json
482
+ * and is updated every market adapter cycle. It contains the persisted grid
483
+ * center and, for dynamic-weight-whitelisted bots, any computed effective weight offsets.
484
+ * On full grid resets the bot may rewrite gridCenterPrice to the latest AMA baseline, but
485
+ * amaCenterPrice remains the raw AMA output for diagnostics and comparison.
486
+ * The snapshot may also expose AMA slope diagnostics and a gridPriceOffsetPct
487
+ * that downstream grid initialization can apply to the raw center price.
488
+ * Called by initializeGrid() when manager.config.gridPrice uses an AMA keyword,
489
+ * by performGridResync(), and by refreshDynamicWeightDistribution() before every
490
+ * rebalance so new orders use live weights — not only on grid reset.
491
+ * @param {string} botKey - Bot key (e.g. "iob-xrp-bts-0")
492
+ * @returns {Object|null} Snapshot with center and optional dynamicWeights fields, or null if invalid
493
+ */
494
+ function loadAmaCenterSnapshot(botKey) {
495
+ try {
496
+ const gridPriceFile = path.join(PATHS.ORDERS_DIR, `${botKey}.dynamicgrid.json`);
497
+ const data = readJSON(gridPriceFile);
498
+ const gridCenterPrice = Number(data?.gridCenterPrice ?? data?.centerPrice);
499
+ const amaCenterPrice = Number(data?.amaCenterPrice);
500
+ if (!Number.isFinite(gridCenterPrice) || gridCenterPrice <= 0) {
501
+ return null;
502
+ }
503
+ return {
504
+ gridCenterPrice,
505
+ centerPrice: gridCenterPrice,
506
+ amaCenterPrice: Number.isFinite(amaCenterPrice) && amaCenterPrice > 0 ? amaCenterPrice : null,
507
+ source: data?.source || null,
508
+ updatedAt: data?.updatedAt || null,
509
+ amaSlopePercentMode: data?.amaSlopePercentMode || null,
510
+ amaSlope: data?.amaSlope ?? null,
511
+ gridRangeScalingAmaSlope: data?.gridRangeScalingAmaSlope ?? null,
512
+ gridPriceOffsetPct: Number.isFinite(Number(data?.gridPriceOffsetPct))
513
+ ? Number(data.gridPriceOffsetPct)
514
+ : null,
515
+ amaSlopeDeltaPercent: Number.isFinite(Number(data?.amaSlopeDeltaPercent))
516
+ ? Number(data.amaSlopeDeltaPercent)
517
+ : null,
518
+ amaSlopeThresholdPercent: Number.isFinite(Number(data?.amaSlopeThresholdPercent))
519
+ ? Number(data.amaSlopeThresholdPercent)
520
+ : null,
521
+ dynamicWeights: data?.dynamicWeights || null,
522
+ asymmetricBounds: data?.asymmetricBounds && typeof data.asymmetricBounds === 'object'
523
+ ? data.asymmetricBounds
524
+ : null,
525
+ };
526
+ }
527
+ catch (_) {
528
+ return null;
529
+ }
530
+ }
531
+ /**
532
+ * Load the AMA grid center price written by market_adapter for a bot.
533
+ * This is the numeric accessor used by the order engine.
534
+ * @param {string} botKey - Bot key (e.g. "iob-xrp-bts-0")
535
+ * @returns {number|null} Grid center price in B/A format, or null if file absent/invalid
536
+ */
537
+ function loadAmaCenterPrice(botKey) {
538
+ const snapshot = loadAmaCenterSnapshot(botKey);
539
+ return snapshot ? snapshot.gridCenterPrice : null;
540
+ }
541
+ // ================================================================================
542
+ // SECTION 2: FEE MANAGEMENT (INIT)
543
+ // ================================================================================
544
+ /**
545
+ * Initialize fee cache from blockchain.
546
+ * Fetches BTS operation fees and asset market fees for all unique assets in config.
547
+ * Populates internal fee cache used by math.js::getAssetFees.
548
+ *
549
+ * @param {Array<Object>} botsConfig - Array of bot configurations
550
+ * @param {Object} BitShares - BitShares client instance
551
+ * @returns {Promise<Object>} Fee cache object keyed by asset symbol
552
+ */
553
+ async function initializeFeeCache(botsConfig, BitShares) {
554
+ const uniqueAssets = new Set(['BTS']);
555
+ for (const bot of botsConfig) {
556
+ if (bot.assetA)
557
+ uniqueAssets.add(bot.assetA);
558
+ if (bot.assetB)
559
+ uniqueAssets.add(bot.assetB);
560
+ }
561
+ const cache = {};
562
+ for (const assetSymbol of uniqueAssets) {
563
+ try {
564
+ if (assetSymbol === 'BTS') {
565
+ const globalProps = await BitShares.db.getGlobalProperties();
566
+ const currentFees = globalProps.parameters.current_fees.parameters;
567
+ const findFee = (opCode) => {
568
+ const param = currentFees.find(p => p[0] === opCode);
569
+ const fee = param?.[1]?.fee;
570
+ const feeNum = toFiniteNumber(fee);
571
+ return {
572
+ raw: feeNum,
573
+ satoshis: feeNum,
574
+ bts: MathUtils.blockchainToFloat(feeNum, BTS_PRECISION)
575
+ };
576
+ };
577
+ const makerFeeDiscountRaw = toFiniteNumber(globalProps?.parameters?.extensions?.maker_fee_discount_percent, FEE_PARAMETERS.MAKER_REFUND_PERCENT * 10000);
578
+ cache.BTS = {
579
+ limitOrderCreate: findFee(1),
580
+ limitOrderCancel: findFee(2),
581
+ limitOrderUpdate: findFee(77),
582
+ makerFeeDiscountPercent: Math.max(0, makerFeeDiscountRaw) / 10000
583
+ };
584
+ }
585
+ else {
586
+ const fullAsset = await lookupAsset(BitShares, assetSymbol);
587
+ const options = fullAsset.options || {};
588
+ cache[assetSymbol] = {
589
+ assetId: fullAsset.id,
590
+ symbol: assetSymbol,
591
+ precision: fullAsset.precision,
592
+ chargesMarketFees: (Number(options.flags || 0) & 0x01) !== 0,
593
+ marketFee: { percent: (options.market_fee_percent || 0) / 100 },
594
+ takerFee: options.taker_fee_percent ? { percent: options.taker_fee_percent / 100 } : null,
595
+ maxMarketFee: {
596
+ raw: options.max_market_fee || 0,
597
+ float: MathUtils.blockchainToFloat(options.max_market_fee || 0, fullAsset.precision)
598
+ }
599
+ };
600
+ }
601
+ }
602
+ catch (error) {
603
+ systemLogger.warn(`initializeFeeCache: failed to parse asset ${assetSymbol}: ${error.message}`);
604
+ }
605
+ }
606
+ MathUtils._setFeeCache(cache);
607
+ return cache;
608
+ }
609
+ // ================================================================================
610
+ // SECTION 3: GRID STATE MANAGEMENT
611
+ // ================================================================================
612
+ /**
613
+ * Persist current grid state to storage.
614
+ * Saves all orders, cache funds, fees, boundary index, and asset info.
615
+ *
616
+ * @param {Object} manager - OrderManager instance
617
+ * @param {Object} accountOrders - AccountOrders data accessor
618
+ * @returns {Promise<boolean>} True if persistence succeeded, false on error
619
+ */
620
+ async function persistGridSnapshot(manager, accountOrders, snapshotOrders) {
621
+ if (!manager || !accountOrders)
622
+ return false;
623
+ try {
624
+ const orders = Array.isArray(snapshotOrders)
625
+ ? snapshotOrders
626
+ : Array.from(manager.orders.values());
627
+ const pricing = manager._lastGridPricingContext || null;
628
+ let debugConfig = manager.config || null;
629
+ if (debugConfig && pricing) {
630
+ const { gridPrice: _gridPrice, configuredMinPrice: _configuredMinPrice, configuredMaxPrice: _configuredMaxPrice, rangeScalingFactor: _rangeScalingFactor, ...restConfig } = debugConfig;
631
+ debugConfig = {
632
+ gridPrice: pricing.gridPrice,
633
+ configuredMinPrice: pricing.configuredMinPrice,
634
+ configuredMaxPrice: pricing.configuredMaxPrice,
635
+ rangeScalingFactor: pricing.rangeScalingFactor,
636
+ ...restConfig
637
+ };
638
+ }
639
+ const btsBalance = (manager.config?.assetA !== 'BTS' && manager.config?.assetB !== 'BTS')
640
+ ? (manager.btsBalance || { free: 0, total: 0, locked: 0 })
641
+ : null;
642
+ await accountOrders.storeMasterGrid(orders, manager.funds.btsFeesOwed, manager.boundaryIdx, manager.assets || null, {
643
+ persistedAt: new Date().toISOString(),
644
+ config: debugConfig,
645
+ accountTotals: manager.accountTotals || null,
646
+ btsBalance: btsBalance
647
+ });
648
+ return true;
649
+ }
650
+ catch (e) {
651
+ return false;
652
+ }
653
+ }
654
+ /**
655
+ * Retry grid persistence if previous attempt failed.
656
+ * Clears persistence warning flag if successful.
657
+ *
658
+ * @param {Object} manager - OrderManager instance
659
+ * @returns {Promise<boolean>} True if persisted successfully or no warning, false on error
660
+ */
661
+ async function retryPersistenceIfNeeded(manager) {
662
+ if (!manager || !manager._persistenceWarning)
663
+ return true;
664
+ try {
665
+ const result = typeof manager.persistGrid === 'function' ? await manager.persistGrid() : true;
666
+ const success = result === true || (result && !result.skipped && result.isValid !== false);
667
+ if (success)
668
+ delete manager._persistenceWarning;
669
+ return success;
670
+ }
671
+ catch (e) {
672
+ systemLogger.warn(`retryPersistenceIfNeeded failed: ${e.message}`);
673
+ return false;
674
+ }
675
+ }
676
+ /**
677
+ * Apply grid corrections for divergence between calculated and active orders.
678
+ * Uses COW (Copy-on-Write): builds a working grid, plans updates/cancels/creates,
679
+ * executes blockchain operations, and commits working grid only on success.
680
+ *
681
+ * Surplus on-chain orders are cancelled (not resized to zero).
682
+ * Size updates are emitted only for committed ACTIVE/PARTIAL orders.
683
+ *
684
+ * @param {Object} manager - OrderManager instance
685
+ * @param {Object} accountOrders - AccountOrders data accessor
686
+ * @param {string} botKey - Bot identifier for persistence
687
+ * @param {Function} updateOrdersOnChainBatchFn - Batch update function for blockchain operations
688
+ * @returns {Promise<void>}
689
+ */
690
+ async function applyGridDivergenceCorrections(manager, accountOrders, botKey, updateOrdersOnChainBatchFn) {
691
+ if (isBrowser())
692
+ throw new Error('applyGridDivergenceCorrections is not available in browser');
693
+ if (!manager._gridLock)
694
+ return;
695
+ const Grid = require('../grid');
696
+ const { WorkingGrid } = require('../working_grid');
697
+ const { hasActionForOrder, removeActionsForOrder } = require('./validate');
698
+ // Phase 1: Pre-lock grid resizing using COW
699
+ // This calculates new sizes from blockchain state but DOES NOT modify master.
700
+ // pendingBoundaryIdx carries any fund-driven boundary shift through the COW
701
+ // pipeline so that manager.boundaryIdx is only updated atomically inside
702
+ // _commitWorkingGrid — never before the slot types are consistent.
703
+ let resizeCowResult = null;
704
+ let pendingBoundaryIdx = manager.boundaryIdx;
705
+ if (manager._gridSidesUpdated && manager._gridSidesUpdated.size > 0) {
706
+ const hasBuy = manager._gridSidesUpdated.has(ORDER_TYPES.BUY);
707
+ const hasSell = manager._gridSidesUpdated.has(ORDER_TYPES.SELL);
708
+ let resizeOrderType = hasBuy && hasSell
709
+ ? 'both'
710
+ : hasBuy
711
+ ? ORDER_TYPES.BUY
712
+ : ORDER_TYPES.SELL;
713
+ // If out-of-spread correction moves boundary, recompute both sides.
714
+ // Store the new index in pendingBoundaryIdx — do NOT touch manager.boundaryIdx
715
+ // here; updateGridFromBlockchainSnapshot will re-assign slot types in the
716
+ // WorkingGrid and _commitWorkingGrid will update manager.boundaryIdx atomically.
717
+ const boundarySync = syncBoundaryToFunds(manager);
718
+ if (manager.outOfSpread > 0 && boundarySync.changed) {
719
+ pendingBoundaryIdx = boundarySync.newIdx;
720
+ resizeOrderType = 'both';
721
+ manager._gridSidesUpdated.add(ORDER_TYPES.BUY);
722
+ manager._gridSidesUpdated.add(ORDER_TYPES.SELL);
723
+ }
724
+ try {
725
+ resizeCowResult = await Grid.updateGridFromBlockchainSnapshot(manager, resizeOrderType, true, pendingBoundaryIdx);
726
+ }
727
+ catch (err) {
728
+ manager.logger?.log?.(`[DIVERGENCE-COW] Grid resize failed: ${err.message}`, 'error');
729
+ manager._gridSidesUpdated.clear();
730
+ return;
731
+ }
732
+ }
733
+ // Phase 2: Create working grid for divergence corrections
734
+ // Use the resize working grid as starting point if available
735
+ let cowResult = null;
736
+ await manager._gridLock.acquire(async () => {
737
+ if (!manager._gridSidesUpdated || manager._gridSidesUpdated.size === 0)
738
+ return;
739
+ // Start from resize result if available, otherwise create fresh working grid
740
+ const workingGrid = resizeCowResult?.workingGrid
741
+ ? resizeCowResult.workingGrid
742
+ : new WorkingGrid(manager.orders, { baseVersion: manager._gridVersion });
743
+ const actions = resizeCowResult?.actions ? [...resizeCowResult.actions] : [];
744
+ for (const orderType of manager._gridSidesUpdated) {
745
+ const sideName = orderType === ORDER_TYPES.BUY ? 'buy' : 'sell';
746
+ const sidePrecision = MathUtils.getPrecisionByOrderType(manager.assets, orderType);
747
+ // Get current on-chain orders for this side (from master, not working)
748
+ const currentOnChainOrders = Array.from(manager.orders.values())
749
+ .filter(o => o.type === orderType && OrderUtils.isOrderPlaced(o));
750
+ // Get all slots for this side from working grid
751
+ const allSideSlots = Array.from(workingGrid.values())
752
+ .filter(o => o.type === orderType)
753
+ .sort((a, b) => sideName === 'buy' ? b.price - a.price : a.price - b.price);
754
+ // Calculate target count
755
+ const baseTargetCount = (manager.config.activeOrders && Number.isFinite(manager.config.activeOrders[sideName]))
756
+ ? Math.max(1, manager.config.activeOrders[sideName])
757
+ : currentOnChainOrders.length;
758
+ const targetCount = baseTargetCount;
759
+ // Determine desired slots (closest to market)
760
+ const desiredSlots = allSideSlots.slice(0, targetCount);
761
+ const desiredSlotIds = new Set(desiredSlots.map(s => s.id));
762
+ const onChainBySlotId = new Map(currentOnChainOrders.map(o => [o.id, o]));
763
+ // Process on-chain orders:
764
+ // - In desired window: keep/update committed size (if not already queued by Phase 1)
765
+ // - Outside desired window: cancel surplus order
766
+ for (const onChainOrder of currentOnChainOrders) {
767
+ // Get current slot from working grid (may have been updated in Phase 1)
768
+ const slot = workingGrid.get(onChainOrder.id);
769
+ const isDesired = desiredSlotIds.has(onChainOrder.id);
770
+ if (!isDesired || !slot || !(toFiniteNumber(slot.size) > 0)) {
771
+ removeActionsForOrder(actions, COW_ACTIONS.UPDATE, onChainOrder);
772
+ const hasQueuedCancel = hasActionForOrder(actions, COW_ACTIONS.CANCEL, onChainOrder);
773
+ if (!hasQueuedCancel) {
774
+ manager.logger.log(`[DIVERGENCE-COW] Queueing cancel for surplus ${onChainOrder.id} (chain id ${onChainOrder.orderId})`, 'info');
775
+ actions.push({
776
+ type: COW_ACTIONS.CANCEL,
777
+ id: onChainOrder.id,
778
+ orderId: onChainOrder.orderId
779
+ });
780
+ }
781
+ const current = slot || onChainOrder;
782
+ workingGrid.set(onChainOrder.id, OrderUtils.convertToSpreadPlaceholder(current));
783
+ continue;
784
+ }
785
+ // Phase 1 already queued committed size updates. Avoid duplicate UPDATEs.
786
+ const hasQueuedUpdate = hasActionForOrder(actions, COW_ACTIONS.UPDATE, onChainOrder);
787
+ const hasQueuedCancel = hasActionForOrder(actions, COW_ACTIONS.CANCEL, onChainOrder);
788
+ if (hasQueuedUpdate || hasQueuedCancel) {
789
+ continue;
790
+ }
791
+ const newSize = toFiniteNumber(slot.size);
792
+ const currentSize = toFiniteNumber(onChainOrder.size);
793
+ const sizeChanged = Number.isFinite(sidePrecision)
794
+ ? MathUtils.floatToBlockchainInt(newSize, sidePrecision) !== MathUtils.floatToBlockchainInt(currentSize, sidePrecision)
795
+ : newSize !== currentSize;
796
+ if (sizeChanged) {
797
+ manager.logger.log(`[DIVERGENCE-COW] Queueing size update for ${onChainOrder.id}: ${currentSize} -> ${newSize}`, 'info');
798
+ actions.push({
799
+ type: COW_ACTIONS.UPDATE,
800
+ id: onChainOrder.id,
801
+ orderId: onChainOrder.orderId,
802
+ newGridId: onChainOrder.id,
803
+ newSize,
804
+ newPrice: slot.price,
805
+ order: {
806
+ id: onChainOrder.id,
807
+ type: onChainOrder.type,
808
+ price: slot.price,
809
+ size: newSize
810
+ }
811
+ });
812
+ }
813
+ }
814
+ // Process holes: CREATE new orders for empty desired slots
815
+ for (const slot of desiredSlots) {
816
+ const hasCreate = hasActionForOrder(actions, COW_ACTIONS.CREATE, slot);
817
+ if (!onChainBySlotId.has(slot.id) && slot.size > 0 && !hasCreate) {
818
+ manager.logger.log(`[DIVERGENCE-COW] Queueing new placement for slot ${slot.id}`, 'info');
819
+ actions.push({
820
+ type: COW_ACTIONS.CREATE,
821
+ id: slot.id,
822
+ order: {
823
+ id: slot.id,
824
+ price: slot.price,
825
+ size: slot.size,
826
+ type: slot.type
827
+ }
828
+ });
829
+ }
830
+ }
831
+ }
832
+ // Build COW result with all actions
833
+ if (actions.length > 0) {
834
+ cowResult = {
835
+ actions,
836
+ workingGrid,
837
+ workingIndexes: workingGrid.getIndexes(),
838
+ workingBoundary: pendingBoundaryIdx,
839
+ aborted: false
840
+ };
841
+ }
842
+ else if (resizeCowResult?.hasWorkingChanges) {
843
+ // No on-chain operations required, but working grid changed (typically virtual sizing).
844
+ // Commit locally to keep master in sync with latest sizing context.
845
+ cowResult = {
846
+ actions: [],
847
+ workingGrid,
848
+ workingIndexes: workingGrid.getIndexes(),
849
+ workingBoundary: pendingBoundaryIdx,
850
+ localOnly: true,
851
+ aborted: false
852
+ };
853
+ }
854
+ });
855
+ // Phase 3: Execute corrections via COW batch
856
+ if (cowResult && !cowResult.aborted) {
857
+ try {
858
+ let result = null;
859
+ if (cowResult.localOnly) {
860
+ const committed = await manager._commitWorkingGrid(cowResult.workingGrid, cowResult.workingIndexes, cowResult.workingBoundary);
861
+ if (committed) {
862
+ if (typeof manager.persistGrid === 'function') {
863
+ await manager.persistGrid();
864
+ }
865
+ else {
866
+ await persistGridSnapshot(manager, accountOrders);
867
+ }
868
+ result = { executed: true, localOnly: true };
869
+ manager.logger.log(`[DIVERGENCE-COW] Applied local-only sizing updates (no blockchain ops)`, 'info');
870
+ }
871
+ else {
872
+ result = { executed: false, localOnly: true, commitSkipped: true };
873
+ manager.logger.log(`[DIVERGENCE-COW] Skipped local-only commit (working grid not committed)`, 'warn');
874
+ }
875
+ }
876
+ else {
877
+ result = await updateOrdersOnChainBatchFn(cowResult);
878
+ }
879
+ if (result && result.executed) {
880
+ manager.logger.log(`[DIVERGENCE-COW] Successfully applied divergence corrections`, 'info');
881
+ manager.outOfSpread = 0;
882
+ manager._gridSidesUpdated.clear();
883
+ // Grid already persisted via _commitWorkingGrid in updateOrdersOnChainBatch
884
+ }
885
+ else {
886
+ manager.logger.log(`[DIVERGENCE-COW] Divergence corrections not executed (working grid discarded)`, 'warn');
887
+ manager._gridSidesUpdated.clear();
888
+ }
889
+ }
890
+ catch (err) {
891
+ manager.logger.log(`[DIVERGENCE-COW] Error executing divergence corrections: ${err.message}`, 'error');
892
+ manager._gridSidesUpdated.clear();
893
+ }
894
+ }
895
+ else {
896
+ // No actions needed or aborted
897
+ manager._gridSidesUpdated.clear();
898
+ }
899
+ }
900
+ // ================================================================================
901
+ // SECTION 4: GRID UTILITIES
902
+ // ================================================================================
903
+ /**
904
+ * Synchronize grid boundary position based on available funds.
905
+ *
906
+ * Computes a fund-driven boundary index and clamps it to the gap between the
907
+ * highest on-chain BUY slot and the lowest on-chain SELL slot. The boundary
908
+ * may therefore only shift within the existing spread — it can never jump over
909
+ * a committed order on either side.
910
+ *
911
+ * A shift is only produced when the fund ratio is asymmetric enough that the
912
+ * clamped result differs from the current boundaryIdx. Balanced available
913
+ * funds yield a mid-range result that, after clamping, equals the current
914
+ * boundary and produces no change.
915
+ *
916
+ * No master-grid mutation is performed here; the caller is responsible for
917
+ * updating manager.boundaryIdx and triggering the subsequent COW resize.
918
+ *
919
+ * @param {Object} manager - OrderManager instance
920
+ * @returns {{ changed: boolean, newIdx?: number }}
921
+ */
922
+ function syncBoundaryToFunds(manager) {
923
+ if (isBrowser())
924
+ throw new Error('syncBoundaryToFunds is not available in browser');
925
+ const availA = (manager.funds?.available?.sell || 0);
926
+ const availB = (manager.funds?.available?.buy || 0);
927
+ const allSlots = Array.from(manager.orders.values()).sort((a, b) => a.price - b.price);
928
+ const Grid = require('../grid');
929
+ const gapSlots = Grid.calculateGapSlots(manager.config.incrementPercent, manager.config.targetSpreadPercent, manager.config.gridLimits);
930
+ // Determine the index range permitted by master-grid slot assignments.
931
+ // Both virtual and active orders count: the boundary must stay strictly
932
+ // between the highest BUY slot and the lowest SELL slot so it never
933
+ // crosses an existing order regardless of whether it is on-chain.
934
+ let maxBuyIdx = -1;
935
+ let minSellIdx = allSlots.length;
936
+ for (let i = 0; i < allSlots.length; i++) {
937
+ const slot = allSlots[i];
938
+ if (slot.type === ORDER_TYPES.BUY && i > maxBuyIdx)
939
+ maxBuyIdx = i;
940
+ if (slot.type === ORDER_TYPES.SELL && i < minSellIdx)
941
+ minSellIdx = i;
942
+ }
943
+ // Build clamp bounds from whichever sides have typed slots.
944
+ // If a side has no typed slots there is nothing to protect on that side,
945
+ // so the boundary is free to move to the corresponding edge of the grid.
946
+ const lowerBound = maxBuyIdx >= 0 ? maxBuyIdx + 1 : 0;
947
+ const upperBound = minSellIdx < allSlots.length ? minSellIdx - 1 : allSlots.length - 1;
948
+ // Bounds are contradictory — typed slots leave no gap to shift into.
949
+ if (lowerBound > upperBound) {
950
+ return { changed: false };
951
+ }
952
+ let newIdx = OrderUtils.calculateFundDrivenBoundary(allSlots, availA, availB, manager.config.startPrice, gapSlots);
953
+ // Clamp to the permitted range.
954
+ newIdx = Math.max(lowerBound, Math.min(newIdx, upperBound));
955
+ if (newIdx !== manager.boundaryIdx) {
956
+ return { changed: true, newIdx };
957
+ }
958
+ return { changed: false };
959
+ }
960
+ // ================================================================================
961
+ // SECTION 5: UI & INTERACTIVE UTILITIES
962
+ // ================================================================================
963
+ /**
964
+ * Ensure profiles directory exists, creating if necessary.
965
+ *
966
+ * @param {string} profilesDir - Path to profiles directory
967
+ * @returns {boolean} True if directory was created, false if it already existed
968
+ */
969
+ function ensureProfilesDirectory(profilesDir) {
970
+ if (!storage.exists(profilesDir)) {
971
+ ensureDir(profilesDir);
972
+ return true;
973
+ }
974
+ return false;
975
+ }
976
+ /**
977
+ * Pause execution for a specified duration.
978
+ * @param {number} ms - Milliseconds to sleep
979
+ * @returns {Promise<void>}
980
+ */
981
+ function sleep(ms) {
982
+ return new Promise(resolve => setTimeout(resolve, ms));
983
+ }
984
+ /**
985
+ * Read user input from stdin with optional masking.
986
+ * Handles raw terminal mode for interactive prompts.
987
+ * Supports password masking and backspace handling.
988
+ *
989
+ * @param {string} prompt - Prompt text to display
990
+ * @param {Object} [options={}] - Input options
991
+ * @param {boolean} [options.hideEchoBack=false] - Hide input echo (for passwords)
992
+ * @param {string} [options.mask=''] - Character to display instead of input
993
+ * @returns {Promise<string>} Trimmed user input
994
+ */
995
+ function readInput(prompt, options = {}) {
996
+ if (!hasProcess()) {
997
+ return Promise.reject(new Error('Interactive input not available in this environment'));
998
+ }
999
+ return new Promise((resolve) => {
1000
+ const stdin = runtime.stdin;
1001
+ const stdout = runtime.stdout;
1002
+ const ESC_SEQUENCE_TIMEOUT_MS = 150;
1003
+ let input = '';
1004
+ let cursorPos = 0;
1005
+ let escBuf = '';
1006
+ let escTimer = null;
1007
+ stdout.write(prompt);
1008
+ const isRaw = stdin.isRaw;
1009
+ if (stdin.isTTY)
1010
+ stdin.setRawMode(true);
1011
+ stdin.resume();
1012
+ stdin.setEncoding('utf8');
1013
+ function redraw() {
1014
+ const shouldMask = options.hideEchoBack || typeof options.mask === 'string';
1015
+ const maskChar = options.mask || '*';
1016
+ const display = shouldMask ? maskChar.repeat(input.length) : input;
1017
+ stdout.write('\r\x1b[K' + prompt + display);
1018
+ if (cursorPos < input.length) {
1019
+ stdout.write('\x1b[' + (input.length - cursorPos) + 'D');
1020
+ }
1021
+ }
1022
+ function handleSequence(seq) {
1023
+ // Arrow keys
1024
+ if (seq === 'D') {
1025
+ if (cursorPos > 0) {
1026
+ cursorPos--;
1027
+ redraw();
1028
+ }
1029
+ return true;
1030
+ }
1031
+ if (seq === 'C') {
1032
+ if (cursorPos < input.length) {
1033
+ cursorPos++;
1034
+ redraw();
1035
+ }
1036
+ return true;
1037
+ }
1038
+ // Home / End
1039
+ if (seq === 'H' || seq === 'OH') {
1040
+ cursorPos = 0;
1041
+ redraw();
1042
+ return true;
1043
+ }
1044
+ if (seq === 'F' || seq === 'OF') {
1045
+ cursorPos = input.length;
1046
+ redraw();
1047
+ return true;
1048
+ }
1049
+ // Delete
1050
+ if (seq === '3~') {
1051
+ if (cursorPos < input.length) {
1052
+ input = input.slice(0, cursorPos) + input.slice(cursorPos + 1);
1053
+ redraw();
1054
+ }
1055
+ return true;
1056
+ }
1057
+ // Insert
1058
+ if (seq === '2~') {
1059
+ return true;
1060
+ }
1061
+ return false;
1062
+ }
1063
+ function processEscBuf() {
1064
+ escTimer = null;
1065
+ const buf = escBuf;
1066
+ escBuf = '';
1067
+ // Standalone ESC
1068
+ if (buf === '\x1b') {
1069
+ cleanup();
1070
+ stdout.write('\r\x1b[K\n');
1071
+ return resolve('\x1b');
1072
+ }
1073
+ // CSI sequence: ESC [ <params> <final>
1074
+ if (buf.length >= 3 && buf[1] === '[') {
1075
+ const seq = buf.substring(2);
1076
+ if (handleSequence(seq))
1077
+ return;
1078
+ // Unhandled sequence — ignore
1079
+ return;
1080
+ }
1081
+ // ESC + something else (e.g. Alt+key) — ignore
1082
+ }
1083
+ function handleChar(ch) {
1084
+ if (ch === '\r' || ch === '\n' || ch === '\u0004') {
1085
+ cleanup();
1086
+ stdout.write('\n');
1087
+ return resolve(input.trim());
1088
+ }
1089
+ if (ch === '\u0003') {
1090
+ cleanup();
1091
+ stdout.write('\r\x1b[K\n');
1092
+ runtime.exit(0);
1093
+ }
1094
+ // Backspace
1095
+ if (ch === '\u007f' || ch === '\u0008') {
1096
+ if (cursorPos > 0) {
1097
+ input = input.slice(0, cursorPos - 1) + input.slice(cursorPos);
1098
+ cursorPos--;
1099
+ redraw();
1100
+ }
1101
+ return;
1102
+ }
1103
+ // Printable character — insert at cursor
1104
+ if (ch.charCodeAt(0) >= 32 && ch.charCodeAt(0) <= 126) {
1105
+ input = input.slice(0, cursorPos) + ch + input.slice(cursorPos);
1106
+ cursorPos++;
1107
+ redraw();
1108
+ }
1109
+ }
1110
+ const onData = (chunk) => {
1111
+ const s = String(chunk);
1112
+ for (let i = 0; i < s.length; i++) {
1113
+ const ch = s[i];
1114
+ // Accumulating an escape sequence
1115
+ if (escBuf) {
1116
+ escBuf += ch;
1117
+ // CSI: after ESC [, collect up to final byte (@-~)
1118
+ if (escBuf.length === 2 && escBuf[1] === '[')
1119
+ continue;
1120
+ if (escBuf.length > 2 && ch >= '@' && ch <= '~') {
1121
+ clearTimeout(escTimer);
1122
+ processEscBuf();
1123
+ }
1124
+ continue;
1125
+ }
1126
+ // Start of potential escape sequence
1127
+ if (ch === '\x1b') {
1128
+ escBuf = ch;
1129
+ escTimer = setTimeout(processEscBuf, ESC_SEQUENCE_TIMEOUT_MS);
1130
+ continue;
1131
+ }
1132
+ handleChar(ch);
1133
+ }
1134
+ };
1135
+ const cleanup = () => { clearTimeout(escTimer); escBuf = ''; stdin.removeListener('data', onData); if (stdin.isTTY)
1136
+ stdin.setRawMode(isRaw); };
1137
+ stdin.on('data', onData);
1138
+ });
1139
+ }
1140
+ /**
1141
+ * Read password input from user with masked echo.
1142
+ *
1143
+ * @param {string} prompt - Prompt text to display
1144
+ * @returns {Promise<string>} User-entered password
1145
+ */
1146
+ async function readPassword(prompt) { return readInput(prompt, { mask: '*', hideEchoBack: false }); }
1147
+ /**
1148
+ * Execute async function with exponential backoff retry logic.
1149
+ * Retries on failure with increasing delays up to maxDelayMs.
1150
+ *
1151
+ * @param {Function} fn - Async function to retry
1152
+ * @param {Object} [options={}] - Retry options
1153
+ * @param {number} [options.maxAttempts=3] - Maximum retry attempts
1154
+ * @param {number} [options.baseDelayMs=1000] - Base delay in milliseconds
1155
+ * @param {number} [options.maxDelayMs=10000] - Maximum delay in milliseconds
1156
+ * @param {Object} [options.logger=null] - Optional logger for retry messages
1157
+ * @param {string} [options.operationName='operation'] - Name for log messages
1158
+ * @returns {Promise<*>} Result of function execution
1159
+ * @throws {Error} If all attempts fail, throws the final error
1160
+ */
1161
+ async function withRetry(fn, options = {}) {
1162
+ const { maxAttempts = PIPELINE_TIMING.RETRY_MAX_ATTEMPTS, baseDelayMs = PIPELINE_TIMING.RETRY_BASE_DELAY_MS, maxDelayMs = PIPELINE_TIMING.RETRY_MAX_DELAY_MS, logger = null, operationName = 'operation' } = options;
1163
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
1164
+ try {
1165
+ return await fn();
1166
+ }
1167
+ catch (err) {
1168
+ if (attempt === maxAttempts)
1169
+ throw err;
1170
+ const delay = Math.min(baseDelayMs * Math.pow(2, attempt - 1), maxDelayMs);
1171
+ logger?.log?.(`${operationName} attempt ${attempt} failed. Retrying in ${delay}ms...`, 'warn');
1172
+ await sleep(delay);
1173
+ }
1174
+ }
1175
+ }
1176
+ // ================================================================================
1177
+ // SECTION 6: GENERAL UTILITIES
1178
+ // ================================================================================
1179
+ /**
1180
+ * Resolve the best account reference for blockchain reads.
1181
+ * Prefer account ID when available, fall back to account name.
1182
+ * Used by recovery and startup paths where implicit account context may be unavailable.
1183
+ * @param {Object} manager - OrderManager instance (optional)
1184
+ * @param {string} account - Account name (optional)
1185
+ * @returns {string|null} Resolved account reference or null
1186
+ */
1187
+ function resolveAccountRef(manager, account) {
1188
+ if (manager && typeof manager.accountId === 'string' && manager.accountId) {
1189
+ return manager.accountId;
1190
+ }
1191
+ if (manager && typeof manager.account === 'string' && manager.account) {
1192
+ return manager.account;
1193
+ }
1194
+ if (typeof account === 'string' && account) {
1195
+ return account;
1196
+ }
1197
+ return null;
1198
+ }
1199
+ /**
1200
+ * Recursively freezes an object to ensure immutability.
1201
+ * @param {Object} obj
1202
+ * @returns {Object}
1203
+ */
1204
+ function deepFreeze(obj) {
1205
+ if (obj === null || typeof obj !== 'object')
1206
+ return obj;
1207
+ Object.freeze(obj);
1208
+ Object.getOwnPropertyNames(obj).forEach(prop => {
1209
+ if (Object.prototype.hasOwnProperty.call(obj, prop) &&
1210
+ obj[prop] !== null &&
1211
+ (typeof obj[prop] === 'object' || typeof obj[prop] === 'function') &&
1212
+ !Object.isFrozen(obj[prop])) {
1213
+ deepFreeze(obj[prop]);
1214
+ }
1215
+ });
1216
+ return obj;
1217
+ }
1218
+ /**
1219
+ * Creates a shallow clone of a Map.
1220
+ * @param {Map} map
1221
+ * @returns {Map}
1222
+ */
1223
+ function cloneMap(map) {
1224
+ return new Map(map);
1225
+ }
1226
+ /**
1227
+ * Parses JSON content that may contain comments (/* or //).
1228
+ * Strips block comments then line comments before parsing.
1229
+ * @param {string} raw - The raw string content with possible comments.
1230
+ * @returns {Object} The parsed JSON object.
1231
+ */
1232
+ function parseJsonWithComments(raw) {
1233
+ const stripped = raw.replace(/\/\*(?:.|[\r\n])*?\*\//g, '').replace(/(^|\s*)\/\/.*$/gm, '');
1234
+ return JSON.parse(stripped);
1235
+ }
1236
+ module.exports = {
1237
+ lookupAsset,
1238
+ deriveMarketPrice,
1239
+ derivePoolPrice,
1240
+ derivePrice,
1241
+ resolveLiquidityPoolByShareAsset,
1242
+ deriveLiquidityPoolTokenValue,
1243
+ loadAmaCenterPrice,
1244
+ loadAmaCenterSnapshot,
1245
+ initializeFeeCache,
1246
+ persistGridSnapshot,
1247
+ retryPersistenceIfNeeded,
1248
+ applyGridDivergenceCorrections,
1249
+ syncBoundaryToFunds,
1250
+ ensureProfilesDirectory,
1251
+ sleep,
1252
+ readInput,
1253
+ readPassword,
1254
+ withRetry,
1255
+ resolveAccountRef,
1256
+ deepFreeze,
1257
+ cloneMap,
1258
+ ensureDir,
1259
+ parseJsonWithComments
1260
+ };
1261
+ //# sourceMappingURL=system.js.map