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.
- package/LICENSE +21 -0
- package/README.md +287 -0
- package/claw/README.md +513 -0
- package/claw/scripts/memu_runner.py +385 -0
- package/claw/skills/bitshares-guide/SKILL.md +14 -0
- package/claw/skills/bitshares-guide/references/example-skill-shells.md +18 -0
- package/claw/skills/bitshares-guide/references/presentation-patterns.md +19 -0
- package/claw/skills/bitshares-guide/references/scope-guardrails.md +9 -0
- package/claw/skills/launcher-ops/SKILL.md +18 -0
- package/claw/skills/launcher-ops/references/launcher-workflow.md +23 -0
- package/claw/skills/margin-trading/SKILL.md +23 -0
- package/claw/skills/margin-trading/references/honest-asset-list.md +74 -0
- package/claw/skills/margin-trading/references/honest-assets.md +44 -0
- package/claw/skills/margin-trading/references/position-management.md +203 -0
- package/claw/skills/margin-trading/references/trading-concepts.md +80 -0
- package/claw/skills/memu-memory/SKILL.md +218 -0
- package/claw/skills/shared/references/js-automation-overview.md +24 -0
- package/claw/skills/shared/references/safety-and-staleness.md +11 -0
- package/claw/skills/shared/references/skill-boundaries.md +17 -0
- package/claw/skills/trend-detection/SKILL.md +33 -0
- package/claw/skills/trend-detection/agents/openai.yaml +3 -0
- package/claw/skills/trend-detection/references/service.md +45 -0
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts +3 -0
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts.map +1 -0
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +149 -0
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.js.map +1 -0
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts +3 -0
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts.map +1 -0
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +387 -0
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +1 -0
- package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts +3 -0
- package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts.map +1 -0
- package/dist/analysis/ama_fitting/calibrate_convergence_er.js +200 -0
- package/dist/analysis/ama_fitting/calibrate_convergence_er.js.map +1 -0
- package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts +3 -0
- package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts.map +1 -0
- package/dist/analysis/ama_fitting/fetch_lp_candles.js +212 -0
- package/dist/analysis/ama_fitting/fetch_lp_candles.js.map +1 -0
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +31 -0
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts.map +1 -0
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +249 -0
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js.map +1 -0
- package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +2 -0
- package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts.map +1 -0
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js +782 -0
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js.map +1 -0
- package/dist/analysis/analyze_derivatives.d.ts +95 -0
- package/dist/analysis/analyze_derivatives.d.ts.map +1 -0
- package/dist/analysis/analyze_derivatives.js +295 -0
- package/dist/analysis/analyze_derivatives.js.map +1 -0
- package/dist/analysis/analyze_dynamic_weight.d.ts +14 -0
- package/dist/analysis/analyze_dynamic_weight.d.ts.map +1 -0
- package/dist/analysis/analyze_dynamic_weight.js +208 -0
- package/dist/analysis/analyze_dynamic_weight.js.map +1 -0
- package/dist/analysis/analyze_kalman.d.ts +13 -0
- package/dist/analysis/analyze_kalman.d.ts.map +1 -0
- package/dist/analysis/analyze_kalman.js +123 -0
- package/dist/analysis/analyze_kalman.js.map +1 -0
- package/dist/analysis/analyze_regime.d.ts +20 -0
- package/dist/analysis/analyze_regime.d.ts.map +1 -0
- package/dist/analysis/analyze_regime.js +139 -0
- package/dist/analysis/analyze_regime.js.map +1 -0
- package/dist/analysis/analyze_regime_windows.d.ts +19 -0
- package/dist/analysis/analyze_regime_windows.d.ts.map +1 -0
- package/dist/analysis/analyze_regime_windows.js +413 -0
- package/dist/analysis/analyze_regime_windows.js.map +1 -0
- package/dist/analysis/analyze_risk_profile.d.ts +3 -0
- package/dist/analysis/analyze_risk_profile.d.ts.map +1 -0
- package/dist/analysis/analyze_risk_profile.js +159 -0
- package/dist/analysis/analyze_risk_profile.js.map +1 -0
- package/dist/analysis/analyze_trade_heatmap.d.ts +3 -0
- package/dist/analysis/analyze_trade_heatmap.d.ts.map +1 -0
- package/dist/analysis/analyze_trade_heatmap.js +367 -0
- package/dist/analysis/analyze_trade_heatmap.js.map +1 -0
- package/dist/analysis/analyze_volatility.d.ts +22 -0
- package/dist/analysis/analyze_volatility.d.ts.map +1 -0
- package/dist/analysis/analyze_volatility.js +172 -0
- package/dist/analysis/analyze_volatility.js.map +1 -0
- package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +99 -0
- package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts.map +1 -0
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js +804 -0
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js.map +1 -0
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +2 -0
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts.map +1 -0
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +347 -0
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js.map +1 -0
- package/dist/analysis/bot_fitting/shared_utils.d.ts +15 -0
- package/dist/analysis/bot_fitting/shared_utils.d.ts.map +1 -0
- package/dist/analysis/bot_fitting/shared_utils.js +48 -0
- package/dist/analysis/bot_fitting/shared_utils.js.map +1 -0
- package/dist/analysis/bot_key_utils.d.ts +16 -0
- package/dist/analysis/bot_key_utils.d.ts.map +1 -0
- package/dist/analysis/bot_key_utils.js +61 -0
- package/dist/analysis/bot_key_utils.js.map +1 -0
- package/dist/analysis/bot_usage/discover_bot_accounts.d.ts +3 -0
- package/dist/analysis/bot_usage/discover_bot_accounts.d.ts.map +1 -0
- package/dist/analysis/bot_usage/discover_bot_accounts.js +498 -0
- package/dist/analysis/bot_usage/discover_bot_accounts.js.map +1 -0
- package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +546 -0
- package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +1 -0
- package/dist/analysis/bot_usage/kibana_bot_queries.js +427 -0
- package/dist/analysis/bot_usage/kibana_bot_queries.js.map +1 -0
- package/dist/analysis/chart_utils.d.ts +13 -0
- package/dist/analysis/chart_utils.d.ts.map +1 -0
- package/dist/analysis/chart_utils.js +142 -0
- package/dist/analysis/chart_utils.js.map +1 -0
- package/dist/analysis/derivative_chart_generator.d.ts +18 -0
- package/dist/analysis/derivative_chart_generator.d.ts.map +1 -0
- package/dist/analysis/derivative_chart_generator.js +896 -0
- package/dist/analysis/derivative_chart_generator.js.map +1 -0
- package/dist/analysis/math_utils.d.ts +35 -0
- package/dist/analysis/math_utils.d.ts.map +1 -0
- package/dist/analysis/math_utils.js +121 -0
- package/dist/analysis/math_utils.js.map +1 -0
- package/dist/analysis/price_sources.d.ts +34 -0
- package/dist/analysis/price_sources.d.ts.map +1 -0
- package/dist/analysis/price_sources.js +103 -0
- package/dist/analysis/price_sources.js.map +1 -0
- package/dist/analysis/trade_profitability.d.ts +115 -0
- package/dist/analysis/trade_profitability.d.ts.map +1 -0
- package/dist/analysis/trade_profitability.js +1247 -0
- package/dist/analysis/trade_profitability.js.map +1 -0
- package/dist/analysis/tradingview/analyze_tradingview.d.ts +38 -0
- package/dist/analysis/tradingview/analyze_tradingview.d.ts.map +1 -0
- package/dist/analysis/tradingview/analyze_tradingview.js +212 -0
- package/dist/analysis/tradingview/analyze_tradingview.js.map +1 -0
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +9 -0
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts.map +1 -0
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +1717 -0
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js.map +1 -0
- package/dist/analysis/trend_detection/derivative_analyzer.d.ts +250 -0
- package/dist/analysis/trend_detection/derivative_analyzer.d.ts.map +1 -0
- package/dist/analysis/trend_detection/derivative_analyzer.js +903 -0
- package/dist/analysis/trend_detection/derivative_analyzer.js.map +1 -0
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +6 -0
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +1 -0
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +1449 -0
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +1 -0
- package/dist/analysis/trend_detection/hurst_analyzer.d.ts +42 -0
- package/dist/analysis/trend_detection/hurst_analyzer.d.ts.map +1 -0
- package/dist/analysis/trend_detection/hurst_analyzer.js +159 -0
- package/dist/analysis/trend_detection/hurst_analyzer.js.map +1 -0
- package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +6 -0
- package/dist/analysis/trend_detection/kalman_chart_generator.d.ts.map +1 -0
- package/dist/analysis/trend_detection/kalman_chart_generator.js +408 -0
- package/dist/analysis/trend_detection/kalman_chart_generator.js.map +1 -0
- package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts +103 -0
- package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts.map +1 -0
- package/dist/analysis/trend_detection/kalman_trend_analyzer.js +229 -0
- package/dist/analysis/trend_detection/kalman_trend_analyzer.js.map +1 -0
- package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts +34 -0
- package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts.map +1 -0
- package/dist/analysis/trend_detection/kalman_velocity_smoothing.js +89 -0
- package/dist/analysis/trend_detection/kalman_velocity_smoothing.js.map +1 -0
- package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts +39 -0
- package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts.map +1 -0
- package/dist/analysis/trend_detection/permutation_entropy_analyzer.js +132 -0
- package/dist/analysis/trend_detection/permutation_entropy_analyzer.js.map +1 -0
- package/dist/analysis/trend_detection/regime_chart_generator.d.ts +6 -0
- package/dist/analysis/trend_detection/regime_chart_generator.d.ts.map +1 -0
- package/dist/analysis/trend_detection/regime_chart_generator.js +345 -0
- package/dist/analysis/trend_detection/regime_chart_generator.js.map +1 -0
- package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts +2 -0
- package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts.map +1 -0
- package/dist/analysis/trend_detection/tests/test_kalman_trend.js +130 -0
- package/dist/analysis/trend_detection/tests/test_kalman_trend.js.map +1 -0
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts +2 -0
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts.map +1 -0
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js +38 -0
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js.map +1 -0
- package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +6 -0
- package/dist/analysis/trend_detection/volatility_chart_generator.d.ts.map +1 -0
- package/dist/analysis/trend_detection/volatility_chart_generator.js +732 -0
- package/dist/analysis/trend_detection/volatility_chart_generator.js.map +1 -0
- package/dist/bot.d.ts +49 -0
- package/dist/bot.d.ts.map +1 -0
- package/dist/bot.js +221 -0
- package/dist/bot.js.map +1 -0
- package/dist/credential-daemon.d.ts +64 -0
- package/dist/credential-daemon.d.ts.map +1 -0
- package/dist/credential-daemon.js +987 -0
- package/dist/credential-daemon.js.map +1 -0
- package/dist/dexbot.d.ts +87 -0
- package/dist/dexbot.d.ts.map +1 -0
- package/dist/dexbot.js +1222 -0
- package/dist/dexbot.js.map +1 -0
- package/dist/market_adapter/ama_signal_runner.d.ts +3 -0
- package/dist/market_adapter/ama_signal_runner.d.ts.map +1 -0
- package/dist/market_adapter/ama_signal_runner.js +175 -0
- package/dist/market_adapter/ama_signal_runner.js.map +1 -0
- package/dist/market_adapter/candle_utils.d.ts +57 -0
- package/dist/market_adapter/candle_utils.d.ts.map +1 -0
- package/dist/market_adapter/candle_utils.js +252 -0
- package/dist/market_adapter/candle_utils.js.map +1 -0
- package/dist/market_adapter/core/asymmetric_bounds.d.ts +20 -0
- package/dist/market_adapter/core/asymmetric_bounds.d.ts.map +1 -0
- package/dist/market_adapter/core/asymmetric_bounds.js +88 -0
- package/dist/market_adapter/core/asymmetric_bounds.js.map +1 -0
- package/dist/market_adapter/core/config_normalizers.d.ts +10 -0
- package/dist/market_adapter/core/config_normalizers.d.ts.map +1 -0
- package/dist/market_adapter/core/config_normalizers.js +24 -0
- package/dist/market_adapter/core/config_normalizers.js.map +1 -0
- package/dist/market_adapter/core/kibana_candles.d.ts +74 -0
- package/dist/market_adapter/core/kibana_candles.d.ts.map +1 -0
- package/dist/market_adapter/core/kibana_candles.js +249 -0
- package/dist/market_adapter/core/kibana_candles.js.map +1 -0
- package/dist/market_adapter/core/kibana_client.d.ts +27 -0
- package/dist/market_adapter/core/kibana_client.d.ts.map +1 -0
- package/dist/market_adapter/core/kibana_client.js +120 -0
- package/dist/market_adapter/core/kibana_client.js.map +1 -0
- package/dist/market_adapter/core/kibana_market_candles.d.ts +143 -0
- package/dist/market_adapter/core/kibana_market_candles.d.ts.map +1 -0
- package/dist/market_adapter/core/kibana_market_candles.js +170 -0
- package/dist/market_adapter/core/kibana_market_candles.js.map +1 -0
- package/dist/market_adapter/core/market_adapter_service.d.ts +210 -0
- package/dist/market_adapter/core/market_adapter_service.d.ts.map +1 -0
- package/dist/market_adapter/core/market_adapter_service.js +2328 -0
- package/dist/market_adapter/core/market_adapter_service.js.map +1 -0
- package/dist/market_adapter/core/strategies/ama.d.ts +2 -0
- package/dist/market_adapter/core/strategies/ama.d.ts.map +1 -0
- package/dist/market_adapter/core/strategies/ama.js +138 -0
- package/dist/market_adapter/core/strategies/ama.js.map +1 -0
- package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +50 -0
- package/dist/market_adapter/core/strategies/ama_slope_model.d.ts.map +1 -0
- package/dist/market_adapter/core/strategies/ama_slope_model.js +143 -0
- package/dist/market_adapter/core/strategies/ama_slope_model.js.map +1 -0
- package/dist/market_adapter/core/strategies/atr/calculator.d.ts +12 -0
- package/dist/market_adapter/core/strategies/atr/calculator.d.ts.map +1 -0
- package/dist/market_adapter/core/strategies/atr/calculator.js +47 -0
- package/dist/market_adapter/core/strategies/atr/calculator.js.map +1 -0
- package/dist/market_adapter/core/strategies/collateral_manager.d.ts +32 -0
- package/dist/market_adapter/core/strategies/collateral_manager.d.ts.map +1 -0
- package/dist/market_adapter/core/strategies/collateral_manager.js +68 -0
- package/dist/market_adapter/core/strategies/collateral_manager.js.map +1 -0
- package/dist/market_adapter/core/strategies/regime_gate.d.ts +66 -0
- package/dist/market_adapter/core/strategies/regime_gate.d.ts.map +1 -0
- package/dist/market_adapter/core/strategies/regime_gate.js +189 -0
- package/dist/market_adapter/core/strategies/regime_gate.js.map +1 -0
- package/dist/market_adapter/index.d.ts +10 -0
- package/dist/market_adapter/index.d.ts.map +1 -0
- package/dist/market_adapter/index.js +71 -0
- package/dist/market_adapter/index.js.map +1 -0
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.d.ts +3 -0
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.d.ts.map +1 -0
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +1165 -0
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js.map +1 -0
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +54 -0
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts.map +1 -0
- package/dist/market_adapter/inputs/fetch_lp_data.js +743 -0
- package/dist/market_adapter/inputs/fetch_lp_data.js.map +1 -0
- package/dist/market_adapter/inputs/kibana_source.d.ts +68 -0
- package/dist/market_adapter/inputs/kibana_source.d.ts.map +1 -0
- package/dist/market_adapter/inputs/kibana_source.js +143 -0
- package/dist/market_adapter/inputs/kibana_source.js.map +1 -0
- package/dist/market_adapter/interval_utils.d.ts +6 -0
- package/dist/market_adapter/interval_utils.d.ts.map +1 -0
- package/dist/market_adapter/interval_utils.js +14 -0
- package/dist/market_adapter/interval_utils.js.map +1 -0
- package/dist/market_adapter/log_format.d.ts +16 -0
- package/dist/market_adapter/log_format.d.ts.map +1 -0
- package/dist/market_adapter/log_format.js +72 -0
- package/dist/market_adapter/log_format.js.map +1 -0
- package/dist/market_adapter/lp_chart_core.d.ts +6 -0
- package/dist/market_adapter/lp_chart_core.d.ts.map +1 -0
- package/dist/market_adapter/lp_chart_core.js +874 -0
- package/dist/market_adapter/lp_chart_core.js.map +1 -0
- package/dist/market_adapter/lp_chart_runner.d.ts +135 -0
- package/dist/market_adapter/lp_chart_runner.d.ts.map +1 -0
- package/dist/market_adapter/lp_chart_runner.js +337 -0
- package/dist/market_adapter/lp_chart_runner.js.map +1 -0
- package/dist/market_adapter/lp_chart_strategy_loader.d.ts +23 -0
- package/dist/market_adapter/lp_chart_strategy_loader.d.ts.map +1 -0
- package/dist/market_adapter/lp_chart_strategy_loader.js +169 -0
- package/dist/market_adapter/lp_chart_strategy_loader.js.map +1 -0
- package/dist/market_adapter/market_adapter.d.ts +133 -0
- package/dist/market_adapter/market_adapter.d.ts.map +1 -0
- package/dist/market_adapter/market_adapter.js +1331 -0
- package/dist/market_adapter/market_adapter.js.map +1 -0
- package/dist/market_adapter/merge_lp_data.d.ts +3 -0
- package/dist/market_adapter/merge_lp_data.d.ts.map +1 -0
- package/dist/market_adapter/merge_lp_data.js +125 -0
- package/dist/market_adapter/merge_lp_data.js.map +1 -0
- package/dist/market_adapter/test_helpers.d.ts +14 -0
- package/dist/market_adapter/test_helpers.d.ts.map +1 -0
- package/dist/market_adapter/test_helpers.js +22 -0
- package/dist/market_adapter/test_helpers.js.map +1 -0
- package/dist/market_adapter/utils/adapter_client.d.ts +20 -0
- package/dist/market_adapter/utils/adapter_client.d.ts.map +1 -0
- package/dist/market_adapter/utils/adapter_client.js +88 -0
- package/dist/market_adapter/utils/adapter_client.js.map +1 -0
- package/dist/market_adapter/utils/atomic_write.d.ts +9 -0
- package/dist/market_adapter/utils/atomic_write.d.ts.map +1 -0
- package/dist/market_adapter/utils/atomic_write.js +13 -0
- package/dist/market_adapter/utils/atomic_write.js.map +1 -0
- package/dist/market_adapter/utils/chain.d.ts +50 -0
- package/dist/market_adapter/utils/chain.d.ts.map +1 -0
- package/dist/market_adapter/utils/chain.js +196 -0
- package/dist/market_adapter/utils/chain.js.map +1 -0
- package/dist/market_adapter/utils/data_discovery.d.ts +6 -0
- package/dist/market_adapter/utils/data_discovery.d.ts.map +1 -0
- package/dist/market_adapter/utils/data_discovery.js +35 -0
- package/dist/market_adapter/utils/data_discovery.js.map +1 -0
- package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +15 -0
- package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts.map +1 -0
- package/dist/market_adapter/utils/dynamic_grid_snapshot.js +60 -0
- package/dist/market_adapter/utils/dynamic_grid_snapshot.js.map +1 -0
- package/dist/market_adapter/utils/file_lock.d.ts +19 -0
- package/dist/market_adapter/utils/file_lock.d.ts.map +1 -0
- package/dist/market_adapter/utils/file_lock.js +191 -0
- package/dist/market_adapter/utils/file_lock.js.map +1 -0
- package/dist/market_adapter/utils/native_history.d.ts +19 -0
- package/dist/market_adapter/utils/native_history.d.ts.map +1 -0
- package/dist/market_adapter/utils/native_history.js +172 -0
- package/dist/market_adapter/utils/native_history.js.map +1 -0
- package/dist/market_adapter/utils/paths.d.ts +5 -0
- package/dist/market_adapter/utils/paths.d.ts.map +1 -0
- package/dist/market_adapter/utils/paths.js +7 -0
- package/dist/market_adapter/utils/paths.js.map +1 -0
- package/dist/modules/account_bots.d.ts +112 -0
- package/dist/modules/account_bots.d.ts.map +1 -0
- package/dist/modules/account_bots.js +1259 -0
- package/dist/modules/account_bots.js.map +1 -0
- package/dist/modules/account_orders.d.ts +273 -0
- package/dist/modules/account_orders.d.ts.map +1 -0
- package/dist/modules/account_orders.js +662 -0
- package/dist/modules/account_orders.js.map +1 -0
- package/dist/modules/authority_resolver.d.ts +2 -0
- package/dist/modules/authority_resolver.d.ts.map +1 -0
- package/dist/modules/authority_resolver.js +231 -0
- package/dist/modules/authority_resolver.js.map +1 -0
- package/dist/modules/bitshares-native/chain_client.d.ts +38 -0
- package/dist/modules/bitshares-native/chain_client.d.ts.map +1 -0
- package/dist/modules/bitshares-native/chain_client.js +322 -0
- package/dist/modules/bitshares-native/chain_client.js.map +1 -0
- package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts +59 -0
- package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts.map +1 -0
- package/dist/modules/bitshares-native/crypto/ecc.browser.js +456 -0
- package/dist/modules/bitshares-native/crypto/ecc.browser.js.map +1 -0
- package/dist/modules/bitshares-native/crypto/ecc.d.ts +66 -0
- package/dist/modules/bitshares-native/crypto/ecc.d.ts.map +1 -0
- package/dist/modules/bitshares-native/crypto/ecc.js +557 -0
- package/dist/modules/bitshares-native/crypto/ecc.js.map +1 -0
- package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -0
- package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts.map +1 -0
- package/dist/modules/bitshares-native/crypto/ecc_selector.js +20 -0
- package/dist/modules/bitshares-native/crypto/ecc_selector.js.map +1 -0
- package/dist/modules/bitshares-native/index.d.ts +3 -0
- package/dist/modules/bitshares-native/index.d.ts.map +1 -0
- package/dist/modules/bitshares-native/index.js +32 -0
- package/dist/modules/bitshares-native/index.js.map +1 -0
- package/dist/modules/bitshares-native/resolvers.d.ts +40 -0
- package/dist/modules/bitshares-native/resolvers.d.ts.map +1 -0
- package/dist/modules/bitshares-native/resolvers.js +161 -0
- package/dist/modules/bitshares-native/resolvers.js.map +1 -0
- package/dist/modules/bitshares-native/serial/chain_constants.d.ts +56 -0
- package/dist/modules/bitshares-native/serial/chain_constants.d.ts.map +1 -0
- package/dist/modules/bitshares-native/serial/chain_constants.js +92 -0
- package/dist/modules/bitshares-native/serial/chain_constants.js.map +1 -0
- package/dist/modules/bitshares-native/serial/index.d.ts +10 -0
- package/dist/modules/bitshares-native/serial/index.d.ts.map +1 -0
- package/dist/modules/bitshares-native/serial/index.js +14 -0
- package/dist/modules/bitshares-native/serial/index.js.map +1 -0
- package/dist/modules/bitshares-native/serial/operations.d.ts +102 -0
- package/dist/modules/bitshares-native/serial/operations.d.ts.map +1 -0
- package/dist/modules/bitshares-native/serial/operations.js +615 -0
- package/dist/modules/bitshares-native/serial/operations.js.map +1 -0
- package/dist/modules/bitshares-native/serial/serializer.d.ts +64 -0
- package/dist/modules/bitshares-native/serial/serializer.d.ts.map +1 -0
- package/dist/modules/bitshares-native/serial/serializer.js +252 -0
- package/dist/modules/bitshares-native/serial/serializer.js.map +1 -0
- package/dist/modules/bitshares-native/serial/types.d.ts +120 -0
- package/dist/modules/bitshares-native/serial/types.d.ts.map +1 -0
- package/dist/modules/bitshares-native/serial/types.js +837 -0
- package/dist/modules/bitshares-native/serial/types.js.map +1 -0
- package/dist/modules/bitshares-native/signing_client.d.ts +6 -0
- package/dist/modules/bitshares-native/signing_client.d.ts.map +1 -0
- package/dist/modules/bitshares-native/signing_client.js +141 -0
- package/dist/modules/bitshares-native/signing_client.js.map +1 -0
- package/dist/modules/bitshares-native/subscriptions.d.ts +6 -0
- package/dist/modules/bitshares-native/subscriptions.d.ts.map +1 -0
- package/dist/modules/bitshares-native/subscriptions.js +865 -0
- package/dist/modules/bitshares-native/subscriptions.js.map +1 -0
- package/dist/modules/bitshares-native/transport.d.ts +51 -0
- package/dist/modules/bitshares-native/transport.d.ts.map +1 -0
- package/dist/modules/bitshares-native/transport.js +447 -0
- package/dist/modules/bitshares-native/transport.js.map +1 -0
- package/dist/modules/bitshares-native/tx/builder.d.ts +30 -0
- package/dist/modules/bitshares-native/tx/builder.d.ts.map +1 -0
- package/dist/modules/bitshares-native/tx/builder.js +262 -0
- package/dist/modules/bitshares-native/tx/builder.js.map +1 -0
- package/dist/modules/bitshares_client.d.ts +129 -0
- package/dist/modules/bitshares_client.d.ts.map +1 -0
- package/dist/modules/bitshares_client.js +627 -0
- package/dist/modules/bitshares_client.js.map +1 -0
- package/dist/modules/bot_settings.d.ts +33 -0
- package/dist/modules/bot_settings.d.ts.map +1 -0
- package/dist/modules/bot_settings.js +328 -0
- package/dist/modules/bot_settings.js.map +1 -0
- package/dist/modules/bots_file_lock.d.ts +88 -0
- package/dist/modules/bots_file_lock.d.ts.map +1 -0
- package/dist/modules/bots_file_lock.js +161 -0
- package/dist/modules/bots_file_lock.js.map +1 -0
- package/dist/modules/chain_keys.d.ts +302 -0
- package/dist/modules/chain_keys.d.ts.map +1 -0
- package/dist/modules/chain_keys.js +1095 -0
- package/dist/modules/chain_keys.js.map +1 -0
- package/dist/modules/chain_orders.d.ts +423 -0
- package/dist/modules/chain_orders.d.ts.map +1 -0
- package/dist/modules/chain_orders.js +1201 -0
- package/dist/modules/chain_orders.js.map +1 -0
- package/dist/modules/cli_whitelist_args.d.ts +6 -0
- package/dist/modules/cli_whitelist_args.d.ts.map +1 -0
- package/dist/modules/cli_whitelist_args.js +13 -0
- package/dist/modules/cli_whitelist_args.js.map +1 -0
- package/dist/modules/config.d.ts +57 -0
- package/dist/modules/config.d.ts.map +1 -0
- package/dist/modules/config.js +107 -0
- package/dist/modules/config.js.map +1 -0
- package/dist/modules/constants.d.ts +635 -0
- package/dist/modules/constants.d.ts.map +1 -0
- package/dist/modules/constants.js +1464 -0
- package/dist/modules/constants.js.map +1 -0
- package/dist/modules/cr_planner.d.ts +51 -0
- package/dist/modules/cr_planner.d.ts.map +1 -0
- package/dist/modules/cr_planner.js +299 -0
- package/dist/modules/cr_planner.js.map +1 -0
- package/dist/modules/credential_policy.d.ts +188 -0
- package/dist/modules/credential_policy.d.ts.map +1 -0
- package/dist/modules/credential_policy.js +1452 -0
- package/dist/modules/credential_policy.js.map +1 -0
- package/dist/modules/credential_runtime.d.ts +42 -0
- package/dist/modules/credential_runtime.d.ts.map +1 -0
- package/dist/modules/credential_runtime.js +148 -0
- package/dist/modules/credential_runtime.js.map +1 -0
- package/dist/modules/credential_session_cache.d.ts +36 -0
- package/dist/modules/credential_session_cache.d.ts.map +1 -0
- package/dist/modules/credential_session_cache.js +106 -0
- package/dist/modules/credential_session_cache.js.map +1 -0
- package/dist/modules/credit_runtime.d.ts +412 -0
- package/dist/modules/credit_runtime.d.ts.map +1 -0
- package/dist/modules/credit_runtime.js +2866 -0
- package/dist/modules/credit_runtime.js.map +1 -0
- package/dist/modules/crypto/browser_provider.d.ts +15 -0
- package/dist/modules/crypto/browser_provider.d.ts.map +1 -0
- package/dist/modules/crypto/browser_provider.js +113 -0
- package/dist/modules/crypto/browser_provider.js.map +1 -0
- package/dist/modules/crypto/index.d.ts +9 -0
- package/dist/modules/crypto/index.d.ts.map +1 -0
- package/dist/modules/crypto/index.js +44 -0
- package/dist/modules/crypto/index.js.map +1 -0
- package/dist/modules/crypto/node_provider.d.ts +15 -0
- package/dist/modules/crypto/node_provider.d.ts.map +1 -0
- package/dist/modules/crypto/node_provider.js +74 -0
- package/dist/modules/crypto/node_provider.js.map +1 -0
- package/dist/modules/crypto/provider.d.ts +34 -0
- package/dist/modules/crypto/provider.d.ts.map +1 -0
- package/dist/modules/crypto/provider.js +3 -0
- package/dist/modules/crypto/provider.js.map +1 -0
- package/dist/modules/crypto/pure_ripemd160.d.ts +8 -0
- package/dist/modules/crypto/pure_ripemd160.d.ts.map +1 -0
- package/dist/modules/crypto/pure_ripemd160.js +142 -0
- package/dist/modules/crypto/pure_ripemd160.js.map +1 -0
- package/dist/modules/crypto/pure_scrypt.d.ts +23 -0
- package/dist/modules/crypto/pure_scrypt.d.ts.map +1 -0
- package/dist/modules/crypto/pure_scrypt.js +161 -0
- package/dist/modules/crypto/pure_scrypt.js.map +1 -0
- package/dist/modules/crypto/pure_secp256k1.d.ts +29 -0
- package/dist/modules/crypto/pure_secp256k1.d.ts.map +1 -0
- package/dist/modules/crypto/pure_secp256k1.js +195 -0
- package/dist/modules/crypto/pure_secp256k1.js.map +1 -0
- package/dist/modules/crypto/sync.d.ts +13 -0
- package/dist/modules/crypto/sync.d.ts.map +1 -0
- package/dist/modules/crypto/sync.js +37 -0
- package/dist/modules/crypto/sync.js.map +1 -0
- package/dist/modules/dexbot_class.d.ts +1074 -0
- package/dist/modules/dexbot_class.d.ts.map +1 -0
- package/dist/modules/dexbot_class.js +4613 -0
- package/dist/modules/dexbot_class.js.map +1 -0
- package/dist/modules/dexbot_credential_client.d.ts +71 -0
- package/dist/modules/dexbot_credential_client.d.ts.map +1 -0
- package/dist/modules/dexbot_credential_client.js +224 -0
- package/dist/modules/dexbot_credential_client.js.map +1 -0
- package/dist/modules/dexbot_fill_runtime.d.ts +173 -0
- package/dist/modules/dexbot_fill_runtime.d.ts.map +1 -0
- package/dist/modules/dexbot_fill_runtime.js +217 -0
- package/dist/modules/dexbot_fill_runtime.js.map +1 -0
- package/dist/modules/dexbot_maintenance_runtime.d.ts +279 -0
- package/dist/modules/dexbot_maintenance_runtime.d.ts.map +1 -0
- package/dist/modules/dexbot_maintenance_runtime.js +1613 -0
- package/dist/modules/dexbot_maintenance_runtime.js.map +1 -0
- package/dist/modules/env.d.ts +12 -0
- package/dist/modules/env.d.ts.map +1 -0
- package/dist/modules/env.js +57 -0
- package/dist/modules/env.js.map +1 -0
- package/dist/modules/fund_registry.d.ts +96 -0
- package/dist/modules/fund_registry.d.ts.map +1 -0
- package/dist/modules/fund_registry.js +261 -0
- package/dist/modules/fund_registry.js.map +1 -0
- package/dist/modules/general_settings.d.ts +36 -0
- package/dist/modules/general_settings.d.ts.map +1 -0
- package/dist/modules/general_settings.js +63 -0
- package/dist/modules/general_settings.js.map +1 -0
- package/dist/modules/graceful_shutdown.d.ts +86 -0
- package/dist/modules/graceful_shutdown.d.ts.map +1 -0
- package/dist/modules/graceful_shutdown.js +164 -0
- package/dist/modules/graceful_shutdown.js.map +1 -0
- package/dist/modules/key_store.d.ts +60 -0
- package/dist/modules/key_store.d.ts.map +1 -0
- package/dist/modules/key_store.js +215 -0
- package/dist/modules/key_store.js.map +1 -0
- package/dist/modules/launcher/bot_supervisor.d.ts +84 -0
- package/dist/modules/launcher/bot_supervisor.d.ts.map +1 -0
- package/dist/modules/launcher/bot_supervisor.js +1067 -0
- package/dist/modules/launcher/bot_supervisor.js.map +1 -0
- package/dist/modules/launcher/child_env.d.ts +9 -0
- package/dist/modules/launcher/child_env.d.ts.map +1 -0
- package/dist/modules/launcher/child_env.js +78 -0
- package/dist/modules/launcher/child_env.js.map +1 -0
- package/dist/modules/launcher/credential_bootstrap.d.ts +22 -0
- package/dist/modules/launcher/credential_bootstrap.d.ts.map +1 -0
- package/dist/modules/launcher/credential_bootstrap.js +303 -0
- package/dist/modules/launcher/credential_bootstrap.js.map +1 -0
- package/dist/modules/launcher/credential_daemon.d.ts +32 -0
- package/dist/modules/launcher/credential_daemon.d.ts.map +1 -0
- package/dist/modules/launcher/credential_daemon.js +173 -0
- package/dist/modules/launcher/credential_daemon.js.map +1 -0
- package/dist/modules/launcher/credential_secret.d.ts +6 -0
- package/dist/modules/launcher/credential_secret.d.ts.map +1 -0
- package/dist/modules/launcher/credential_secret.js +15 -0
- package/dist/modules/launcher/credential_secret.js.map +1 -0
- package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -0
- package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +1 -0
- package/dist/modules/launcher/foreign_cred_daemon.js +166 -0
- package/dist/modules/launcher/foreign_cred_daemon.js.map +1 -0
- package/dist/modules/launcher/headless_password.d.ts +8 -0
- package/dist/modules/launcher/headless_password.d.ts.map +1 -0
- package/dist/modules/launcher/headless_password.js +33 -0
- package/dist/modules/launcher/headless_password.js.map +1 -0
- package/dist/modules/launcher/launch_modes.d.ts +36 -0
- package/dist/modules/launcher/launch_modes.d.ts.map +1 -0
- package/dist/modules/launcher/launch_modes.js +129 -0
- package/dist/modules/launcher/launch_modes.js.map +1 -0
- package/dist/modules/launcher/market_adapter_runtime.d.ts +43 -0
- package/dist/modules/launcher/market_adapter_runtime.d.ts.map +1 -0
- package/dist/modules/launcher/market_adapter_runtime.js +217 -0
- package/dist/modules/launcher/market_adapter_runtime.js.map +1 -0
- package/dist/modules/launcher/market_adapter_watchdog.d.ts +26 -0
- package/dist/modules/launcher/market_adapter_watchdog.d.ts.map +1 -0
- package/dist/modules/launcher/market_adapter_watchdog.js +214 -0
- package/dist/modules/launcher/market_adapter_watchdog.js.map +1 -0
- package/dist/modules/launcher/monolithic_runtime.d.ts +89 -0
- package/dist/modules/launcher/monolithic_runtime.d.ts.map +1 -0
- package/dist/modules/launcher/monolithic_runtime.js +425 -0
- package/dist/modules/launcher/monolithic_runtime.js.map +1 -0
- package/dist/modules/launcher/runtime_entry.d.ts +26 -0
- package/dist/modules/launcher/runtime_entry.d.ts.map +1 -0
- package/dist/modules/launcher/runtime_entry.js +49 -0
- package/dist/modules/launcher/runtime_entry.js.map +1 -0
- package/dist/modules/launcher/status_reporting.d.ts +48 -0
- package/dist/modules/launcher/status_reporting.d.ts.map +1 -0
- package/dist/modules/launcher/status_reporting.js +113 -0
- package/dist/modules/launcher/status_reporting.js.map +1 -0
- package/dist/modules/launcher/supervisor_control.d.ts +6 -0
- package/dist/modules/launcher/supervisor_control.d.ts.map +1 -0
- package/dist/modules/launcher/supervisor_control.js +59 -0
- package/dist/modules/launcher/supervisor_control.js.map +1 -0
- package/dist/modules/logger.d.ts +2 -0
- package/dist/modules/logger.d.ts.map +1 -0
- package/dist/modules/logger.js +71 -0
- package/dist/modules/logger.js.map +1 -0
- package/dist/modules/market_adapter_whitelist.d.ts +22 -0
- package/dist/modules/market_adapter_whitelist.d.ts.map +1 -0
- package/dist/modules/market_adapter_whitelist.js +82 -0
- package/dist/modules/market_adapter_whitelist.js.map +1 -0
- package/dist/modules/node_health_cache.d.ts +55 -0
- package/dist/modules/node_health_cache.d.ts.map +1 -0
- package/dist/modules/node_health_cache.js +134 -0
- package/dist/modules/node_health_cache.js.map +1 -0
- package/dist/modules/node_manager.d.ts +215 -0
- package/dist/modules/node_manager.d.ts.map +1 -0
- package/dist/modules/node_manager.js +628 -0
- package/dist/modules/node_manager.js.map +1 -0
- package/dist/modules/order/accounting.d.ts +349 -0
- package/dist/modules/order/accounting.d.ts.map +1 -0
- package/dist/modules/order/accounting.js +1191 -0
- package/dist/modules/order/accounting.js.map +1 -0
- package/dist/modules/order/async_lock.d.ts +126 -0
- package/dist/modules/order/async_lock.d.ts.map +1 -0
- package/dist/modules/order/async_lock.js +195 -0
- package/dist/modules/order/async_lock.js.map +1 -0
- package/dist/modules/order/export.d.ts +129 -0
- package/dist/modules/order/export.d.ts.map +1 -0
- package/dist/modules/order/export.js +316 -0
- package/dist/modules/order/export.js.map +1 -0
- package/dist/modules/order/format.d.ts +158 -0
- package/dist/modules/order/format.d.ts.map +1 -0
- package/dist/modules/order/format.js +232 -0
- package/dist/modules/order/format.js.map +1 -0
- package/dist/modules/order/grid.d.ts +549 -0
- package/dist/modules/order/grid.d.ts.map +1 -0
- package/dist/modules/order/grid.js +1746 -0
- package/dist/modules/order/grid.js.map +1 -0
- package/dist/modules/order/grid_reconcile.d.ts +154 -0
- package/dist/modules/order/grid_reconcile.d.ts.map +1 -0
- package/dist/modules/order/grid_reconcile.js +1192 -0
- package/dist/modules/order/grid_reconcile.js.map +1 -0
- package/dist/modules/order/index.d.ts +55 -0
- package/dist/modules/order/index.d.ts.map +1 -0
- package/dist/modules/order/index.js +79 -0
- package/dist/modules/order/index.js.map +1 -0
- package/dist/modules/order/logger.d.ts +136 -0
- package/dist/modules/order/logger.d.ts.map +1 -0
- package/dist/modules/order/logger.js +614 -0
- package/dist/modules/order/logger.js.map +1 -0
- package/dist/modules/order/logger_state.d.ts +133 -0
- package/dist/modules/order/logger_state.d.ts.map +1 -0
- package/dist/modules/order/logger_state.js +170 -0
- package/dist/modules/order/logger_state.js.map +1 -0
- package/dist/modules/order/manager.d.ts +413 -0
- package/dist/modules/order/manager.d.ts.map +1 -0
- package/dist/modules/order/manager.js +1605 -0
- package/dist/modules/order/manager.js.map +1 -0
- package/dist/modules/order/processed_fill_store.d.ts +135 -0
- package/dist/modules/order/processed_fill_store.d.ts.map +1 -0
- package/dist/modules/order/processed_fill_store.js +288 -0
- package/dist/modules/order/processed_fill_store.js.map +1 -0
- package/dist/modules/order/runner.d.ts +70 -0
- package/dist/modules/order/runner.d.ts.map +1 -0
- package/dist/modules/order/runner.js +140 -0
- package/dist/modules/order/runner.js.map +1 -0
- package/dist/modules/order/strategy.d.ts +196 -0
- package/dist/modules/order/strategy.d.ts.map +1 -0
- package/dist/modules/order/strategy.js +398 -0
- package/dist/modules/order/strategy.js.map +1 -0
- package/dist/modules/order/sync_engine.d.ts +386 -0
- package/dist/modules/order/sync_engine.d.ts.map +1 -0
- package/dist/modules/order/sync_engine.js +1459 -0
- package/dist/modules/order/sync_engine.js.map +1 -0
- package/dist/modules/order/utils/math.d.ts +677 -0
- package/dist/modules/order/utils/math.d.ts.map +1 -0
- package/dist/modules/order/utils/math.js +1172 -0
- package/dist/modules/order/utils/math.js.map +1 -0
- package/dist/modules/order/utils/order.d.ts +572 -0
- package/dist/modules/order/utils/order.d.ts.map +1 -0
- package/dist/modules/order/utils/order.js +1145 -0
- package/dist/modules/order/utils/order.js.map +1 -0
- package/dist/modules/order/utils/system.d.ts +268 -0
- package/dist/modules/order/utils/system.d.ts.map +1 -0
- package/dist/modules/order/utils/system.js +1261 -0
- package/dist/modules/order/utils/system.js.map +1 -0
- package/dist/modules/order/utils/validate.d.ts +280 -0
- package/dist/modules/order/utils/validate.d.ts.map +1 -0
- package/dist/modules/order/utils/validate.js +918 -0
- package/dist/modules/order/utils/validate.js.map +1 -0
- package/dist/modules/order/working_grid.d.ts +212 -0
- package/dist/modules/order/working_grid.d.ts.map +1 -0
- package/dist/modules/order/working_grid.js +279 -0
- package/dist/modules/order/working_grid.js.map +1 -0
- package/dist/modules/path_api.d.ts +32 -0
- package/dist/modules/path_api.d.ts.map +1 -0
- package/dist/modules/path_api.js +148 -0
- package/dist/modules/path_api.js.map +1 -0
- package/dist/modules/paths.d.ts +58 -0
- package/dist/modules/paths.d.ts.map +1 -0
- package/dist/modules/paths.js +82 -0
- package/dist/modules/paths.js.map +1 -0
- package/dist/modules/process_discovery.d.ts +58 -0
- package/dist/modules/process_discovery.d.ts.map +1 -0
- package/dist/modules/process_discovery.js +265 -0
- package/dist/modules/process_discovery.js.map +1 -0
- package/dist/modules/runtime.d.ts +34 -0
- package/dist/modules/runtime.d.ts.map +1 -0
- package/dist/modules/runtime.js +98 -0
- package/dist/modules/runtime.js.map +1 -0
- package/dist/modules/runtime_settings.d.ts +12 -0
- package/dist/modules/runtime_settings.d.ts.map +1 -0
- package/dist/modules/runtime_settings.js +122 -0
- package/dist/modules/runtime_settings.js.map +1 -0
- package/dist/modules/settings_merge.d.ts +38 -0
- package/dist/modules/settings_merge.d.ts.map +1 -0
- package/dist/modules/settings_merge.js +246 -0
- package/dist/modules/settings_merge.js.map +1 -0
- package/dist/modules/storage/browser_adapter.d.ts +56 -0
- package/dist/modules/storage/browser_adapter.d.ts.map +1 -0
- package/dist/modules/storage/browser_adapter.js +231 -0
- package/dist/modules/storage/browser_adapter.js.map +1 -0
- package/dist/modules/storage/index.d.ts +28 -0
- package/dist/modules/storage/index.d.ts.map +1 -0
- package/dist/modules/storage/index.js +52 -0
- package/dist/modules/storage/index.js.map +1 -0
- package/dist/modules/storage/node_adapter.d.ts +49 -0
- package/dist/modules/storage/node_adapter.d.ts.map +1 -0
- package/dist/modules/storage/node_adapter.js +167 -0
- package/dist/modules/storage/node_adapter.js.map +1 -0
- package/dist/modules/storage/types.d.ts +92 -0
- package/dist/modules/storage/types.d.ts.map +1 -0
- package/dist/modules/storage/types.js +3 -0
- package/dist/modules/storage/types.js.map +1 -0
- package/dist/modules/types.d.ts +1382 -0
- package/dist/modules/types.d.ts.map +1 -0
- package/dist/modules/types.js +11 -0
- package/dist/modules/types.js.map +1 -0
- package/dist/modules/utils/base58check.d.ts +12 -0
- package/dist/modules/utils/base58check.d.ts.map +1 -0
- package/dist/modules/utils/base58check.js +112 -0
- package/dist/modules/utils/base58check.js.map +1 -0
- package/dist/modules/utils/build_dir.d.ts +7 -0
- package/dist/modules/utils/build_dir.d.ts.map +1 -0
- package/dist/modules/utils/build_dir.js +8 -0
- package/dist/modules/utils/build_dir.js.map +1 -0
- package/dist/modules/utils/fs_utils.d.ts +25 -0
- package/dist/modules/utils/fs_utils.d.ts.map +1 -0
- package/dist/modules/utils/fs_utils.js +27 -0
- package/dist/modules/utils/fs_utils.js.map +1 -0
- package/dist/modules/utils/math_utils.d.ts +10 -0
- package/dist/modules/utils/math_utils.d.ts.map +1 -0
- package/dist/modules/utils/math_utils.js +17 -0
- package/dist/modules/utils/math_utils.js.map +1 -0
- package/dist/modules/validate_profiles.d.ts +37 -0
- package/dist/modules/validate_profiles.d.ts.map +1 -0
- package/dist/modules/validate_profiles.js +369 -0
- package/dist/modules/validate_profiles.js.map +1 -0
- package/dist/pm2.d.ts +167 -0
- package/dist/pm2.d.ts.map +1 -0
- package/dist/pm2.js +998 -0
- package/dist/pm2.js.map +1 -0
- package/dist/scripts/analyze-git.d.ts +11 -0
- package/dist/scripts/analyze-git.d.ts.map +1 -0
- package/dist/scripts/analyze-git.js +851 -0
- package/dist/scripts/analyze-git.js.map +1 -0
- package/dist/scripts/analyze-orders.d.ts +17 -0
- package/dist/scripts/analyze-orders.d.ts.map +1 -0
- package/dist/scripts/analyze-orders.js +1568 -0
- package/dist/scripts/analyze-orders.js.map +1 -0
- package/dist/scripts/diagnose-kibana-candles.d.ts +3 -0
- package/dist/scripts/diagnose-kibana-candles.d.ts.map +1 -0
- package/dist/scripts/diagnose-kibana-candles.js +82 -0
- package/dist/scripts/diagnose-kibana-candles.js.map +1 -0
- package/dist/scripts/diagnose-pool-history.d.ts +3 -0
- package/dist/scripts/diagnose-pool-history.d.ts.map +1 -0
- package/dist/scripts/diagnose-pool-history.js +296 -0
- package/dist/scripts/diagnose-pool-history.js.map +1 -0
- package/dist/scripts/divergence-calc.d.ts +26 -0
- package/dist/scripts/divergence-calc.d.ts.map +1 -0
- package/dist/scripts/divergence-calc.js +119 -0
- package/dist/scripts/divergence-calc.js.map +1 -0
- package/dist/scripts/generate_lp_chart.d.ts +31 -0
- package/dist/scripts/generate_lp_chart.d.ts.map +1 -0
- package/dist/scripts/generate_lp_chart.js +92 -0
- package/dist/scripts/generate_lp_chart.js.map +1 -0
- package/dist/scripts/generate_mainnet_corpus_report.d.ts +24 -0
- package/dist/scripts/generate_mainnet_corpus_report.d.ts.map +1 -0
- package/dist/scripts/generate_mainnet_corpus_report.js +237 -0
- package/dist/scripts/generate_mainnet_corpus_report.js.map +1 -0
- package/dist/scripts/generate_market_adapter_whitelist.d.ts +2 -0
- package/dist/scripts/generate_market_adapter_whitelist.d.ts.map +1 -0
- package/dist/scripts/generate_market_adapter_whitelist.js +111 -0
- package/dist/scripts/generate_market_adapter_whitelist.js.map +1 -0
- package/dist/scripts/migrate_bot_keys.d.ts +6 -0
- package/dist/scripts/migrate_bot_keys.d.ts.map +1 -0
- package/dist/scripts/migrate_bot_keys.js +301 -0
- package/dist/scripts/migrate_bot_keys.js.map +1 -0
- package/dist/scripts/native_release_gates.d.ts +3 -0
- package/dist/scripts/native_release_gates.d.ts.map +1 -0
- package/dist/scripts/native_release_gates.js +52 -0
- package/dist/scripts/native_release_gates.js.map +1 -0
- package/dist/scripts/print_grid.d.ts +16 -0
- package/dist/scripts/print_grid.d.ts.map +1 -0
- package/dist/scripts/print_grid.js +80 -0
- package/dist/scripts/print_grid.js.map +1 -0
- package/dist/scripts/run-tests.d.ts +2 -0
- package/dist/scripts/run-tests.d.ts.map +1 -0
- package/dist/scripts/run-tests.js +49 -0
- package/dist/scripts/run-tests.js.map +1 -0
- package/dist/scripts/sync-version.d.ts +14 -0
- package/dist/scripts/sync-version.d.ts.map +1 -0
- package/dist/scripts/sync-version.js +158 -0
- package/dist/scripts/sync-version.js.map +1 -0
- package/dist/scripts/test-credit-renewal.d.ts +2 -0
- package/dist/scripts/test-credit-renewal.d.ts.map +1 -0
- package/dist/scripts/test-credit-renewal.js +329 -0
- package/dist/scripts/test-credit-renewal.js.map +1 -0
- package/dist/scripts/update.d.ts +24 -0
- package/dist/scripts/update.d.ts.map +1 -0
- package/dist/scripts/update.js +650 -0
- package/dist/scripts/update.js.map +1 -0
- package/dist/scripts/validate_bots.d.ts +16 -0
- package/dist/scripts/validate_bots.d.ts.map +1 -0
- package/dist/scripts/validate_bots.js +106 -0
- package/dist/scripts/validate_bots.js.map +1 -0
- package/dist/scripts/verify-browser-bundle.d.ts +22 -0
- package/dist/scripts/verify-browser-bundle.d.ts.map +1 -0
- package/dist/scripts/verify-browser-bundle.js +339 -0
- package/dist/scripts/verify-browser-bundle.js.map +1 -0
- package/dist/unlock.d.ts +48 -0
- package/dist/unlock.d.ts.map +1 -0
- package/dist/unlock.js +925 -0
- package/dist/unlock.js.map +1 -0
- package/package.json +112 -0
- package/scripts/README.md +356 -0
- package/scripts/clear-all.sh +195 -0
- package/scripts/clear-logs.sh +95 -0
- package/scripts/clear-market-adapter.sh +196 -0
- package/scripts/clear-orders.sh +113 -0
- package/scripts/create-bot-symlinks.sh +51 -0
- package/scripts/postinstall.js +9 -0
- 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
|