dexbot 1.6.11 → 1.6.12
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/CHANGELOG.md +35 -4
- package/README.md +2 -1
- package/analysis/README.md +2 -0
- package/analysis/tradingview/README.md +1 -1
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
- package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
- package/claw/modules/chain_broadcast.ts +7 -1
- package/claw/modules/claw_launcher.ts +1 -1
- package/claw/modules/launcher_mode_detector.ts +9 -2
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/account_resolver.d.ts +1 -1
- package/dist/analysis/account_resolver.js +2 -1
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -7
- package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
- package/dist/analysis/ama_fitting/fetch_lp_candles.js +4 -4
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +20 -4
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +9 -6
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js +16 -12
- package/dist/analysis/analyze_args.d.ts +31 -0
- package/dist/analysis/analyze_args.js +41 -0
- package/dist/analysis/analyze_dynamic_weight.js +7 -17
- package/dist/analysis/analyze_kalman.js +7 -17
- package/dist/analysis/analyze_regime.js +7 -17
- package/dist/analysis/analyze_regime_windows.js +8 -18
- package/dist/analysis/analyze_risk_profile.js +8 -18
- package/dist/analysis/analyze_trade_heatmap.js +7 -17
- package/dist/analysis/analyze_volatility.js +7 -17
- package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +220 -12
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js +6 -5
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +11 -63
- package/dist/analysis/bot_fitting/shared_utils.d.ts +7 -7
- package/dist/analysis/bot_fitting/shared_utils.js +2 -2
- package/dist/analysis/bot_key_utils.d.ts +18 -10
- package/dist/analysis/bot_key_utils.js +7 -4
- package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
- package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
- package/dist/analysis/chain_pool.d.ts +3 -1
- package/dist/analysis/chart_ui.d.ts +5 -2
- package/dist/analysis/chart_ui.js +6 -3
- package/dist/analysis/chart_utils.d.ts +5 -5
- package/dist/analysis/chart_utils.js +9 -0
- package/dist/analysis/fills_cache.d.ts +1 -1
- package/dist/analysis/fills_source.d.ts +2 -2
- package/dist/analysis/fills_source.js +14 -12
- package/dist/analysis/grid_correction_check.d.ts +1 -1
- package/dist/analysis/grid_correction_check.js +12 -11
- package/dist/analysis/math_utils.d.ts +7 -6
- package/dist/analysis/math_utils.js +5 -8
- package/dist/analysis/pnl_report.js +29 -29
- package/dist/analysis/price_sources.d.ts +8 -8
- package/dist/analysis/price_sources.js +5 -4
- package/dist/analysis/resolve_bot_accounts.js +2 -2
- package/dist/analysis/resolve_source.d.ts +1 -1
- package/dist/analysis/trade_profitability.d.ts +23 -2
- package/dist/analysis/trade_profitability.js +50 -50
- package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
- package/dist/analysis/tradingview/analyze_tradingview.js +6 -5
- package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
- package/dist/analysis/tradingview/grid_reset_config.js +23 -11
- package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
- package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +18 -19
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -1
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +5 -5
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +5 -4
- package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
- package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
- package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
- package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
- package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
- package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
- package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
- package/dist/credential-daemon.js +34 -20
- package/dist/dexbot.js +11 -11
- package/dist/market_adapter/candle_utils.d.ts +22 -18
- package/dist/market_adapter/candle_utils.js +24 -20
- package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
- package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
- package/dist/market_adapter/core/kibana_candles.d.ts +53 -18
- package/dist/market_adapter/core/kibana_candles.js +9 -7
- package/dist/market_adapter/core/kibana_client.d.ts +9 -1
- package/dist/market_adapter/core/kibana_client.js +8 -7
- package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
- package/dist/market_adapter/core/market_adapter_service.d.ts +284 -117
- package/dist/market_adapter/core/market_adapter_service.js +137 -113
- package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
- package/dist/market_adapter/core/strategies/ama.js +2 -4
- package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
- package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
- package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
- package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
- package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
- package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
- package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
- package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
- package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
- package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
- package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
- package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
- package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
- package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
- package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
- package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
- package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +96 -224
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +42 -7
- package/dist/market_adapter/inputs/fetch_lp_data.js +22 -15
- package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
- package/dist/market_adapter/inputs/kibana_feed_source.js +29 -22
- package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
- package/dist/market_adapter/inputs/kibana_source.js +2 -2
- package/dist/market_adapter/inputs/window_cache.d.ts +99 -94
- package/dist/market_adapter/inputs/window_cache.js +8 -8
- package/dist/market_adapter/interval_utils.d.ts +4 -4
- package/dist/market_adapter/log_format.d.ts +6 -6
- package/dist/market_adapter/log_format.js +28 -21
- package/dist/market_adapter/lp_chart_core.d.ts +22 -1
- package/dist/market_adapter/lp_chart_core.js +26 -192
- package/dist/market_adapter/lp_chart_runner.d.ts +7 -7
- package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
- package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
- package/dist/market_adapter/market_adapter.d.ts +94 -32
- package/dist/market_adapter/market_adapter.js +67 -48
- package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
- package/dist/market_adapter/utils/adapter_client.js +2 -2
- package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
- package/dist/market_adapter/utils/chain.d.ts +50 -41
- package/dist/market_adapter/utils/chain.js +40 -46
- package/dist/market_adapter/utils/data_discovery.d.ts +4 -1
- package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
- package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
- package/dist/market_adapter/utils/file_lock.d.ts +28 -14
- package/dist/market_adapter/utils/file_lock.js +36 -32
- package/dist/market_adapter/utils/native_history.d.ts +9 -2
- package/dist/market_adapter/utils/native_history.js +35 -28
- package/dist/modules/account_bots.d.ts +577 -21
- package/dist/modules/account_bots.js +182 -158
- package/dist/modules/account_orders.d.ts +66 -30
- package/dist/modules/account_orders.js +22 -20
- package/dist/modules/authority_resolver.d.ts +12 -2
- package/dist/modules/authority_resolver.js +15 -8
- package/dist/modules/bitshares-native/chain_client.d.ts +38 -3
- package/dist/modules/bitshares-native/chain_client.js +45 -46
- package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
- package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
- package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
- package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
- package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
- package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
- package/dist/modules/bitshares-native/index.d.ts +1 -1
- package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
- package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
- package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
- package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
- package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
- package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
- package/dist/modules/bitshares-native/serial/serializer.js +7 -13
- package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
- package/dist/modules/bitshares-native/serial/types.js +55 -62
- package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
- package/dist/modules/bitshares-native/signing_client.js +19 -14
- package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
- package/dist/modules/bitshares-native/subscriptions.js +12 -12
- package/dist/modules/bitshares-native/transport.d.ts +5 -4
- package/dist/modules/bitshares-native/transport.js +5 -4
- package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
- package/dist/modules/bitshares-native/tx/builder.js +4 -3
- package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
- package/dist/modules/bitshares_client.d.ts +45 -13
- package/dist/modules/bitshares_client.js +28 -19
- package/dist/modules/bot_defaults.d.ts +6 -15
- package/dist/modules/bot_defaults.js +1 -5
- package/dist/modules/bot_settings.d.ts +44 -10
- package/dist/modules/bot_settings.js +11 -8
- package/dist/modules/bots_file_lock.d.ts +6 -6
- package/dist/modules/bots_file_lock.js +16 -12
- package/dist/modules/broadcast_failure.d.ts +2 -2
- package/dist/modules/broadcast_failure.js +5 -4
- package/dist/modules/chain_keys.d.ts +42 -40
- package/dist/modules/chain_keys.js +53 -45
- package/dist/modules/chain_orders.d.ts +93 -59
- package/dist/modules/chain_orders.js +31 -23
- package/dist/modules/constants.d.ts +527 -31
- package/dist/modules/constants.js +15 -47
- package/dist/modules/cr_planner.d.ts +40 -2
- package/dist/modules/credential_policy.d.ts +68 -8
- package/dist/modules/credential_policy.js +37 -31
- package/dist/modules/credential_session_cache.d.ts +2 -2
- package/dist/modules/credit_pricing.d.ts +42 -6
- package/dist/modules/credit_pricing.js +44 -30
- package/dist/modules/credit_runtime.d.ts +276 -118
- package/dist/modules/credit_runtime.js +462 -165
- package/dist/modules/crypto/browser_provider.js +6 -4
- package/dist/modules/crypto/node_provider.js +1 -1
- package/dist/modules/crypto/pure_scrypt.js +35 -4
- package/dist/modules/crypto/pure_secp256k1.js +72 -26
- package/dist/modules/crypto/sync.d.ts +9 -9
- package/dist/modules/crypto/sync.js +16 -9
- package/dist/modules/dexbot_class.d.ts +195 -139
- package/dist/modules/dexbot_class.js +78 -28
- package/dist/modules/dexbot_cow_runtime.d.ts +167 -87
- package/dist/modules/dexbot_cow_runtime.js +248 -206
- package/dist/modules/dexbot_credential_client.d.ts +19 -11
- package/dist/modules/dexbot_fill_runtime.d.ts +63 -48
- package/dist/modules/dexbot_fill_runtime.js +48 -41
- package/dist/modules/dexbot_maintenance_runtime.d.ts +109 -70
- package/dist/modules/dexbot_maintenance_runtime.js +108 -83
- package/dist/modules/dexbot_startup_runtime.d.ts +11 -10
- package/dist/modules/dexbot_startup_runtime.js +43 -43
- package/dist/modules/dexbot_state_recovery.d.ts +13 -12
- package/dist/modules/dexbot_state_recovery.js +18 -13
- package/dist/modules/fund_registry.d.ts +4 -2
- package/dist/modules/fund_registry.js +10 -10
- package/dist/modules/general_settings.d.ts +30 -4
- package/dist/modules/graceful_shutdown.d.ts +3 -3
- package/dist/modules/graceful_shutdown.js +2 -2
- package/dist/modules/grid_price_source.d.ts +1 -1
- package/dist/modules/key_store.d.ts +14 -8
- package/dist/modules/key_store.js +7 -6
- package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
- package/dist/modules/launcher/adapter_requirement.js +5 -5
- package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
- package/dist/modules/launcher/bot_supervisor.js +12 -11
- package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
- package/dist/modules/launcher/credential_bootstrap.js +1 -1
- package/dist/modules/launcher/credential_daemon.d.ts +4 -4
- package/dist/modules/launcher/credential_daemon.js +2 -2
- package/dist/modules/launcher/credential_secret.d.ts +1 -1
- package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
- package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
- package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
- package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
- package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
- package/dist/modules/launcher/status_reporting.d.ts +22 -14
- package/dist/modules/launcher/supervisor_control.d.ts +8 -1
- package/dist/modules/launcher/supervisor_control.js +4 -2
- package/dist/modules/market_adapter_whitelist.d.ts +9 -3
- package/dist/modules/market_adapter_whitelist.js +15 -3
- package/dist/modules/node_manager.d.ts +41 -11
- package/dist/modules/node_manager.js +5 -4
- package/dist/modules/order/accounting.d.ts +53 -24
- package/dist/modules/order/accounting.js +16 -15
- package/dist/modules/order/async_lock.d.ts +5 -2
- package/dist/modules/order/async_lock.js +1 -1
- package/dist/modules/order/export.d.ts +7 -6
- package/dist/modules/order/export.js +1 -7
- package/dist/modules/order/format.d.ts +4 -4
- package/dist/modules/order/genesis_policy.d.ts +21 -18
- package/dist/modules/order/genesis_policy.js +12 -8
- package/dist/modules/order/grid.d.ts +142 -36
- package/dist/modules/order/grid.js +148 -123
- package/dist/modules/order/grid_reconcile.d.ts +21 -20
- package/dist/modules/order/grid_reconcile.js +13 -12
- package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
- package/dist/modules/order/grid_reconcile_internal.js +28 -19
- package/dist/modules/order/index.d.ts +263 -1
- package/dist/modules/order/logger.d.ts +45 -11
- package/dist/modules/order/logger.js +38 -40
- package/dist/modules/order/logger_state.d.ts +4 -4
- package/dist/modules/order/manager.d.ts +225 -180
- package/dist/modules/order/manager.js +80 -83
- package/dist/modules/order/processed_fill_store.d.ts +18 -3
- package/dist/modules/order/processed_fill_store.js +16 -27
- package/dist/modules/order/strategy.d.ts +21 -13
- package/dist/modules/order/strategy.js +5 -6
- package/dist/modules/order/sync_engine.d.ts +91 -33
- package/dist/modules/order/sync_engine.js +84 -53
- package/dist/modules/order/utils/math.d.ts +157 -102
- package/dist/modules/order/utils/math.js +77 -38
- package/dist/modules/order/utils/order.d.ts +310 -110
- package/dist/modules/order/utils/order.js +122 -99
- package/dist/modules/order/utils/slot.d.ts +1 -1
- package/dist/modules/order/utils/system.d.ts +176 -26
- package/dist/modules/order/utils/system.js +86 -69
- package/dist/modules/order/utils/validate.d.ts +89 -41
- package/dist/modules/order/utils/validate.js +24 -22
- package/dist/modules/order/utils/withPoolRef.d.ts +4 -3
- package/dist/modules/order/utils/withPoolRef.js +18 -12
- package/dist/modules/order/working_grid.d.ts +14 -13
- package/dist/modules/paths.d.ts +1 -4
- package/dist/modules/paths.js +1 -27
- package/dist/modules/process_discovery.d.ts +1 -1
- package/dist/modules/process_discovery.js +2 -1
- package/dist/modules/runtime.d.ts +7 -3
- package/dist/modules/runtime.js +4 -3
- package/dist/modules/runtime_settings.d.ts +15 -10
- package/dist/modules/runtime_settings.js +30 -24
- package/dist/modules/settings_merge.d.ts +29 -3
- package/dist/modules/settings_merge.js +56 -78
- package/dist/modules/socket_json_client.d.ts +7 -4
- package/dist/modules/storage/browser_adapter.d.ts +38 -53
- package/dist/modules/storage/browser_adapter.js +7 -30
- package/dist/modules/storage/index.d.ts +1 -1
- package/dist/modules/storage/node_adapter.d.ts +45 -27
- package/dist/modules/storage/node_adapter.js +9 -9
- package/dist/modules/storage/types.d.ts +5 -4
- package/dist/modules/types.d.ts +1071 -2
- package/dist/modules/types.js +4 -1
- package/dist/modules/utils/asset_symbols.d.ts +2 -1
- package/dist/modules/utils/asset_symbols.js +2 -1
- package/dist/modules/utils/errors.d.ts +9 -0
- package/dist/modules/utils/errors.js +23 -1
- package/dist/modules/utils/time_range.d.ts +1 -12
- package/dist/modules/utils/time_range.js +1 -1
- package/dist/modules/validate_profiles.js +53 -43
- package/dist/modules/version_notice.d.ts +14 -3
- package/dist/modules/version_notice.js +6 -4
- package/dist/pm2.d.ts +29 -27
- package/dist/pm2.js +5 -5
- package/dist/scripts/analyze-credit.d.ts +2 -1
- package/dist/scripts/analyze-credit.js +23 -24
- package/dist/scripts/analyze-orders.d.ts +77 -9
- package/dist/scripts/analyze-orders.js +65 -40
- package/dist/scripts/chart_command.d.ts +27 -18
- package/dist/scripts/chart_command.js +13 -11
- package/dist/scripts/check_any.d.ts +18 -0
- package/dist/scripts/check_any.js +126 -0
- package/dist/scripts/diagnose-pool-history.js +12 -7
- package/dist/scripts/print_grid.js +0 -1
- package/dist/scripts/run-tests.js +39 -7
- package/dist/scripts/runner.js +1 -1
- package/dist/scripts/test-credit-renewal.js +30 -21
- package/dist/scripts/update.d.ts +10 -5
- package/dist/scripts/update.js +168 -103
- package/dist/scripts/update_dist_freshness.js +1 -0
- package/dist/scripts/update_layout.d.ts +61 -0
- package/dist/scripts/update_layout.js +180 -0
- package/dist/scripts/validate_bots.js +2 -1
- package/dist/scripts/verify-browser-bundle.js +8 -0
- package/dist/unlock.d.ts +28 -3
- package/dist/unlock.js +63 -35
- package/docs/BITSHARES_ONBOARDING.md +2 -0
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
- package/docs/COW_INVARIANTS.md +13 -6
- package/docs/DEXBOT_COMPARISON.md +8 -8
- package/docs/EVOLUTION.md +10 -9
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
- package/docs/GRID_RECALCULATION.md +4 -2
- package/docs/GRID_RECONCILE.md +14 -3
- package/docs/LIFECYCLE.md +11 -11
- package/docs/MPA_CREDIT_USAGE.md +22 -3
- package/docs/README.md +14 -3
- package/docs/architecture.md +12 -9
- package/docs/developer_guide.md +6 -6
- package/market_adapter/README.md +6 -1
- package/modules/README.md +4 -1
- package/package.json +4 -1
|
@@ -40,7 +40,8 @@ const livePath = PATHS.PROFILES.BOTS_JSON;
|
|
|
40
40
|
*/
|
|
41
41
|
function checkConfig(obj, src) {
|
|
42
42
|
// Normalize: convert single bot to array format for uniform processing
|
|
43
|
-
const
|
|
43
|
+
const o = (obj && typeof obj === 'object') ? obj : {};
|
|
44
|
+
const bots = Array.isArray(o.bots) && o.bots.length ? o.bots : [o];
|
|
44
45
|
console.log(`\n== Checking ${src}: found ${bots.length} bot entries`);
|
|
45
46
|
// List of required fields that every bot must have
|
|
46
47
|
const required = ['assetA', 'assetB', 'activeOrders', 'botFunds'];
|
|
@@ -196,6 +196,14 @@ const TESTS = [
|
|
|
196
196
|
expectFail: false,
|
|
197
197
|
externalizeNodeBuiltins: true,
|
|
198
198
|
},
|
|
199
|
+
{
|
|
200
|
+
// Guards the shared ECC core and its browser entry now that ecc.browser.ts
|
|
201
|
+
// delegates its curve math to modules/bitshares-native/crypto/ecc_core.ts.
|
|
202
|
+
label: 'modules/bitshares-native/crypto/ecc.browser.ts (browser-safe)',
|
|
203
|
+
entry: 'modules/bitshares-native/crypto/ecc.browser.ts',
|
|
204
|
+
expectFail: false,
|
|
205
|
+
externalizeNodeBuiltins: true,
|
|
206
|
+
},
|
|
199
207
|
{
|
|
200
208
|
label: 'modules/utils/base58check.ts (browser-safe)',
|
|
201
209
|
entry: 'modules/utils/base58check.ts',
|
package/dist/unlock.d.ts
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import type { ChildProcess } from 'node:child_process';
|
|
2
3
|
declare const waitForChildSpawn: any, pidMatchesScriptCandidates: any, candidateRuntimeScriptPaths: any;
|
|
3
4
|
declare const isLikelyCredentialDaemonProcess: any, ensureNoForeignCredentialDaemon: any, findCredentialSocketOwnerPid: any, buildDexbotStartArgs: any;
|
|
4
|
-
declare function waitForStableChildStartup(child:
|
|
5
|
+
declare function waitForStableChildStartup(child: ChildProcess, { label, timeoutMs }?: {
|
|
6
|
+
label?: string;
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
}): Promise<void>;
|
|
5
9
|
/**
|
|
6
10
|
* Handle first-run setup at the launcher boundary. This is shared by
|
|
7
11
|
* `dexbot start`, `dexbot unlock`, and direct `node unlock` invocations.
|
|
@@ -14,6 +18,27 @@ declare function runStartOnboardingIfNeeded({ allowInteractive, nonInteractiveFl
|
|
|
14
18
|
allowInteractive?: boolean;
|
|
15
19
|
nonInteractiveFlag?: string;
|
|
16
20
|
}): Promise<boolean>;
|
|
17
|
-
declare function main({ argv, startupGraceMs, exitAfterOnboarding, onboard }?:
|
|
18
|
-
|
|
21
|
+
declare function main({ argv, startupGraceMs, exitAfterOnboarding, onboard }?: {
|
|
22
|
+
argv?: string[];
|
|
23
|
+
startupGraceMs?: number;
|
|
24
|
+
exitAfterOnboarding?: boolean;
|
|
25
|
+
onboard?: boolean;
|
|
26
|
+
}): Promise<void>;
|
|
27
|
+
/**
|
|
28
|
+
* Best-effort wait until no `dexbot` worker process remains.
|
|
29
|
+
*
|
|
30
|
+
* `stop` returns as soon as the monolithic wrapper exits, but the wrapper's
|
|
31
|
+
* supervisor pid file is wiped on wrapper exit, so a `start` racing the worker
|
|
32
|
+
* teardown spawns a SECOND worker over the still-live orders (duplicate
|
|
33
|
+
* trades). Poll /proc until every dexbot worker is gone or the deadline
|
|
34
|
+
* expires. No-op off Linux / when /proc is unreadable.
|
|
35
|
+
*
|
|
36
|
+
* Must also run when there is no live wrapper (stale or absent pid file): an
|
|
37
|
+
* orphaned worker is exactly the case the pid-file check cannot see.
|
|
38
|
+
*
|
|
39
|
+
* @param deadlineMs - Maximum time to wait for the workers to exit.
|
|
40
|
+
* @returns True when no worker remains (or the scan is unavailable).
|
|
41
|
+
*/
|
|
42
|
+
declare function drainMonolithicWorkers(deadlineMs?: number): Promise<boolean>;
|
|
43
|
+
export { buildDexbotStartArgs, candidateRuntimeScriptPaths, drainMonolithicWorkers, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, isLikelyCredentialDaemonProcess, main, runStartOnboardingIfNeeded, pidMatchesScriptCandidates, waitForChildSpawn, waitForStableChildStartup };
|
|
19
44
|
//# sourceMappingURL=unlock.d.ts.map
|
package/dist/unlock.js
CHANGED
|
@@ -65,7 +65,7 @@ import { getWhitelistFlags } from './modules/market_adapter_whitelist.js';
|
|
|
65
65
|
import { createMarketAdapterWatchdog } from './modules/launcher/market_adapter_watchdog.js';
|
|
66
66
|
import { isLikelyMarketAdapterProcess } from './modules/launcher/market_adapter_runtime.js';
|
|
67
67
|
import { Config } from './modules/config.js';
|
|
68
|
-
import { getErrorMessage } from './modules/utils/errors.js';
|
|
68
|
+
import { getErrorMessage, getErrorCode } from './modules/utils/errors.js';
|
|
69
69
|
import { isSameBotName } from './modules/utils/sanitize_key.js';
|
|
70
70
|
import { withTimeout } from './modules/order/utils/timeout.js';
|
|
71
71
|
setUmask(0o077);
|
|
@@ -143,7 +143,7 @@ function printLauncherSuccess({ botName = null, clawOnly = false, isolated = fal
|
|
|
143
143
|
function makeFinishGuard(cleanup) {
|
|
144
144
|
let settled = false;
|
|
145
145
|
let timer = null;
|
|
146
|
-
const finish = (fn,
|
|
146
|
+
const finish = (fn, ...args) => {
|
|
147
147
|
if (settled)
|
|
148
148
|
return;
|
|
149
149
|
settled = true;
|
|
@@ -152,7 +152,7 @@ function makeFinishGuard(cleanup) {
|
|
|
152
152
|
timer = null;
|
|
153
153
|
}
|
|
154
154
|
cleanup();
|
|
155
|
-
fn(
|
|
155
|
+
fn(args[0]);
|
|
156
156
|
};
|
|
157
157
|
return { finish, getTimer: () => timer, setTimer: (t) => { timer = t; } };
|
|
158
158
|
}
|
|
@@ -299,12 +299,12 @@ async function launchDetachedSupervisor({ botName = null, credentialDaemonPid =
|
|
|
299
299
|
}),
|
|
300
300
|
stdio: ['ignore', stdoutFd, stderrFd],
|
|
301
301
|
});
|
|
302
|
-
child
|
|
302
|
+
child?.unref();
|
|
303
303
|
const ready = await waitForSupervisorReady({ child });
|
|
304
304
|
if (!ready) {
|
|
305
305
|
throw new Error(`supervisor did not become ready. Check ${SUPERVISOR_OUT_LOG} and ${SUPERVISOR_ERROR_LOG}`);
|
|
306
306
|
}
|
|
307
|
-
return child
|
|
307
|
+
return child?.pid || 0;
|
|
308
308
|
}
|
|
309
309
|
catch (err) {
|
|
310
310
|
if (child && child.pid) {
|
|
@@ -652,7 +652,6 @@ async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRAC
|
|
|
652
652
|
const watchdog = createMarketAdapterWatchdog({
|
|
653
653
|
codeRoot: CODE_ROOT,
|
|
654
654
|
root: PATHS.PROJECT_ROOT,
|
|
655
|
-
logsDir: LOGS_DIR,
|
|
656
655
|
});
|
|
657
656
|
const cancelWatchdog = watchdog.schedule(MONOLITHIC_ERROR_LOG);
|
|
658
657
|
let restartCount = 0;
|
|
@@ -728,7 +727,7 @@ async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRAC
|
|
|
728
727
|
};
|
|
729
728
|
const exitCode = await new Promise((resolve, reject) => {
|
|
730
729
|
botProcess.on('error', reject);
|
|
731
|
-
botProcess.on('close', (code) => resolve(code));
|
|
730
|
+
botProcess.on('close', (code) => resolve(code ?? 0));
|
|
732
731
|
}).catch((err) => {
|
|
733
732
|
cleanupBotHandlers();
|
|
734
733
|
throw err;
|
|
@@ -869,6 +868,45 @@ function printMarketAdapterStatusBlock() {
|
|
|
869
868
|
console.log(` - ${colorStatus(b.name, STATUS_COLORS.ok)} (${b.gridPrice}${suffix})`);
|
|
870
869
|
}
|
|
871
870
|
}
|
|
871
|
+
/**
|
|
872
|
+
* Best-effort wait until no `dexbot` worker process remains.
|
|
873
|
+
*
|
|
874
|
+
* `stop` returns as soon as the monolithic wrapper exits, but the wrapper's
|
|
875
|
+
* supervisor pid file is wiped on wrapper exit, so a `start` racing the worker
|
|
876
|
+
* teardown spawns a SECOND worker over the still-live orders (duplicate
|
|
877
|
+
* trades). Poll /proc until every dexbot worker is gone or the deadline
|
|
878
|
+
* expires. No-op off Linux / when /proc is unreadable.
|
|
879
|
+
*
|
|
880
|
+
* Must also run when there is no live wrapper (stale or absent pid file): an
|
|
881
|
+
* orphaned worker is exactly the case the pid-file check cannot see.
|
|
882
|
+
*
|
|
883
|
+
* @param deadlineMs - Maximum time to wait for the workers to exit.
|
|
884
|
+
* @returns True when no worker remains (or the scan is unavailable).
|
|
885
|
+
*/
|
|
886
|
+
async function drainMonolithicWorkers(deadlineMs = 15000) {
|
|
887
|
+
const workerPaths = candidateRuntimeScriptPaths(['dexbot']);
|
|
888
|
+
const drainStarted = Date.now();
|
|
889
|
+
while (Date.now() - drainStarted < deadlineMs) {
|
|
890
|
+
let aliveWorkers = 0;
|
|
891
|
+
try {
|
|
892
|
+
for (const procEntry of fs.readdirSync('/proc')) {
|
|
893
|
+
const wpid = Number(procEntry);
|
|
894
|
+
if (!Number.isInteger(wpid) || wpid <= 0)
|
|
895
|
+
continue;
|
|
896
|
+
if (pidMatchesScriptCandidates(wpid, workerPaths))
|
|
897
|
+
aliveWorkers++;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
catch (_) { /* /proc scan is best-effort */ }
|
|
901
|
+
// A failed scan yields 0 and returns immediately, so this is a no-op
|
|
902
|
+
// on platforms without /proc rather than a 15s stall.
|
|
903
|
+
if (aliveWorkers === 0)
|
|
904
|
+
return true;
|
|
905
|
+
await new Promise((res) => setTimeout(res, 250));
|
|
906
|
+
}
|
|
907
|
+
console.warn(`dexbot stop: worker process(es) still alive after ${deadlineMs}ms — not waiting longer (state kept; a start may report the running bot).`);
|
|
908
|
+
return false;
|
|
909
|
+
}
|
|
872
910
|
async function handleControl({ cmd, target }) {
|
|
873
911
|
const effectiveCmd = cmd === 'shutdown' ? 'delete' : cmd === 'stat' ? 'status' : cmd;
|
|
874
912
|
const actionLabel = getControlActionLabel(cmd);
|
|
@@ -905,7 +943,7 @@ async function handleControl({ cmd, target }) {
|
|
|
905
943
|
runtime.kill(pid, 'SIGUSR2');
|
|
906
944
|
}
|
|
907
945
|
catch (err) {
|
|
908
|
-
if (err
|
|
946
|
+
if (getErrorCode(err) !== 'ESRCH')
|
|
909
947
|
throw err;
|
|
910
948
|
}
|
|
911
949
|
printControlActionSummary(actionLabel, summaryBotNames, summaryServiceNames);
|
|
@@ -985,35 +1023,11 @@ async function handleControl({ cmd, target }) {
|
|
|
985
1023
|
// (duplicate trades). Wait for every dexbot worker to actually
|
|
986
1024
|
// die before returning.
|
|
987
1025
|
if (monolithicExited) {
|
|
988
|
-
|
|
989
|
-
const drainDeadlineMs = 15000;
|
|
990
|
-
const drainStarted = Date.now();
|
|
991
|
-
let drained = false;
|
|
992
|
-
while (Date.now() - drainStarted < drainDeadlineMs) {
|
|
993
|
-
const aliveWorkers = [];
|
|
994
|
-
try {
|
|
995
|
-
for (const procEntry of fs.readdirSync('/proc')) {
|
|
996
|
-
const wpid = Number(procEntry);
|
|
997
|
-
if (!Number.isInteger(wpid) || wpid <= 0)
|
|
998
|
-
continue;
|
|
999
|
-
if (pidMatchesScriptCandidates(wpid, workerPaths))
|
|
1000
|
-
aliveWorkers.push(wpid);
|
|
1001
|
-
}
|
|
1002
|
-
}
|
|
1003
|
-
catch (_) { /* /proc scan is best-effort */ }
|
|
1004
|
-
if (aliveWorkers.length === 0) {
|
|
1005
|
-
drained = true;
|
|
1006
|
-
break;
|
|
1007
|
-
}
|
|
1008
|
-
await new Promise((res) => setTimeout(res, 250));
|
|
1009
|
-
}
|
|
1010
|
-
if (!drained) {
|
|
1011
|
-
console.warn(`dexbot stop: worker process(es) still alive after ${drainDeadlineMs}ms — not waiting longer (state kept; a start may report the running bot).`);
|
|
1012
|
-
}
|
|
1026
|
+
await drainMonolithicWorkers();
|
|
1013
1027
|
}
|
|
1014
1028
|
}
|
|
1015
1029
|
catch (err) {
|
|
1016
|
-
if (err
|
|
1030
|
+
if (getErrorCode(err) !== 'ESRCH')
|
|
1017
1031
|
throw err;
|
|
1018
1032
|
monolithicExited = true;
|
|
1019
1033
|
}
|
|
@@ -1032,6 +1046,12 @@ async function handleControl({ cmd, target }) {
|
|
|
1032
1046
|
return;
|
|
1033
1047
|
}
|
|
1034
1048
|
else if (stale) {
|
|
1049
|
+
// Stale pid file: the wrapper is gone, but its worker can outlive
|
|
1050
|
+
// it. Drain before returning so a following start cannot spawn a
|
|
1051
|
+
// duplicate over the live orders.
|
|
1052
|
+
if (effectiveCmd !== 'status') {
|
|
1053
|
+
await drainMonolithicWorkers();
|
|
1054
|
+
}
|
|
1035
1055
|
if (effectiveCmd === 'delete') {
|
|
1036
1056
|
const summaryBotNames = getControlBotNames(undefined, true);
|
|
1037
1057
|
const isolatedDeleted = await sendIsolatedDeleteIfAvailable();
|
|
@@ -1063,6 +1083,14 @@ async function handleControl({ cmd, target }) {
|
|
|
1063
1083
|
}
|
|
1064
1084
|
}
|
|
1065
1085
|
}
|
|
1086
|
+
// No live wrapper pid file: an orphaned worker can still be running (the
|
|
1087
|
+
// wrapper was killed without leaving a pid file, or cleanupStateFiles
|
|
1088
|
+
// already ran). Drain before the isolated fall-through so that path cannot
|
|
1089
|
+
// race a start into a duplicate worker.
|
|
1090
|
+
if (!target && effectiveCmd !== 'status'
|
|
1091
|
+
&& (effectiveCmd === 'stop-all' || effectiveCmd === 'delete' || effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all')) {
|
|
1092
|
+
await drainMonolithicWorkers();
|
|
1093
|
+
}
|
|
1066
1094
|
if (effectiveCmd === 'delete' && !target && storage.exists(MONOLITHIC_CRED_PID_FILE)) {
|
|
1067
1095
|
await sendIsolatedDeleteIfAvailable();
|
|
1068
1096
|
const credResult = await stopCredentialDaemon();
|
|
@@ -1148,5 +1176,5 @@ if (isUnlockStartDirectRun) {
|
|
|
1148
1176
|
}
|
|
1149
1177
|
})();
|
|
1150
1178
|
}
|
|
1151
|
-
export { buildDexbotStartArgs, candidateRuntimeScriptPaths, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, isLikelyCredentialDaemonProcess, main, runStartOnboardingIfNeeded, pidMatchesScriptCandidates, waitForChildSpawn, waitForStableChildStartup };
|
|
1179
|
+
export { buildDexbotStartArgs, candidateRuntimeScriptPaths, drainMonolithicWorkers, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, isLikelyCredentialDaemonProcess, main, runStartOnboardingIfNeeded, pidMatchesScriptCandidates, waitForChildSpawn, waitForStableChildStartup };
|
|
1152
1180
|
//# sourceMappingURL=unlock.js.map
|
|
@@ -287,6 +287,8 @@ The only things worth tuning later:
|
|
|
287
287
|
`{ "sell": 1.0, "buy": 1.0 }` for your first bot.
|
|
288
288
|
- `minPrice` / `maxPrice` — grid bounds. Once AMA is active, tighten them
|
|
289
289
|
around the market's maximum expected volatility instead of a wide range.
|
|
290
|
+
Use `dexbot tv <bot>` to see the grid range and AMA recentering against
|
|
291
|
+
real candles.
|
|
290
292
|
|
|
291
293
|
See the "Recommended Bot Setup" section of the
|
|
292
294
|
[README](../README.md#recommended-bot-setup).
|
|
@@ -230,7 +230,7 @@ syncFromMaster(masterGrid, orderId, masterVersion?) {
|
|
|
230
230
|
|--------|-------------|
|
|
231
231
|
| `performSafeRebalance(fills, excludeIds)` | Entry point — delegates to COW |
|
|
232
232
|
| `_applySafeRebalanceCOW(fills, excludeIds)` | Creates working grid, runs planning |
|
|
233
|
-
| `WorkingGrid.buildDelta(masterGrid)` | Delta between master and working copy (`modules/order/working_grid.ts:
|
|
233
|
+
| `WorkingGrid.buildDelta(masterGrid)` | Delta between master and working copy (`modules/order/working_grid.ts:205`, delegating to `utils/order.ts`) |
|
|
234
234
|
| `_commitWorkingGrid(workingGrid, indexes, boundary, options = {})` | Atomic swap to master |
|
|
235
235
|
| `_setRebalanceState(state)` | Track rebalance state |
|
|
236
236
|
| `_currentWorkingGrid` | Reference to working grid during rebalance for fill sync |
|
package/docs/COW_INVARIANTS.md
CHANGED
|
@@ -87,11 +87,11 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
87
87
|
- `INV-PROJ-002` Preserve on-chain PARTIAL size in projection
|
|
88
88
|
- If identity is retained (`keepOrderId=true`) and current state is `PARTIAL`, projected size must preserve current on-chain remaining size.
|
|
89
89
|
- It must not be overwritten by ideal geometric `targetSize`.
|
|
90
|
-
- Exception: a `PARTIAL` with a rotation/size-update action targeting its `orderId` does use `targetSize` (the explicit-UPDATE path at `modules/order/utils/validate.ts:
|
|
90
|
+
- Exception: a `PARTIAL` with a rotation/size-update action targeting its `orderId` does use `targetSize` (the explicit-UPDATE path at `modules/order/utils/validate.ts:1158`).
|
|
91
91
|
- Preserve-path size must be normalized to finite, non-negative value.
|
|
92
92
|
|
|
93
93
|
- `INV-PROJ-003` ACTIVE on-chain projection preserves current size (same as PARTIAL)
|
|
94
|
-
- If identity is retained and state is `ACTIVE`, projection preserves current on-chain size via the same `shouldPreserveSize` path as `PARTIAL` (`validate.ts:
|
|
94
|
+
- If identity is retained and state is `ACTIVE`, projection preserves current on-chain size via the same `shouldPreserveSize` path as `PARTIAL` (`validate.ts:1158`).
|
|
95
95
|
- An explicit UPDATE action targeting the `orderId` is required to apply `targetSize`.
|
|
96
96
|
|
|
97
97
|
- `INV-ID-001` Order identity retention rule
|
|
@@ -110,7 +110,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
110
110
|
- `INV-ACC-003` Cross-bot fund registry invariant (INVARIANT 3)
|
|
111
111
|
- Shared-account per-bot commitment must not exceed the bot's proportional share of chain balance.
|
|
112
112
|
- Checked with widened tolerance `max(PERCENT_TOLERANCE * 3, 0.15)`.
|
|
113
|
-
- Registry failure logs an error (`order/accounting.ts:
|
|
113
|
+
- Registry failure logs an error (`order/accounting.ts:636-685`), not a silent skip.
|
|
114
114
|
|
|
115
115
|
---
|
|
116
116
|
|
|
@@ -229,6 +229,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
229
229
|
- Cancelled IDs are filtered out of `unmatchedParsed` to prevent reprocessing.
|
|
230
230
|
- No size guard — any duplicate at the same price is a violation.
|
|
231
231
|
- The earlier fuzzy `SUSPECTED_DUPLICATE_TOLERANCE_MULTIPLIER` (5× `calculatePriceTolerance`) and `SUSPECTED_DUPLICATE_TOLERANCE_FLOOR` are removed; only exact price-level equality triggers a reconcile cancel.
|
|
232
|
+
- Cancel deferral under `INV-RECON-006` applies before submission.
|
|
232
233
|
|
|
233
234
|
- `INV-RECON-004` Rebalance must not convert on-chain slots to SPREAD via CREATE
|
|
234
235
|
- `performSafeRebalance` must not emit `CREATE` actions that convert existing on-chain slots into SPREAD orders.
|
|
@@ -238,13 +239,19 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
238
239
|
- BUY placements must use nearest available free slots first (descending price, so the nearest-to-center slots fill first — `order/utils/order.ts` `buildOutsideInPairGroups`).
|
|
239
240
|
- SELL placements must use nearest available free slots first (ascending price).
|
|
240
241
|
|
|
242
|
+
- `INV-RECON-006` Fresh-placement cancels are deferred for a grace window
|
|
243
|
+
- A CANCEL action targeting an `orderId` placed within `TIMING.SURPLUS_CANCEL_GRACE_MS` (15 min) is deferred. The timestamp is written by `recordOrderPlacement` into `manager._placedAt` and tested by `isFreshlyPlacedOrder`.
|
|
244
|
+
- `COWRebalanceEngine.execute` drops the whole slot's action group for a deferred cancel (dropping only the CANCEL would let a paired CREATE fold back into an UPDATE and re-materialize the placement), then re-syncs the deferred slots from master via `workingGrid.syncFromMaster` so the commit does not virtualize a still-live order.
|
|
245
|
+
- Divergence correction (`applyGridDivergenceCorrections`) applies the same guard after dropping any queued committed-size UPDATE for the not-desired/size-0 slot.
|
|
246
|
+
- `grid-load`/`grid-init` load contexts are excluded so restarts do not suppress the sweep.
|
|
247
|
+
|
|
241
248
|
---
|
|
242
249
|
|
|
243
250
|
## Batch / Pipeline
|
|
244
251
|
|
|
245
252
|
- `INV-BATCH-001` Illegal state batch abort
|
|
246
253
|
- `executeBatch` throws `ILLEGAL_SPREAD_STATE` on an illegal grid layout (emitted at `modules/order/utils/validate.ts`, propagated via `modules/order/manager.ts` `_throwOnIllegalState`).
|
|
247
|
-
- The `_handleBatchHardAbort` catch for `ILLEGAL_ORDER_STATE` (`dexbot_class.ts:
|
|
254
|
+
- The `_handleBatchHardAbort` catch for `ILLEGAL_ORDER_STATE` (`dexbot_class.ts:501`) is a test-only dead branch — production never emits that code; only a test stub uses it.
|
|
248
255
|
- In production, recovery + cooldown are armed on the next maintenance tick via `_abortFlowIfIllegalState` (the `INV-MAINT-002` path), returning `abortedForIllegalState: true` to the caller. The caller does not need to return immediately; the maintenance tick handles recovery.
|
|
249
256
|
- Hard abort triggers one immediate recovery sync (`_triggerStateRecoverySync`) plus arms one maintenance cooldown cycle (`_maintenanceCooldownCycles = Math.max(current, 1)`).
|
|
250
257
|
|
|
@@ -263,7 +270,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
263
270
|
- NOT virtualize the slot.
|
|
264
271
|
- Preserve `orderId` until sync reconciles it.
|
|
265
272
|
- NOT mark the order as stale-cleaned.
|
|
266
|
-
- Fast path: if the batch result indicates `ORDER_SIZE_DRIFT_TARGETED` (`dexbot_state_recovery.ts:
|
|
273
|
+
- Fast path: if the batch result indicates `ORDER_SIZE_DRIFT_TARGETED` (`dexbot_state_recovery.ts:273`), a targeted repair applies the correction directly and skips `_triggerStateRecoverySync`.
|
|
267
274
|
|
|
268
275
|
---
|
|
269
276
|
|
|
@@ -287,7 +294,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
287
294
|
- `INV-REG-001` Cross-bot allocation ≤ proportional share
|
|
288
295
|
- Per-bot committed amounts (sum of on-chain orders) must not exceed `totalChainBalance × allocatedPercent`.
|
|
289
296
|
- Violation triggers an error-level log entry (not silent), with tolerance `max(PERCENT_TOLERANCE * 3, 0.15)`.
|
|
290
|
-
- Registry registration is pre-flight + atomic; only shared-account bots register (`dexbot.ts:
|
|
297
|
+
- Registry registration is pre-flight + atomic; only shared-account bots register (`dexbot.ts:617` filters `accountGroups[a].length > 1`), and registration completes before any shared-account bot starts.
|
|
291
298
|
- Release happens in `DEXBot.shutdown`.
|
|
292
299
|
|
|
293
300
|
- `INV-REG-002` Async-locked registry writes
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# DEXBot vs DEXBot2 — Detailed Comparison Report
|
|
2
2
|
|
|
3
3
|
> **Date:** 2026-09-02 *(metrics refreshed against local source trees)*
|
|
4
|
-
> **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.6.
|
|
4
|
+
> **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.6.12).
|
|
5
5
|
> **Audience:** Developers, contributors, and operators evaluating or migrating between the two projects.
|
|
6
6
|
|
|
7
7
|
---
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
|
|
37
37
|
| Attribute | DEXBot (original) | DEXBot2 |
|
|
38
38
|
|---|---|---|
|
|
39
|
-
| **Release Track** | 1.0.0 | v1.6.
|
|
39
|
+
| **Release Track** | 1.0.0 | v1.6.12 |
|
|
40
40
|
| **Language** | Python 3.6+ | TypeScript 5.x |
|
|
41
41
|
| **Status** | Released 1.0.0, unmaintained | Active development |
|
|
42
42
|
| **Last Repo Activity** | May 23, 2020 | 2026-09-02 |
|
|
@@ -616,7 +616,7 @@ Where:
|
|
|
616
616
|
### DEXBot2
|
|
617
617
|
|
|
618
618
|
- **Framework:** Native Node `assert` module (no external test framework)
|
|
619
|
-
- **
|
|
619
|
+
- **330 `test_*.ts` files** auto-discovered via `globSync` (`tests/test_*.ts` + `claw/tests/test_*.ts`), covering:
|
|
620
620
|
- Unit tests: accounting, strategy, grid, manager logic
|
|
621
621
|
- Copy-on-Write semantics: COW commits, guards, concurrent fills
|
|
622
622
|
- Edge cases: authoritative full-fill resolution, partial fills, BTS fee accounting, precision
|
|
@@ -776,13 +776,13 @@ Where:
|
|
|
776
776
|
|
|
777
777
|
| Metric | DEXBot | DEXBot2 |
|
|
778
778
|
|---|---|---|
|
|
779
|
-
| **Release Track** | 1.0.0 | v1.6.
|
|
779
|
+
| **Release Track** | 1.0.0 | v1.6.12 |
|
|
780
780
|
| **Active Since** | ~2018 | December 2025 |
|
|
781
|
-
| **Last Commit** | May 23, 2020 | 2026-
|
|
782
|
-
| **Total Commits** | 2281 | 2,
|
|
781
|
+
| **Last Commit** | May 23, 2020 | 2026-10-08 |
|
|
782
|
+
| **Total Commits** | 2281 | 2,350 (current HEAD, v1.6.12 line) |
|
|
783
783
|
| **Lines of Code** | ~10,846 Python LOC in `dexbot/` | Large TypeScript runtime + adapter + Claw + analysis + tests |
|
|
784
|
-
| **Source Files** | 72 Python files in `dexbot/` | ~
|
|
785
|
-
| **Test Files** | 16 Python test files |
|
|
784
|
+
| **Source Files** | 72 Python files in `dexbot/` | ~656 TS files across the repo |
|
|
785
|
+
| **Test Files** | 16 Python test files | 330 `test_*.ts` files (313 `tests/` + 17 `claw/tests/`, auto-discovered via `globSync`) |
|
|
786
786
|
| **Documentation** | Sphinx docs + README | 60+ Markdown docs plus Claw skills/references |
|
|
787
787
|
| **Strategies** | 3 + plugins | 1 |
|
|
788
788
|
| **Max Concurrent Bots** | Many (one process) | Many (one monolithic process by default; per-bot via `--isolated`/PM2) |
|
package/docs/EVOLUTION.md
CHANGED
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
## Executive Summary
|
|
4
4
|
|
|
5
|
-
DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.6.
|
|
5
|
+
DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.6.12 release.
|
|
6
6
|
|
|
7
7
|
### Key Milestones
|
|
8
8
|
- **Project Inception**: December 2, 2025
|
|
9
|
-
- **Growth Phase**: 2,
|
|
9
|
+
- **Growth Phase**: 2,350 commits over ~9 active months
|
|
10
10
|
- **Code Maturity**: Evolution from basic utilities to a ~100,000+ LoC intelligent TypeScript system
|
|
11
|
-
- **Stability**: Progression from manual testing to a suite of
|
|
12
|
-
- **Releases**:
|
|
11
|
+
- **Stability**: Progression from manual testing to a suite of 313 automated test files
|
|
12
|
+
- **Releases**: 144 version entries in the changelog (v0.1.0 to v1.6.12)
|
|
13
13
|
|
|
14
14
|
> **Post-1.0.0 "why":** the thematic story behind the hardening releases — root cause, recurring
|
|
15
15
|
> bug families, and lessons — lives in
|
|
@@ -145,11 +145,11 @@ Evolved from a basic README to a comprehensive framework (50+ docs entries, 80%+
|
|
|
145
145
|
|
|
146
146
|
**Completed**: browser-safe core; credit/MPA runtime; storage-adapter I/O centralization; self-healing recovery; Kibana PnL analytics — terminal analyzer plus the self-contained HTML report behind `dexbot pnl` (`analysis/pnl_report.ts`), backed by a per-account month-shard fill cache (`analysis/fills_cache.ts`); credit-only mode; Docker support; npm package. For the grid order engine arc specifically (COW pipeline, orphan/self-trade/fill-guard hardening, invariants) see [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md) §R4.
|
|
147
147
|
|
|
148
|
-
**Planned**: backtesting engine (historical candle replay via exchange abstraction); injectable interfaces at call boundaries; SQLite persistence + Zod validation at the blockchain boundary
|
|
148
|
+
**Planned**: backtesting engine (historical candle replay via exchange abstraction); injectable interfaces at call boundaries; SQLite persistence + Zod validation at the blockchain boundary.
|
|
149
149
|
|
|
150
150
|
## Version History
|
|
151
151
|
|
|
152
|
-
Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-10-
|
|
152
|
+
Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-10-08), so the column sums to 2,243 — the 107 commits up to and including the `v0.1.0` tag are not attributed to an era (2,243 + 107 = 2,350). Per-release detail lives in [CHANGELOG.md](../CHANGELOG.md); the thematic post-1.0.0 story in [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md).
|
|
153
153
|
|
|
154
154
|
| Era | Commits | Theme |
|
|
155
155
|
|-----|--------:|-------|
|
|
@@ -169,11 +169,12 @@ Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` o
|
|
|
169
169
|
| v1.6.8 → v1.6.9 | 6 | Market-adapter cycle-CPU cuts, candle-boundary off-hour idle, spread-correction spread-tightening guard |
|
|
170
170
|
| v1.6.9 → v1.6.10 | 7 | Huber-robust AMA slope, asset-pair uppercase canonicalization, TradingView indicator ownership (auto opt-in, span bounds) and chart-view preservation |
|
|
171
171
|
| v1.6.10 → v1.6.11 | 6 | AMA-slope 3-bar persistence gate + 16h Huber lookback, EMA-smoothing removal, PnL HTML report + month-shard fill cache, five order-engine/lifecycle safety fixes |
|
|
172
|
+
| v1.6.11 → v1.6.12 | 27 | Explicit-`any` elimination + ratchet, shared ECC core & Firefox-safe pure-JS scrypt, worker-drain and fresh-placement cancel-grace safety fixes, funded spread correction, partial credit renewal, update install-layout classifier, AMA persistence-override fixes, test-suite speedup, dynamic-weight knob retune |
|
|
172
173
|
|
|
173
174
|
---
|
|
174
175
|
|
|
175
176
|
**Report Originally Generated**: February 19, 2026
|
|
176
|
-
**Last Updated**: October
|
|
177
|
-
**Total Commits**: 2,
|
|
178
|
-
**Date Range**: December 2, 2025 – October
|
|
177
|
+
**Last Updated**: October 8, 2026
|
|
178
|
+
**Total Commits**: 2,350
|
|
179
|
+
**Date Range**: December 2, 2025 – October 8, 2026
|
|
179
180
|
**Repository**: DEXBot2 (BitShares DEX Trading Bot)
|
|
@@ -52,7 +52,7 @@ funds.allocated → _getSizingContext() (budget for spread correction)
|
|
|
52
52
|
**Key points:**
|
|
53
53
|
- `botFunds` percentage applies to **total** capital (free + locked in orders), not just free. A bot at `"50%"` gets half of everything, not half of what's currently idle.
|
|
54
54
|
- `funds.allocated` is the ceiling for each side. Existing orders already consume part of it; the remaining free portion is available for new placements.
|
|
55
|
-
- The downstream `applyBotFundsAllocation()` (`manager.ts:
|
|
55
|
+
- The downstream `applyBotFundsAllocation()` (`manager.ts:1277`) also caps `funds.available` to `<= allocated` as a safety net, but the primary budget chokepoint is `getSideBudget` / `_getSizingContext` reading `allocated` directly (v1.2.6).
|
|
56
56
|
|
|
57
57
|
---
|
|
58
58
|
|
|
@@ -123,7 +123,7 @@ See [developer_guide.md#order-state-helper-functions](developer_guide.md#order-s
|
|
|
123
123
|
**Per-Batch Execution**:
|
|
124
124
|
|
|
125
125
|
1. **Peek & Pop**: Check `_incomingFillQueue`, pop up to N fills (batch size)
|
|
126
|
-
2. **Replay-safe Accounting Pass**: Each fill is accounted individually via `processFillAccounting(fillOp, fillKey)` with replay-safe dedup (`applyReplaySafeFillAccounting`, `dexbot_fill_runtime.ts:
|
|
126
|
+
2. **Replay-safe Accounting Pass**: Each fill is accounted individually via `processFillAccounting(fillOp, fillKey)` with replay-safe dedup (`applyReplaySafeFillAccounting`, `dexbot_fill_runtime.ts:305`)
|
|
127
127
|
- Proceeds credited directly to `chainFree` (via `adjustTotalBalance`)
|
|
128
128
|
- Same-order fill batching (sync_engine Phase 6 cumulative transition) aggregates multiple fill transitions on one order before a single rebalance
|
|
129
129
|
- All proceeds immediately available to next rebalance cycle (not split across cycles)
|
|
@@ -137,7 +137,7 @@ See [developer_guide.md#order-state-helper-functions](developer_guide.md#order-s
|
|
|
137
137
|
|
|
138
138
|
**Result**: 29 fills now processed in ~8 broadcasts (~24s) instead of 29 broadcasts (~90s).
|
|
139
139
|
|
|
140
|
-
**Residual Dust Cancellation** (post-1.4.12): After a sub-dust fill leaves a residual order on chain (e.g. the quote-side value truncates to 0 on `bitshares-core` `maybe_cull_small_order`), the fill runtime explicitly cancels those residuals via `cancelResidualOrders()` (`dexbot_fill_runtime.ts:
|
|
140
|
+
**Residual Dust Cancellation** (post-1.4.12): After a sub-dust fill leaves a residual order on chain (e.g. the quote-side value truncates to 0 on `bitshares-core` `maybe_cull_small_order`), the fill runtime explicitly cancels those residuals via `cancelResidualOrders()` (`dexbot_fill_runtime.ts:193`, `[RESIDUAL]` tag) so a leftover of ≥1 base unit cannot be re-adopted into a grid slot by maintenance.
|
|
141
141
|
|
|
142
142
|
#### Grid Regeneration Trigger (Available Funds Ratio — bidirectional)
|
|
143
143
|
|
|
@@ -154,7 +154,7 @@ SHRINK: overAlloc = (gridTracked - allocatedCapital) / allocatedCapital * 100
|
|
|
154
154
|
→ Trigger grid regeneration (resize affected orders down)
|
|
155
155
|
```
|
|
156
156
|
|
|
157
|
-
Deliberately no per-side chain-total-drop leg: a normal fill moves value across sides (pays one asset, receives the other — see `
|
|
157
|
+
Deliberately no per-side chain-total-drop leg: a normal fill moves value across sides (pays one asset, receives the other — see `processFillAccounting`), so one side's total routinely drops ≥3% on ordinary fills, and the fill pipeline already re-sizes from the post-fill budget.
|
|
158
158
|
|
|
159
159
|
**How It Works (grow)**:
|
|
160
160
|
1. Fill occurs → proceeds added to `chainFree`
|
|
@@ -801,4 +801,4 @@ To prevent "Time-of-Check to Time-of-Use" errors:
|
|
|
801
801
|
**TOCTOU protection in `processFillAccounting`.** `_buildBtsDeferredRefundAdjustment` reads `btsFeeState` from `mgr.orders` while the order lock is held — the lock is acquired before accounting runs, and the POST-RESET and BOOTSTRAP tracked-fill accounting paths follow the same locking pattern.
|
|
802
802
|
|
|
803
803
|
---
|
|
804
|
-
*Technical Reference for DEXBot2 v1.6.
|
|
804
|
+
*Technical Reference for DEXBot2 v1.6.12 release*
|
|
@@ -279,7 +279,9 @@ in the same direction, so a 1–2 bar excursion is ignored. A sustained move is
|
|
|
279
279
|
confirmed K bars after onset — up to K−1 bars later than the ungated trigger;
|
|
280
280
|
the independent price/Drift trigger is unaffected.
|
|
281
281
|
`AMA_SLOPE_PERSIST_ENABLED` (default `true`) is the master switch; a
|
|
282
|
-
bot/market can override via `amaSlope.persistBars`
|
|
282
|
+
bot/market can override via `amaSlope.persistBars` (`>= 1` gate length, `0`
|
|
283
|
+
disables) or `amaSlope.persistEnabled: false`, which disables the gate for that
|
|
284
|
+
bot even while the global switch is on.
|
|
283
285
|
Versus the ungated path this cuts resets ~35% and whipsaws (~52%→~17%) with lag
|
|
284
286
|
and range tilt unchanged.
|
|
285
287
|
|
|
@@ -643,7 +645,7 @@ Removed trigger file.
|
|
|
643
645
|
|
|
644
646
|
## Visualizing the AMA Triggers (§3 and §4)
|
|
645
647
|
|
|
646
|
-
`dexbot tv <bot>` (and `analysis/tradingview/analyze_tradingview.js`) replays the
|
|
648
|
+
`dexbot tv <bot>` (and `dist/analysis/tradingview/analyze_tradingview.js`) replays the
|
|
647
649
|
two market-adapter recentering triggers over the chart's candle history and draws
|
|
648
650
|
the accepted grid center, the range that center would own, and one marker per
|
|
649
651
|
reset (amber = AMA-price Δ, cyan = AMA-slope Δ, grey = first snapshot). The
|
package/docs/GRID_RECONCILE.md
CHANGED
|
@@ -125,10 +125,21 @@ but likewise causes no plans to execute because no target remains present.
|
|
|
125
125
|
This closes stale-cancellation replays without requiring the whole book to
|
|
126
126
|
remain unchanged.
|
|
127
127
|
|
|
128
|
+
**Fresh-placement grace (`TIMING.SURPLUS_CANCEL_GRACE_MS`, 15 min):** surplus
|
|
129
|
+
and cancel-only cancellations also skip any order whose `orderId` was placed
|
|
130
|
+
inside the grace window. The timestamp is written by `recordOrderPlacement` into
|
|
131
|
+
`manager._placedAt` and tested with `isFreshlyPlacedOrder`; the reconciler's CANCEL
|
|
132
|
+
actions are filtered by `COWRebalanceEngine.execute`, which drops the whole slot's
|
|
133
|
+
action group (a paired CANCEL+CREATE must not lose only its CANCEL, or the CREATE
|
|
134
|
+
folds back into an UPDATE and re-materializes the placement) and re-syncs the
|
|
135
|
+
deferred slots from master via `workingGrid.syncFromMaster` before commit. The
|
|
136
|
+
order stays ACTIVE and is re-drained once the window expires. `grid-load`/
|
|
137
|
+
`grid-init` contexts are excluded so a restart does not suppress the sweep.
|
|
138
|
+
|
|
128
139
|
Surplus settlement uses the same live-ownership decision. Only an order that is
|
|
129
|
-
still untracked
|
|
130
|
-
or geometry-changed order is
|
|
131
|
-
snapshot.
|
|
140
|
+
still untracked, signature-unchanged, and outside the fresh-placement grace
|
|
141
|
+
window reaches `_cancelChainOrder`; a now-owned or geometry-changed order is
|
|
142
|
+
skipped rather than released from the stale snapshot.
|
|
132
143
|
|
|
133
144
|
**Updates:**
|
|
134
145
|
- Batch via `_executeStartupUpdateBatch` when `supportsBatchUpdate` is available
|
package/docs/LIFECYCLE.md
CHANGED
|
@@ -90,7 +90,7 @@ sequenceDiagram
|
|
|
90
90
|
participant CO as chain_orders (broadcast)
|
|
91
91
|
participant STORE as Storage
|
|
92
92
|
|
|
93
|
-
CH->>Q: enqueue fill(s) (dexbot_fill_runtime.ts:
|
|
93
|
+
CH->>Q: enqueue fill(s) (dexbot_fill_runtime.ts:458)
|
|
94
94
|
FR->>FR: drain queue -> _processFillsWithBatching
|
|
95
95
|
FR->>OM: processFilledOrders() (manager.ts)
|
|
96
96
|
OM->>AC: processFillAccounting() (single call, batch)
|
|
@@ -134,10 +134,10 @@ sequenceDiagram
|
|
|
134
134
|
participant STORE as Storage
|
|
135
135
|
|
|
136
136
|
MA->>CL: AMA center snapshot updated
|
|
137
|
-
CL->>CL: _performPeriodicGridChecks() (dexbot_class.ts:
|
|
138
|
-
CL->>RT: performPeriodicGridChecks() (dexbot_maintenance_runtime.ts:
|
|
139
|
-
RT->>RT: runGridMaintenance(bot,'periodic') (dexbot_maintenance_runtime.ts:
|
|
140
|
-
RT->>RT: executeMaintenanceLogic() (dexbot_maintenance_runtime.ts:
|
|
137
|
+
CL->>CL: _performPeriodicGridChecks() (dexbot_class.ts:1685)
|
|
138
|
+
CL->>RT: performPeriodicGridChecks() (dexbot_maintenance_runtime.ts:1645)
|
|
139
|
+
RT->>RT: runGridMaintenance(bot,'periodic') (dexbot_maintenance_runtime.ts:2944)
|
|
140
|
+
RT->>RT: executeMaintenanceLogic() (dexbot_maintenance_runtime.ts:2443)
|
|
141
141
|
RT->>AC: recalculate funds from balances
|
|
142
142
|
RT->>GD: promote AMA center -> grid center
|
|
143
143
|
RT->>GD: recalculateGrid() (grid.ts)
|
|
@@ -157,13 +157,13 @@ The AMA signal stack (AMA/Kalman/Hurst/PE) is *research-tuned* in `analysis/` an
|
|
|
157
157
|
the parameters.
|
|
158
158
|
|
|
159
159
|
> Note: `runMaintenance()` is a **different** subsystem — the credit/MPA debt
|
|
160
|
-
> runtime (`modules/credit_runtime.ts:
|
|
161
|
-
> `_runCreditRuntimeMaintenance` at `dexbot_class.ts:
|
|
160
|
+
> runtime (`modules/credit_runtime.ts:3468`, reached via
|
|
161
|
+
> `_runCreditRuntimeMaintenance` at `dexbot_class.ts:1802`). The grid maintenance
|
|
162
162
|
> chain above is the one that matters for order/price upkeep.
|
|
163
163
|
|
|
164
|
-
References: `modules/dexbot_class.ts:
|
|
165
|
-
`modules/dexbot_maintenance_runtime.ts:
|
|
166
|
-
`:
|
|
164
|
+
References: `modules/dexbot_class.ts:1685` (`_performPeriodicGridChecks`) →
|
|
165
|
+
`modules/dexbot_maintenance_runtime.ts:1645` (`performPeriodicGridChecks`) →
|
|
166
|
+
`:2944` (`runGridMaintenance`) → `:2443` (`executeMaintenanceLogic`),
|
|
167
167
|
`docs/GRID_RECALCULATION.md`, `docs/GRID_RECONCILE.md`.
|
|
168
168
|
|
|
169
169
|
---
|
|
@@ -192,7 +192,7 @@ enforced*, not compiler-enforced — learn them or you will introduce fund bugs.
|
|
|
192
192
|
| How a fill becomes orders | `modules/dexbot_fill_runtime.ts` → `modules/order/manager.ts` |
|
|
193
193
|
| Grid math / recalculation | `modules/order/grid.ts`, `docs/GRID_RECALCULATION.md` |
|
|
194
194
|
| Funds & accounting | `modules/order/accounting.ts`, `docs/FUND_MOVEMENT_AND_ACCOUNTING.md` |
|
|
195
|
-
| Periodic loop & AMA hook | `modules/dexbot_maintenance_runtime.ts`, `modules/dexbot_class.ts:
|
|
195
|
+
| Periodic loop & AMA hook | `modules/dexbot_maintenance_runtime.ts`, `modules/dexbot_class.ts:1685` |
|
|
196
196
|
| Market signal source | `market_adapter/market_adapter.ts`, `analysis/README.md` |
|
|
197
197
|
| Startup & orchestration | `modules/dexbot_class.ts`, `docs/developer_guide.md` §"Startup Sequence" |
|
|
198
198
|
| Why COW exists | `docs/architecture.md` §"Copy-on-Write (COW) Grid Pattern", `docs/COW_INVARIANTS.md` |
|
package/docs/MPA_CREDIT_USAGE.md
CHANGED
|
@@ -266,6 +266,26 @@ When a deal's `latest_repay_time` is within `CREDIT_DEAL_EXPIRY_THRESHOLD_HOURS`
|
|
|
266
266
|
|
|
267
267
|
If inline reborrow cannot be built safely, the runtime stores a deferred reborrow request in `profiles/credit_runtime/<botKey>.json` and retries later.
|
|
268
268
|
|
|
269
|
+
#### Shortfall-Aware Partial Renewal
|
|
270
|
+
|
|
271
|
+
The repay leg is funded from the borrower's *free* debt-asset balance before the atomic reborrow returns anything. If that balance is below principal + credit fee (the borrowed asset was spent into the grid), a full renewal fails on-chain with `Insufficient Balance`. The runtime renews the largest affordable piece instead:
|
|
272
|
+
|
|
273
|
+
- `free >= principal + fee` → full renewal (legacy behaviour).
|
|
274
|
+
- Otherwise repay/reborrow the largest piece that fits, floored to the debt-asset precision, clamped to the offer's `min_deal_amount` and the policy's `maxBorrowAmountPerOperation`, and leaving one raw unit unspent as a balance-drift buffer.
|
|
275
|
+
- The remainder keeps its original `latest_repay_time` (the rolled piece gets a fresh one), so later cycles chip it away.
|
|
276
|
+
- If no piece can be formed, it falls back to the full renewal so the chain error still surfaces.
|
|
277
|
+
|
|
278
|
+
The reborrow snapshots the pre-repay deal IDs, so the stale-entry guard only drops a request when a deal *appeared after* the repay on the same offer — sibling deals no longer block a legitimate reborrow.
|
|
279
|
+
|
|
280
|
+
#### Collateral Shortfall Scaling
|
|
281
|
+
|
|
282
|
+
A reborrow can only lock the collateral the repay just released. If the market moved against the collateral, the full debt needs more than the deal holds, so the runtime clamps the borrow to the released collateral rather than emit an op that fails the collateral check:
|
|
283
|
+
|
|
284
|
+
- `buildCreditOfferAcceptOperation` takes an optional raw `availableCollateralAmount` budget and shrinks the borrow to the maximum that budget can back at the offer price (`capBorrowToCollateral`). It lives in the shared builder, so original, fallback, and deferred reborrows all get it.
|
|
285
|
+
- A clamped borrow below `min_deal_amount` is deferred and retried (up to `TIMING.CREDIT_REBORROW_MAX_ATTEMPTS`, default `6`) so a price recovery can revive it; after the limit it is dropped. The repay still proceeds, so the position deleverages.
|
|
286
|
+
- The collateral-switch flow passes the new asset's balance as the budget.
|
|
287
|
+
- Each accept records `requestedBorrowAmount` vs `borrowAmount` and `clampedByCollateral` in `lastBorrowRequest`.
|
|
288
|
+
|
|
269
289
|
### Collateral Switching on Renewal
|
|
270
290
|
|
|
271
291
|
You can switch a credit deal's collateral to a different asset on its next renewal by changing `lendingItem.collateralAsset` to the new asset in `bots.json`. The runtime detects existing deals whose collateral no longer matches the policy and migrates them during proactive expiry repay+reborrow. Requirements:
|
|
@@ -322,7 +342,7 @@ The file tracks discovered chain state and pending work, including:
|
|
|
322
342
|
- `positions` — per-position state map keyed as `debtAssetId:collateralAssetId`
|
|
323
343
|
- Active MPA call-order state and credit deal IDs per position
|
|
324
344
|
- `assignedCollateralBudget` per position
|
|
325
|
-
- Pending reborrow requests (including deferred split pieces when an oversized-deal cycle hits `CREDIT_DEAL_SPLIT_MAX_PIECES`)
|
|
345
|
+
- Pending reborrow requests (including deferred split pieces when an oversized-deal cycle hits `CREDIT_DEAL_SPLIT_MAX_PIECES`, and the `reborrowAttempts` counter that bounds retries)
|
|
326
346
|
- Last repay timestamp and grid reset request
|
|
327
347
|
- Debt snapshot across all assets
|
|
328
348
|
|
|
@@ -343,8 +363,7 @@ Treat this file as runtime state, not primary configuration. The source of truth
|
|
|
343
363
|
|
|
344
364
|
- `modules/credit_runtime.ts`: debt workflow executor (Phase 0 oversized-deal splitter lives here)
|
|
345
365
|
- `modules/credit_pricing.ts`: canonical credit-pricing math (offer orientation, conversion rates, CR, fees) shared by runtime and analyzer
|
|
346
|
-
- `modules/cr_planner.ts`: MPA debt-first planner
|
|
347
|
-
- `modules/cr_planner.ts`: `DebtFirstCrPlanOptions` — planner options carrying `maxBorrowAmountPerOperation`; lending-item shapes are validated inline in `bot_settings.ts`
|
|
366
|
+
- `modules/cr_planner.ts`: MPA debt-first planner (`DebtFirstCrPlanOptions`, clamps `debtDelta` by `maxBorrowAmountPerOperation`); lending-item shapes are validated in `modules/bot_settings.ts`
|
|
348
367
|
- `modules/dexbot_class.ts`: runtime startup and watchdog lifecycle
|
|
349
368
|
- `modules/bot_settings.ts`: `debtPolicy` validation
|
|
350
369
|
- `market_adapter/README.md`: AMA pricing, grid triggers, and dynamic-weight runtime
|