dexbot 1.6.10 → 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 +50 -3
- package/README.md +3 -1
- package/analysis/README.md +51 -11
- package/analysis/bot_fitting/README.md +12 -0
- package/analysis/tradingview/README.md +3 -3
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +11 -37
- package/analysis/trend_detection/README.md +31 -0
- 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 +15 -2
- 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 -20
- 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 +55 -10
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +72 -66
- package/dist/analysis/bot_fitting/backtest_lookback_drawdown.d.ts +21 -0
- package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +315 -0
- 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 +10 -17
- 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 +64 -0
- package/dist/analysis/fills_cache.js +254 -0
- package/dist/analysis/fills_source.d.ts +2 -2
- package/dist/analysis/fills_source.js +19 -14
- 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.d.ts +39 -0
- package/dist/analysis/pnl_report.js +325 -0
- 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 -2
- package/dist/analysis/trade_profitability.d.ts +32 -2
- package/dist/analysis/trade_profitability.js +232 -106
- package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
- package/dist/analysis/tradingview/analyze_tradingview.js +9 -10
- package/dist/analysis/tradingview/grid_reset_config.d.ts +42 -31
- package/dist/analysis/tradingview/grid_reset_config.js +35 -6
- package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -8
- package/dist/analysis/tradingview/grid_reset_sim.js +42 -5
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -20
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +102 -0
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +725 -0
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +27 -112
- package/dist/analysis/trend_detection/huber_scale_variants.d.ts +40 -0
- package/dist/analysis/trend_detection/huber_scale_variants.js +176 -0
- 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 +17 -14
- 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 +297 -115
- package/dist/market_adapter/core/market_adapter_service.js +184 -101
- package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
- package/dist/market_adapter/core/strategies/ama.js +7 -32
- 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 +36 -8
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +9 -9
- 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 +97 -226
- 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 -22
- 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 -33
- package/dist/market_adapter/market_adapter.js +69 -75
- 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 +530 -32
- package/dist/modules/constants.js +52 -60
- 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 +117 -80
- 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 +40 -14
- 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 +39 -19
- package/dist/modules/order/format.js +62 -16
- 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 +226 -180
- package/dist/modules/order/manager.js +101 -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 +99 -54
- 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 +326 -106
- package/dist/modules/order/utils/order.js +200 -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 +3 -4
- package/dist/modules/paths.js +3 -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 +4 -0
- package/dist/modules/utils/time_range.js +18 -0
- 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 +66 -84
- package/dist/scripts/chart_command.d.ts +27 -18
- package/dist/scripts/chart_command.js +16 -15
- 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/pnl.d.ts +3 -0
- package/dist/scripts/pnl.js +40 -0
- 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 +72 -10
- 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 +12 -10
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
- package/docs/GRID_RECALCULATION.md +15 -16
- 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 +15 -4
- package/docs/WORKFLOW.md +1 -0
- package/docs/architecture.md +12 -9
- package/docs/developer_guide.md +6 -6
- package/market_adapter/README.md +9 -26
- package/modules/README.md +4 -1
- package/package.json +4 -1
- package/scripts/README.md +14 -0
|
@@ -108,14 +108,14 @@ import * as client from '../bitshares_client.js';
|
|
|
108
108
|
* Production never sets this; default is the chain.
|
|
109
109
|
*/
|
|
110
110
|
function readSingleOrderSeam(mgr, orderId, timeoutMs) {
|
|
111
|
-
const seam = mgr
|
|
111
|
+
const seam = mgr._readSingleOrderFn;
|
|
112
112
|
if (typeof seam === 'function')
|
|
113
113
|
return seam(orderId, timeoutMs);
|
|
114
114
|
return chainOrders.readSingleOrder(orderId, timeoutMs);
|
|
115
115
|
}
|
|
116
116
|
/** Same seam for the batched drift refetch (batch path). */
|
|
117
117
|
function batchReadOrdersSeam(mgr, orderIds, timeoutMs) {
|
|
118
|
-
const seam = mgr
|
|
118
|
+
const seam = mgr._batchReadOrdersFn;
|
|
119
119
|
if (typeof seam === 'function')
|
|
120
120
|
return seam(orderIds, timeoutMs);
|
|
121
121
|
return chainOrders.batchReadOrders(orderIds, timeoutMs);
|
|
@@ -124,7 +124,7 @@ const { BitShares } = client;
|
|
|
124
124
|
import { NATIVE_CLIENT } from '../constants.js';
|
|
125
125
|
const { toFiniteNumber } = Format;
|
|
126
126
|
import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, priceForSlot, priceSlotEqual } from './utils/math.js';
|
|
127
|
-
import { parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance } from './utils/order.js';
|
|
127
|
+
import { parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance, _filterUnmatchedChainOrders } from './utils/order.js';
|
|
128
128
|
import { parseSlotIndex } from './utils/slot.js';
|
|
129
129
|
import { resolveProcessedFillPersistenceMode } from './processed_fill_store.js';
|
|
130
130
|
import { hasGenesisLadder } from './genesis_policy.js';
|
|
@@ -155,8 +155,8 @@ async function confirmSuspectEmptyRead(mgr) {
|
|
|
155
155
|
try {
|
|
156
156
|
if (mgr?.config?.dryRun)
|
|
157
157
|
return 'unavailable';
|
|
158
|
-
const seam = mgr
|
|
159
|
-
const delay = mgr
|
|
158
|
+
const seam = mgr._confirmEmptyReadFn;
|
|
159
|
+
const delay = mgr._skipEmptyReadConfirmDelay
|
|
160
160
|
? 0
|
|
161
161
|
: Math.max(0, Number(TIMING.SYNC_EMPTY_READ_CONFIRM_DELAY_MS) || 0);
|
|
162
162
|
if (typeof seam === 'function') {
|
|
@@ -177,7 +177,7 @@ async function confirmSuspectEmptyRead(mgr) {
|
|
|
177
177
|
}
|
|
178
178
|
let accountRef = null;
|
|
179
179
|
try {
|
|
180
|
-
accountRef = resolveAccountRef(mgr,
|
|
180
|
+
accountRef = resolveAccountRef(mgr, mgr.accountId ?? '');
|
|
181
181
|
}
|
|
182
182
|
catch {
|
|
183
183
|
return 'unavailable';
|
|
@@ -277,7 +277,7 @@ function describeNearestAdoptionCandidates(mgr, chainOrder, precision, matchedGr
|
|
|
277
277
|
` orderId=${slot.orderId || 'none'}` +
|
|
278
278
|
` price=${Format.formatPrice6(slot.price)}` +
|
|
279
279
|
` diff=${Format.formatPrice6(candidate.priceDiff)}` +
|
|
280
|
-
` size=${Format.formatSizeByOrderType(slot.size || 0, chainOrder.type, mgr.assets)}` +
|
|
280
|
+
` size=${Format.formatSizeByOrderType(slot.size || 0, chainOrder.type ?? ORDER_TYPES.SPREAD, mgr.assets)}` +
|
|
281
281
|
` sizeDiffInt=${candidate.sizeDiffInt}` +
|
|
282
282
|
` reason=${reasons.join('|') || 'unknown'}`;
|
|
283
283
|
}).join('; ');
|
|
@@ -296,7 +296,8 @@ function describeNearestAdoptionCandidates(mgr, chainOrder, precision, matchedGr
|
|
|
296
296
|
function chainPriceOnSameLevel(chainPrice, slotPrice, genesis, precision) {
|
|
297
297
|
if (hasGenesisLadder(genesis)) {
|
|
298
298
|
try {
|
|
299
|
-
|
|
299
|
+
const g = genesis;
|
|
300
|
+
return slotIndexForPrice(chainPrice, g) === slotIndexForPrice(slotPrice, g);
|
|
300
301
|
}
|
|
301
302
|
catch { /* unjudgeable — fall through to integer equality */ }
|
|
302
303
|
}
|
|
@@ -328,7 +329,7 @@ function chainPriceOnSameLevel(chainPrice, slotPrice, genesis, precision) {
|
|
|
328
329
|
*/
|
|
329
330
|
function adoptedSlotKeepsItsOwnPrice(mgr, adopted, chainOrderId, path) {
|
|
330
331
|
try {
|
|
331
|
-
const genesis = mgr
|
|
332
|
+
const genesis = mgr._genesis;
|
|
332
333
|
const levels = genesis?.priceLevels;
|
|
333
334
|
if (!Array.isArray(levels) || levels.length === 0) {
|
|
334
335
|
// Undefined grid (INV-GRID-004): no ladder means no authority for
|
|
@@ -351,7 +352,7 @@ function adoptedSlotKeepsItsOwnPrice(mgr, adopted, chainOrderId, path) {
|
|
|
351
352
|
const diff = Math.abs(got - expected);
|
|
352
353
|
const rel = diff / Math.max(1e-12, Math.abs(expected));
|
|
353
354
|
if (rel > 1e-9 && diff > 1e-12) {
|
|
354
|
-
mgr.logger?.log?.(`[SYNC] Adoption (${path}) for ${chainOrderId} into slot ${adopted
|
|
355
|
+
mgr.logger?.log?.(`[SYNC] Adoption (${path}) for ${chainOrderId} into slot ${adopted?.id}: slot price ${got} is NOT the slot's ` +
|
|
355
356
|
`genesis level ${expected} (drift ${(rel * 100).toFixed(3)}%). Adoption must not write the chain order's price ` +
|
|
356
357
|
`into slot.price — the slot keeps its own level. Adopting anyway (the chain order is real); investigate what ` +
|
|
357
358
|
`corrupted this slot's price.`, 'warn');
|
|
@@ -399,22 +400,28 @@ async function adoptChainOrderIntoSlot(mgr, slot, chainOrder, chainOrderId, rawC
|
|
|
399
400
|
bestMatch.orderId = chainOrderId;
|
|
400
401
|
bestMatch.state = wasVirtual ? ORDER_STATES.ACTIVE : slot.state;
|
|
401
402
|
const bestMatchRaw = rawChainOrders.get(chainOrderId);
|
|
402
|
-
bestMatch.rawOnChain = bestMatchRaw
|
|
403
|
+
bestMatch.rawOnChain = bestMatchRaw
|
|
404
|
+
? { ...bestMatchRaw, fetchedAt: Date.now() }
|
|
405
|
+
: bestMatchRaw;
|
|
403
406
|
matchedGridOrderIds.add(bestMatch.id);
|
|
404
407
|
if (bestMatch.rawOnChain) {
|
|
405
|
-
const
|
|
408
|
+
const rawRecord = bestMatch.rawOnChain;
|
|
409
|
+
const rawDeferredFee = toFiniteNumber(rawRecord.deferred_fee, null);
|
|
406
410
|
if (rawDeferredFee !== null && rawDeferredFee > 0) {
|
|
407
411
|
bestMatch.btsFeeState = { deferredFee: blockchainToFloat(rawDeferredFee, BTS_PRECISION) };
|
|
408
412
|
}
|
|
409
|
-
else if (wasVirtual && rawDeferredFee !== null && rawDeferredFee <= 0 &&
|
|
413
|
+
else if (wasVirtual && rawDeferredFee !== null && rawDeferredFee <= 0 && Number(rawRecord.for_sale) > 0) {
|
|
410
414
|
bestMatch.state = ORDER_STATES.PARTIAL;
|
|
411
415
|
}
|
|
412
416
|
}
|
|
413
|
-
const
|
|
417
|
+
const assets = mgr.assets;
|
|
418
|
+
if (!assets?.assetA || !assets?.assetB)
|
|
419
|
+
return false;
|
|
420
|
+
const precision = (bestMatch.type === ORDER_TYPES.SELL) ? assets.assetA.precision : assets.assetB.precision;
|
|
414
421
|
const targetInt = floatToBlockchainInt(slot.size, precision);
|
|
415
422
|
const chainInt = floatToBlockchainInt(chainOrder.size, precision);
|
|
416
423
|
if (targetInt !== chainInt) {
|
|
417
|
-
const updated = await applyChainSizeToGridOrder(mgr, bestMatch, chainOrder.size);
|
|
424
|
+
const updated = await applyChainSizeToGridOrder(mgr, bestMatch, toFiniteNumber(chainOrder.size));
|
|
418
425
|
if (updated)
|
|
419
426
|
bestMatch = { ...bestMatch, ...updated };
|
|
420
427
|
if (chainInt > 0) {
|
|
@@ -442,6 +449,10 @@ async function adoptChainOrderIntoSlot(mgr, slot, chainOrder, chainOrderId, rawC
|
|
|
442
449
|
filledOrders.push({ ...bestMatch });
|
|
443
450
|
updatedOrders.push(spreadOrder);
|
|
444
451
|
chainOrderIdsOnGrid.add(chainOrderId);
|
|
452
|
+
try {
|
|
453
|
+
_filterUnmatchedChainOrders(mgr, chainOrderId);
|
|
454
|
+
}
|
|
455
|
+
catch { /* counting hygiene only */ }
|
|
445
456
|
return true; // filled path
|
|
446
457
|
}
|
|
447
458
|
}
|
|
@@ -458,6 +469,12 @@ async function adoptChainOrderIntoSlot(mgr, slot, chainOrder, chainOrderId, rawC
|
|
|
458
469
|
}
|
|
459
470
|
updatedOrders.push(bestMatch);
|
|
460
471
|
chainOrderIdsOnGrid.add(chainOrderId);
|
|
472
|
+
// Adopted means matched: drop any deferred-orphan record so fund counting
|
|
473
|
+
// (which adds unmatched locks) never double-counts the slot.
|
|
474
|
+
try {
|
|
475
|
+
_filterUnmatchedChainOrders(mgr, chainOrderId);
|
|
476
|
+
}
|
|
477
|
+
catch { /* counting hygiene only */ }
|
|
461
478
|
return true;
|
|
462
479
|
}
|
|
463
480
|
class SyncEngine {
|
|
@@ -631,7 +648,7 @@ class SyncEngine {
|
|
|
631
648
|
? innerResult.unmatchedChainOrders.length
|
|
632
649
|
: 0;
|
|
633
650
|
mgr._lastUnmatchedChainOrders = unmatchedCount > 0
|
|
634
|
-
? innerResult.unmatchedChainOrders.map((order) => ({ ...order }))
|
|
651
|
+
? (innerResult.unmatchedChainOrders ?? []).map((order) => ({ ...order }))
|
|
635
652
|
: [];
|
|
636
653
|
mgr._lastUnmatchedChainOrdersAt = unmatchedCount > 0 ? Date.now() : 0;
|
|
637
654
|
mgr.logger?.log?.(`[SYNC] Synchronization complete: ${innerResult.filledOrders.length} filled, ` +
|
|
@@ -759,7 +776,7 @@ class SyncEngine {
|
|
|
759
776
|
if (parsedChainOrders.size === 0) {
|
|
760
777
|
const gridOrderIds = Array.from(mgr.orders.values()).filter((o) => o?.orderId).length;
|
|
761
778
|
if (gridOrderIds > 0) {
|
|
762
|
-
const suspect = mgr._suspectEmptyReads
|
|
779
|
+
const suspect = mgr._suspectEmptyReads ?? { count: 0, firstAt: 0 };
|
|
763
780
|
suspect.count += 1;
|
|
764
781
|
if (!suspect.firstAt)
|
|
765
782
|
suspect.firstAt = Date.now();
|
|
@@ -883,7 +900,7 @@ class SyncEngine {
|
|
|
883
900
|
* @returns {Promise<any>}
|
|
884
901
|
*/
|
|
885
902
|
async _performSyncFromOpenOrders(mgr, assetAPrecision, assetBPrecision, parsedChainOrders, rawChainOrders, chainOrderIdsOnGrid, matchedGridOrderIds, filledOrders, updatedOrders, ordersNeedingCorrection, unmatchedChainOrders, options) {
|
|
886
|
-
const skipAccounting = options?.skipAccounting ?? true;
|
|
903
|
+
const skipAccounting = (options?.skipAccounting ?? true);
|
|
887
904
|
const queueCorrection = (entry) => {
|
|
888
905
|
// Provenance: classify the detector so a stale replay at drain
|
|
889
906
|
// time logs who queued it and when. Classification from entry
|
|
@@ -917,6 +934,8 @@ class SyncEngine {
|
|
|
917
934
|
for (const gridOrder of mgr.orders.values()) {
|
|
918
935
|
if (gridOrder.orderId && parsedChainOrders.has(gridOrder.orderId)) {
|
|
919
936
|
const chainOrder = parsedChainOrders.get(gridOrder.orderId);
|
|
937
|
+
if (!chainOrder)
|
|
938
|
+
continue;
|
|
920
939
|
let updatedOrder = { ...gridOrder };
|
|
921
940
|
chainOrderIdsOnGrid.add(gridOrder.orderId);
|
|
922
941
|
// Store raw blockchain data in grid slot for later update calculation.
|
|
@@ -1016,12 +1035,13 @@ class SyncEngine {
|
|
|
1016
1035
|
// pass-2 adoption path below: deferred_fee > 0 → fee
|
|
1017
1036
|
// state; deferred_fee === 0 with for_sale > 0 → the
|
|
1018
1037
|
// order was partially filled).
|
|
1019
|
-
const
|
|
1038
|
+
const reboundRaw = reboundOrder.rawOnChain;
|
|
1039
|
+
const rawDeferredFee = toFiniteNumber(reboundRaw?.deferred_fee, null);
|
|
1020
1040
|
if (rawDeferredFee !== null && rawDeferredFee > 0) {
|
|
1021
1041
|
reboundOrder.btsFeeState = { deferredFee: blockchainToFloat(rawDeferredFee, BTS_PRECISION) };
|
|
1022
1042
|
}
|
|
1023
1043
|
else if (rawDeferredFee !== null && rawDeferredFee <= 0
|
|
1024
|
-
&& toFiniteNumber(
|
|
1044
|
+
&& toFiniteNumber(reboundRaw?.for_sale, 0) > 0) {
|
|
1025
1045
|
reboundOrder.state = ORDER_STATES.PARTIAL;
|
|
1026
1046
|
}
|
|
1027
1047
|
const applied = await mgr._applyOrderUpdate(reboundOrder, 'sync-pass1-duplicate-swap', { skipAccounting: skipAccounting, fee: 0 });
|
|
@@ -1118,7 +1138,7 @@ class SyncEngine {
|
|
|
1118
1138
|
// at 3s each). Prevents permanent stall when a fill event was missed
|
|
1119
1139
|
// (reconnect gap, lossy subscription) and the only detection path is
|
|
1120
1140
|
// this open-orders sync.
|
|
1121
|
-
if (mgr._committedOrderIds?.has(gridOrder.orderId)) {
|
|
1141
|
+
if (gridOrder.orderId != null && mgr._committedOrderIds?.has(gridOrder.orderId)) {
|
|
1122
1142
|
const commitAge = Date.now() - (mgr._committedOrderIdsBuiltAt || 0);
|
|
1123
1143
|
const isGhost = gridOrder.size <= 0 && gridOrder.state === ORDER_STATES.PARTIAL;
|
|
1124
1144
|
if (!isGhost && commitAge < TIMING.SYNC_LOCK_TIMEOUT_MS) {
|
|
@@ -1157,13 +1177,14 @@ class SyncEngine {
|
|
|
1157
1177
|
// PASS 2: CHAIN → GRID - Nearest-slot deterministic adoption (genesis-frozen)
|
|
1158
1178
|
// ====================================================================
|
|
1159
1179
|
const genesis = mgr._genesis;
|
|
1180
|
+
const genesisLadder = genesis;
|
|
1160
1181
|
// Genesis is mandatory for any populated grid, but an EMPTY grid
|
|
1161
1182
|
// (slotCount 0) passes the E2 gate without a ladder, so the
|
|
1162
1183
|
// `!hasGenesis` branch below is reachable when live chain orders exist
|
|
1163
1184
|
// against no slots. There the anchor is meaningless and only orders the
|
|
1164
1185
|
// deferred holds (every price is measured against 0, i.e. ascending).
|
|
1165
1186
|
const hasGenesis = hasGenesisLadder(genesis);
|
|
1166
|
-
const anchorPrice = hasGenesis ? genesis
|
|
1187
|
+
const anchorPrice = hasGenesis ? (genesis?.startPrice ?? 0) : 0;
|
|
1167
1188
|
const sortedChainEntries = [...parsedChainOrders.entries()].sort((a, b) => {
|
|
1168
1189
|
const pa = toFiniteNumber(a[1].price);
|
|
1169
1190
|
const pb = toFiniteNumber(b[1].price);
|
|
@@ -1190,7 +1211,7 @@ class SyncEngine {
|
|
|
1190
1211
|
}
|
|
1191
1212
|
let idx;
|
|
1192
1213
|
try {
|
|
1193
|
-
idx = slotIndexForPrice(chainOrder.price,
|
|
1214
|
+
idx = slotIndexForPrice(chainOrder.price, genesisLadder);
|
|
1194
1215
|
}
|
|
1195
1216
|
catch {
|
|
1196
1217
|
unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'no-available-nearest-slot' });
|
|
@@ -1207,13 +1228,13 @@ class SyncEngine {
|
|
|
1207
1228
|
// sitting below a fresh grid after a reset.
|
|
1208
1229
|
{
|
|
1209
1230
|
const precision = (chainOrder.type === ORDER_TYPES.SELL) ? assetAPrecision : assetBPrecision;
|
|
1210
|
-
if (isChainPriceOutOfGrid(chainOrder.price,
|
|
1231
|
+
if (isChainPriceOutOfGrid(chainOrder.price, genesisLadder, precision)) {
|
|
1211
1232
|
unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'out-of-grid-deferred', candidateSlotId: slotId });
|
|
1212
1233
|
mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: price outside grid range, deferred (nearest slot ${slotId})`, 'warn');
|
|
1213
1234
|
continue;
|
|
1214
1235
|
}
|
|
1215
1236
|
}
|
|
1216
|
-
const gapSlots = genesis
|
|
1237
|
+
const gapSlots = genesis?.gapSlots ?? mgr._gapSlots ?? 0;
|
|
1217
1238
|
const boundaryIdx = mgr.boundaryIdx;
|
|
1218
1239
|
// Pre-boundary sync: gap geometry is unknown, so adoption is
|
|
1219
1240
|
// deferred entirely — touch nothing (no adopt, no cancelOnly).
|
|
@@ -1283,6 +1304,9 @@ class SyncEngine {
|
|
|
1283
1304
|
return null;
|
|
1284
1305
|
}
|
|
1285
1306
|
_computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw) {
|
|
1307
|
+
const assets = mgr.assets;
|
|
1308
|
+
if (!assets?.assetA || !assets?.assetB)
|
|
1309
|
+
throw new Error('assets required for fill context');
|
|
1286
1310
|
// A SPREAD slot can carry an on-chain order (e.g. spread-correction
|
|
1287
1311
|
// activation). Resolve the real side from the fill's pays asset so the
|
|
1288
1312
|
// transition result is BUY/SELL — never SPREAD with an on-chain state,
|
|
@@ -1292,22 +1316,22 @@ class SyncEngine {
|
|
|
1292
1316
|
// into a fill result (which would drop the boundary shift downstream).
|
|
1293
1317
|
let orderType = matchedGridOrder.type;
|
|
1294
1318
|
if (orderType === ORDER_TYPES.SPREAD) {
|
|
1295
|
-
if (paysAssetId ===
|
|
1319
|
+
if (paysAssetId === assets.assetB.id)
|
|
1296
1320
|
orderType = ORDER_TYPES.BUY;
|
|
1297
|
-
else if (paysAssetId ===
|
|
1321
|
+
else if (paysAssetId === assets.assetA.id)
|
|
1298
1322
|
orderType = ORDER_TYPES.SELL;
|
|
1299
1323
|
else
|
|
1300
1324
|
orderType = resolveSpreadOrderSide(matchedGridOrder.price, mgr.config.startPrice);
|
|
1301
1325
|
}
|
|
1302
1326
|
const currentSize = toFiniteNumber(matchedGridOrder.size);
|
|
1303
|
-
const precision = (orderType === ORDER_TYPES.SELL) ?
|
|
1327
|
+
const precision = (orderType === ORDER_TYPES.SELL) ? assets.assetA.precision : assets.assetB.precision;
|
|
1304
1328
|
let filledAmount = 0;
|
|
1305
1329
|
if (orderType === ORDER_TYPES.SELL) {
|
|
1306
|
-
if (paysAssetId ===
|
|
1330
|
+
if (paysAssetId === assets.assetA.id)
|
|
1307
1331
|
filledAmount = blockchainToFloat(paysAmountRaw, precision);
|
|
1308
1332
|
}
|
|
1309
1333
|
else {
|
|
1310
|
-
if (paysAssetId ===
|
|
1334
|
+
if (paysAssetId === assets.assetB.id)
|
|
1311
1335
|
filledAmount = blockchainToFloat(paysAmountRaw, precision);
|
|
1312
1336
|
}
|
|
1313
1337
|
const currentSizeIntFromGrid = floatToBlockchainInt(currentSize, precision);
|
|
@@ -1345,7 +1369,8 @@ class SyncEngine {
|
|
|
1345
1369
|
// sweep it.
|
|
1346
1370
|
let residualCancel = null;
|
|
1347
1371
|
if (!isEffectivelyFull) {
|
|
1348
|
-
const
|
|
1372
|
+
const assets = mgr.assets;
|
|
1373
|
+
const otherPrecision = (orderType === ORDER_TYPES.SELL) ? assets.assetB.precision : assets.assetA.precision;
|
|
1349
1374
|
const otherSidePrice = matchedGridOrder.price;
|
|
1350
1375
|
const otherSize = (orderType === ORDER_TYPES.SELL) ? newSize * otherSidePrice : newSize / otherSidePrice;
|
|
1351
1376
|
if (floatToBlockchainInt(otherSize, otherPrecision) <= 0) {
|
|
@@ -1377,7 +1402,7 @@ class SyncEngine {
|
|
|
1377
1402
|
}
|
|
1378
1403
|
else {
|
|
1379
1404
|
try {
|
|
1380
|
-
const residualOrder = await readSingleOrderSeam(mgr, matchedGridOrder.orderId, 3000);
|
|
1405
|
+
const residualOrder = await readSingleOrderSeam(mgr, matchedGridOrder.orderId ?? '', 3000);
|
|
1381
1406
|
residualForSale = residualOrder ? toFiniteNumber(residualOrder.for_sale, null) : null;
|
|
1382
1407
|
}
|
|
1383
1408
|
catch (residualErr) {
|
|
@@ -1386,7 +1411,7 @@ class SyncEngine {
|
|
|
1386
1411
|
// authoritative fill transition.
|
|
1387
1412
|
mgr.logger.log(`[SYNC] Order ${matchedGridOrder.orderId} (slot ${matchedGridOrder.id}) other-side (${otherSize}) rounds to 0. ` +
|
|
1388
1413
|
`Fill is authoritative: treating as full fill for rotation. Residual verification read failed (${getErrorMessage(residualErr)}); ` +
|
|
1389
|
-
`relying on reconciliation for
|
|
1414
|
+
`relying on reconciliation for residuals.`, 'warn');
|
|
1390
1415
|
}
|
|
1391
1416
|
}
|
|
1392
1417
|
if (Number.isFinite(residualForSale) && Math.round(residualForSale) > 0) {
|
|
@@ -1467,6 +1492,10 @@ class SyncEngine {
|
|
|
1467
1492
|
const blockNum = fill.block_num;
|
|
1468
1493
|
const historyId = fill.id;
|
|
1469
1494
|
const orderId = fillOp.order_id;
|
|
1495
|
+
if (orderId == null || orderId === '') {
|
|
1496
|
+
mgr.logger.log('[SYNC] Fill event missing order_id; deferring to open-orders sync', 'warn');
|
|
1497
|
+
return { filledOrders: [], updatedOrders: [], partialFill: false, requiresOpenOrdersSync: true };
|
|
1498
|
+
}
|
|
1470
1499
|
if (fillOp.is_maker === undefined) {
|
|
1471
1500
|
mgr.logger.log(`[SYNC] is_maker flag missing from fill data for order ${orderId}; defaulting to maker`, 'warn');
|
|
1472
1501
|
}
|
|
@@ -1539,7 +1568,7 @@ class SyncEngine {
|
|
|
1539
1568
|
}
|
|
1540
1569
|
}
|
|
1541
1570
|
catch (refetchErr) {
|
|
1542
|
-
mgr.logger.log(`[SYNC] Drift refetch for ${orderId} failed; falling back to cache: ${refetchErr
|
|
1571
|
+
mgr.logger.log(`[SYNC] Drift refetch for ${orderId} failed; falling back to cache: ${getErrorMessage(refetchErr)}`, 'warn');
|
|
1543
1572
|
}
|
|
1544
1573
|
}
|
|
1545
1574
|
const result = await this._computeFillTransitionResult(mgr, {
|
|
@@ -1659,7 +1688,7 @@ class SyncEngine {
|
|
|
1659
1688
|
return { filledOrders: [], updatedOrders: [], partialFill: false, requiresOpenOrdersSync: anyRequiresSync };
|
|
1660
1689
|
}
|
|
1661
1690
|
// Phase 2: Lock all unique order IDs once
|
|
1662
|
-
const allOrderIds = [...new Set(fillEntries.map(e => e.orderId))];
|
|
1691
|
+
const allOrderIds = [...new Set(fillEntries.map(e => e.orderId))].filter((id) => typeof id === 'string');
|
|
1663
1692
|
// Raise the fill-batch in-flight guard BEFORE the accountTotals refresh.
|
|
1664
1693
|
// The refresh fetches post-fill balances, but the grid still holds the
|
|
1665
1694
|
// filled orders as committed until the batch's grid mutation (Phase 7),
|
|
@@ -1717,7 +1746,7 @@ class SyncEngine {
|
|
|
1717
1746
|
}
|
|
1718
1747
|
const ctx = this._computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw);
|
|
1719
1748
|
mgr.logger.log(`[SYNC] Order ${orderId} (${ctx.orderType}) currentSize=${ctx.currentSize}, filledAmount=${ctx.filledAmount}`, 'debug');
|
|
1720
|
-
if (ctx.driftSignal) {
|
|
1749
|
+
if (ctx.driftSignal && orderId) {
|
|
1721
1750
|
driftOrderIds.add(orderId);
|
|
1722
1751
|
}
|
|
1723
1752
|
entryContexts.push({
|
|
@@ -1771,7 +1800,7 @@ class SyncEngine {
|
|
|
1771
1800
|
}
|
|
1772
1801
|
}
|
|
1773
1802
|
catch (refetchErr) {
|
|
1774
|
-
mgr.logger.log(`[SYNC] Batch drift refetch failed for ${driftOrderIds.size} orders; falling back to cache: ${refetchErr
|
|
1803
|
+
mgr.logger.log(`[SYNC] Batch drift refetch failed for ${driftOrderIds.size} orders; falling back to cache: ${getErrorMessage(refetchErr)}`, 'warn');
|
|
1775
1804
|
}
|
|
1776
1805
|
}
|
|
1777
1806
|
// Phase 6: Compute state transitions and collect grid updates.
|
|
@@ -1812,7 +1841,7 @@ class SyncEngine {
|
|
|
1812
1841
|
if (group.length > 1) {
|
|
1813
1842
|
mgr.logger.log(`[SYNC] Aggregated ${group.length} fill(s) for order ${orderId} (slot ${matchedGridOrder.id}): total filled=${totalFilledAmount}`, 'debug');
|
|
1814
1843
|
}
|
|
1815
|
-
const refetchInfo = refetchMap.get(orderId);
|
|
1844
|
+
const refetchInfo = refetchMap.get(orderId ?? '');
|
|
1816
1845
|
const chainRefetched = refetchInfo?.chainRefetched || false;
|
|
1817
1846
|
const chainConfirmsEmpty = refetchInfo?.chainConfirmsEmpty || false;
|
|
1818
1847
|
const effectiveRawForSale = refetchInfo?.effectiveRawForSale != null ? refetchInfo.effectiveRawForSale : rawForSaleInt;
|
|
@@ -1833,14 +1862,14 @@ class SyncEngine {
|
|
|
1833
1862
|
});
|
|
1834
1863
|
if (result.isFull) {
|
|
1835
1864
|
mgr.logger.log(`[SYNC] Full fill for order ${orderId} (slot ${matchedGridOrder.id}).`, 'info');
|
|
1836
|
-
gridUpdates.push({ id: matchedGridOrder.id,
|
|
1865
|
+
gridUpdates.push({ ...result.fullUpdate, id: matchedGridOrder.id, context: 'handle-fill-full' });
|
|
1837
1866
|
filledOrders.push(result.filledOrder);
|
|
1838
1867
|
if (result.residualCancel)
|
|
1839
1868
|
residualCancels.push(result.residualCancel);
|
|
1840
1869
|
}
|
|
1841
1870
|
else {
|
|
1842
1871
|
mgr.logger.log(`[SYNC] Partial fill for order ${orderId} (slot ${matchedGridOrder.id}): newSize=${result.newSize}`, 'info');
|
|
1843
|
-
gridUpdates.push({ id: matchedGridOrder.id,
|
|
1872
|
+
gridUpdates.push({ ...result.partialUpdate, id: matchedGridOrder.id, context: 'handle-fill-partial' });
|
|
1844
1873
|
updatedOrders.push(result.partialUpdate);
|
|
1845
1874
|
filledOrders.push(result.filledOrder);
|
|
1846
1875
|
anyPartialFill = true;
|
|
@@ -1952,14 +1981,14 @@ class SyncEngine {
|
|
|
1952
1981
|
*
|
|
1953
1982
|
* Non-throwing on purpose: the load-side gates (E1/E3) own the fail-closed
|
|
1954
1983
|
* decision, this one makes a bypass loud without stranding a live manager.
|
|
1955
|
-
* @param {
|
|
1984
|
+
* @param {unknown} mgr - OrderManager instance
|
|
1956
1985
|
* @returns {boolean} true when the grid may be synced (no slots, or a usable
|
|
1957
1986
|
* ladder is present); false when the sync must not run.
|
|
1958
1987
|
*/
|
|
1959
1988
|
_assertGenesisInvariant(mgr) {
|
|
1960
1989
|
try {
|
|
1961
1990
|
const orders = mgr?.orders;
|
|
1962
|
-
const slotCount = orders instanceof Map ? orders.size :
|
|
1991
|
+
const slotCount = orders instanceof Map ? orders.size : 0;
|
|
1963
1992
|
if (slotCount === 0)
|
|
1964
1993
|
return true;
|
|
1965
1994
|
if (hasGenesisLadder(mgr._genesis))
|
|
@@ -1991,7 +2020,7 @@ class SyncEngine {
|
|
|
1991
2020
|
async synchronizeWithChain(chainData, source) {
|
|
1992
2021
|
const mgr = this.manager;
|
|
1993
2022
|
if (!mgr.assets)
|
|
1994
|
-
return { newOrders: [], ordersNeedingCorrection: [] };
|
|
2023
|
+
return { newOrders: [], filledOrders: [], updatedOrders: [], ordersNeedingCorrection: [] };
|
|
1995
2024
|
switch (source) {
|
|
1996
2025
|
case 'createOrder': {
|
|
1997
2026
|
const { gridOrderId, chainOrderId, isPartialPlacement, expectedType, fee } = chainData;
|
|
@@ -2045,7 +2074,7 @@ class SyncEngine {
|
|
|
2045
2074
|
...gridOrder,
|
|
2046
2075
|
type: normalizedExpectedType || gridOrder.type,
|
|
2047
2076
|
state: newState,
|
|
2048
|
-
orderId: chainOrderId,
|
|
2077
|
+
orderId: chainOrderId ?? null,
|
|
2049
2078
|
};
|
|
2050
2079
|
// Restore btsFeeState from raw chain order data if provided.
|
|
2051
2080
|
// After a grid reset, in-memory orders have no fee state but the
|
|
@@ -2057,10 +2086,22 @@ class SyncEngine {
|
|
|
2057
2086
|
}
|
|
2058
2087
|
// Deduced fee (createFee or updateFee) must always be applied to reflect blockchain cost
|
|
2059
2088
|
const actualFee = fee;
|
|
2060
|
-
await mgr._applyOrderUpdate(updatedOrder, 'fill-place', {
|
|
2089
|
+
const linked = await mgr._applyOrderUpdate(updatedOrder, 'fill-place', {
|
|
2061
2090
|
skipAccounting: chainData.skipAccounting || false,
|
|
2062
2091
|
fee: actualFee
|
|
2063
2092
|
});
|
|
2093
|
+
// Linkage binds the chain order to a slot. Drop any
|
|
2094
|
+
// deferred-orphan record for it: fund accounting counts
|
|
2095
|
+
// unmatched locks too, so a kept record double-counts
|
|
2096
|
+
// now that the slot loop also sees the order. Only on
|
|
2097
|
+
// success — a rejected update leaves the order
|
|
2098
|
+
// unmatched and the record must stay.
|
|
2099
|
+
if (linked !== false) {
|
|
2100
|
+
try {
|
|
2101
|
+
_filterUnmatchedChainOrders(mgr, chainOrderId);
|
|
2102
|
+
}
|
|
2103
|
+
catch { /* counting hygiene only */ }
|
|
2104
|
+
}
|
|
2064
2105
|
}
|
|
2065
2106
|
else {
|
|
2066
2107
|
// Unknown grid id: the broadcast landed but master no
|
|
@@ -2200,6 +2241,10 @@ class SyncEngine {
|
|
|
2200
2241
|
mgr.logger?.log?.(`[SYNC] createOrder linkage FAILED: grid order ${gridOrderId} not in master and materializing chain order ${chainOrderId} (${materializeType} @${materializePrice} x${descriptorSize}) was rejected — chain order left untracked`, 'error');
|
|
2201
2242
|
}
|
|
2202
2243
|
else {
|
|
2244
|
+
try {
|
|
2245
|
+
_filterUnmatchedChainOrders(mgr, chainOrderId);
|
|
2246
|
+
}
|
|
2247
|
+
catch { /* counting hygiene only */ }
|
|
2203
2248
|
mgr.logger?.log?.(`[SYNC] createOrder for unknown grid order ${gridOrderId}: materialized ${materializeType} @${materializePrice} x${descriptorSize} (price source: ${priceSource}) -> ${chainOrderId} (master lost the slot mid-broadcast)`, 'warn');
|
|
2204
2249
|
}
|
|
2205
2250
|
}
|
|
@@ -2244,7 +2289,7 @@ class SyncEngine {
|
|
|
2244
2289
|
const gridOrder = Array.from(mgr.orders.values()).find((o) => o && o.orderId === orderId);
|
|
2245
2290
|
if (gridOrder) {
|
|
2246
2291
|
// Lock both chain orderId and grid order ID to prevent concurrent modifications
|
|
2247
|
-
const orderIds = [orderId, gridOrder.id].filter(Boolean);
|
|
2292
|
+
const orderIds = [orderId, gridOrder.id].filter((x) => Boolean(x));
|
|
2248
2293
|
mgr.lockOrders(orderIds);
|
|
2249
2294
|
try {
|
|
2250
2295
|
// Re-fetch to ensure we have latest state after acquiring lock
|
|
@@ -2274,8 +2319,8 @@ class SyncEngine {
|
|
|
2274
2319
|
// CRITICAL: Even if order not in grid, the cancellation fee was still paid on blockchain
|
|
2275
2320
|
// Deduct it from account totals to prevent drift.
|
|
2276
2321
|
const btsSide = getBtsSide(mgr.config?.assetA, mgr.config?.assetB);
|
|
2277
|
-
if (btsSide && btsFeeData?.cancelFee > 0) {
|
|
2278
|
-
await mgr.accountant.adjustTotalBalance(btsSide, -btsFeeData
|
|
2322
|
+
if (btsSide && (btsFeeData?.cancelFee ?? 0) > 0) {
|
|
2323
|
+
await mgr.accountant.adjustTotalBalance(btsSide, -(btsFeeData?.cancelFee ?? 0), 'cancel-order-unmatched-fee');
|
|
2279
2324
|
}
|
|
2280
2325
|
}
|
|
2281
2326
|
};
|
|
@@ -2303,7 +2348,7 @@ class SyncEngine {
|
|
|
2303
2348
|
});
|
|
2304
2349
|
}
|
|
2305
2350
|
}
|
|
2306
|
-
return { newOrders: [], ordersNeedingCorrection: [] };
|
|
2351
|
+
return { newOrders: [], filledOrders: [], updatedOrders: [], ordersNeedingCorrection: [] };
|
|
2307
2352
|
}
|
|
2308
2353
|
/**
|
|
2309
2354
|
* Fetch account balances from blockchain and update optimistic fund totals.
|
|
@@ -2379,8 +2424,8 @@ class SyncEngine {
|
|
|
2379
2424
|
assetList.push(NATIVE_CLIENT.CHAIN.CORE_ASSET_ID);
|
|
2380
2425
|
}
|
|
2381
2426
|
const lookup = await chainOrders.getOnChainAssetBalances(accountIdOrName, assetList);
|
|
2382
|
-
const aInfo = lookup?.[assetAId] || lookup?.[mgr.config.assetA];
|
|
2383
|
-
const bInfo = lookup?.[assetBId] || lookup?.[mgr.config.assetB];
|
|
2427
|
+
const aInfo = lookup?.[assetAId] || lookup?.[String(mgr.config.assetA)];
|
|
2428
|
+
const bInfo = lookup?.[assetBId] || lookup?.[String(mgr.config.assetB)];
|
|
2384
2429
|
if (aInfo && bInfo) {
|
|
2385
2430
|
await mgr.setAccountTotals({ sell: aInfo.total, sellFree: aInfo.free, buy: bInfo.total, buyFree: bInfo.free });
|
|
2386
2431
|
}
|
|
@@ -2388,7 +2433,7 @@ class SyncEngine {
|
|
|
2388
2433
|
if (mgr.config.assetA !== 'BTS' && mgr.config.assetB !== 'BTS') {
|
|
2389
2434
|
const btsInfo = lookup?.[NATIVE_CLIENT.CHAIN.CORE_ASSET_ID];
|
|
2390
2435
|
if (btsInfo) {
|
|
2391
|
-
mgr.btsBalance = { free: btsInfo.free, total: btsInfo.total, locked: 0 };
|
|
2436
|
+
mgr.btsBalance = { free: btsInfo.free ?? 0, total: btsInfo.total ?? 0, locked: 0 };
|
|
2392
2437
|
}
|
|
2393
2438
|
}
|
|
2394
2439
|
}
|
|
@@ -2463,8 +2508,8 @@ class SyncEngine {
|
|
|
2463
2508
|
};
|
|
2464
2509
|
try {
|
|
2465
2510
|
mgr.assets = {
|
|
2466
|
-
assetA: await fetchAssetWithFallback(mgr.config.assetA, 'A'),
|
|
2467
|
-
assetB: await fetchAssetWithFallback(mgr.config.assetB, 'B')
|
|
2511
|
+
assetA: await fetchAssetWithFallback(mgr.config.assetA ?? '', 'A'),
|
|
2512
|
+
assetB: await fetchAssetWithFallback(mgr.config.assetB ?? '', 'B')
|
|
2468
2513
|
};
|
|
2469
2514
|
}
|
|
2470
2515
|
catch (err) {
|