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
|
@@ -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);
|
|
@@ -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) {
|
|
@@ -641,7 +648,7 @@ class SyncEngine {
|
|
|
641
648
|
? innerResult.unmatchedChainOrders.length
|
|
642
649
|
: 0;
|
|
643
650
|
mgr._lastUnmatchedChainOrders = unmatchedCount > 0
|
|
644
|
-
? innerResult.unmatchedChainOrders.map((order) => ({ ...order }))
|
|
651
|
+
? (innerResult.unmatchedChainOrders ?? []).map((order) => ({ ...order }))
|
|
645
652
|
: [];
|
|
646
653
|
mgr._lastUnmatchedChainOrdersAt = unmatchedCount > 0 ? Date.now() : 0;
|
|
647
654
|
mgr.logger?.log?.(`[SYNC] Synchronization complete: ${innerResult.filledOrders.length} filled, ` +
|
|
@@ -769,7 +776,7 @@ class SyncEngine {
|
|
|
769
776
|
if (parsedChainOrders.size === 0) {
|
|
770
777
|
const gridOrderIds = Array.from(mgr.orders.values()).filter((o) => o?.orderId).length;
|
|
771
778
|
if (gridOrderIds > 0) {
|
|
772
|
-
const suspect = mgr._suspectEmptyReads
|
|
779
|
+
const suspect = mgr._suspectEmptyReads ?? { count: 0, firstAt: 0 };
|
|
773
780
|
suspect.count += 1;
|
|
774
781
|
if (!suspect.firstAt)
|
|
775
782
|
suspect.firstAt = Date.now();
|
|
@@ -893,7 +900,7 @@ class SyncEngine {
|
|
|
893
900
|
* @returns {Promise<any>}
|
|
894
901
|
*/
|
|
895
902
|
async _performSyncFromOpenOrders(mgr, assetAPrecision, assetBPrecision, parsedChainOrders, rawChainOrders, chainOrderIdsOnGrid, matchedGridOrderIds, filledOrders, updatedOrders, ordersNeedingCorrection, unmatchedChainOrders, options) {
|
|
896
|
-
const skipAccounting = options?.skipAccounting ?? true;
|
|
903
|
+
const skipAccounting = (options?.skipAccounting ?? true);
|
|
897
904
|
const queueCorrection = (entry) => {
|
|
898
905
|
// Provenance: classify the detector so a stale replay at drain
|
|
899
906
|
// time logs who queued it and when. Classification from entry
|
|
@@ -927,6 +934,8 @@ class SyncEngine {
|
|
|
927
934
|
for (const gridOrder of mgr.orders.values()) {
|
|
928
935
|
if (gridOrder.orderId && parsedChainOrders.has(gridOrder.orderId)) {
|
|
929
936
|
const chainOrder = parsedChainOrders.get(gridOrder.orderId);
|
|
937
|
+
if (!chainOrder)
|
|
938
|
+
continue;
|
|
930
939
|
let updatedOrder = { ...gridOrder };
|
|
931
940
|
chainOrderIdsOnGrid.add(gridOrder.orderId);
|
|
932
941
|
// Store raw blockchain data in grid slot for later update calculation.
|
|
@@ -1026,12 +1035,13 @@ class SyncEngine {
|
|
|
1026
1035
|
// pass-2 adoption path below: deferred_fee > 0 → fee
|
|
1027
1036
|
// state; deferred_fee === 0 with for_sale > 0 → the
|
|
1028
1037
|
// order was partially filled).
|
|
1029
|
-
const
|
|
1038
|
+
const reboundRaw = reboundOrder.rawOnChain;
|
|
1039
|
+
const rawDeferredFee = toFiniteNumber(reboundRaw?.deferred_fee, null);
|
|
1030
1040
|
if (rawDeferredFee !== null && rawDeferredFee > 0) {
|
|
1031
1041
|
reboundOrder.btsFeeState = { deferredFee: blockchainToFloat(rawDeferredFee, BTS_PRECISION) };
|
|
1032
1042
|
}
|
|
1033
1043
|
else if (rawDeferredFee !== null && rawDeferredFee <= 0
|
|
1034
|
-
&& toFiniteNumber(
|
|
1044
|
+
&& toFiniteNumber(reboundRaw?.for_sale, 0) > 0) {
|
|
1035
1045
|
reboundOrder.state = ORDER_STATES.PARTIAL;
|
|
1036
1046
|
}
|
|
1037
1047
|
const applied = await mgr._applyOrderUpdate(reboundOrder, 'sync-pass1-duplicate-swap', { skipAccounting: skipAccounting, fee: 0 });
|
|
@@ -1128,7 +1138,7 @@ class SyncEngine {
|
|
|
1128
1138
|
// at 3s each). Prevents permanent stall when a fill event was missed
|
|
1129
1139
|
// (reconnect gap, lossy subscription) and the only detection path is
|
|
1130
1140
|
// this open-orders sync.
|
|
1131
|
-
if (mgr._committedOrderIds?.has(gridOrder.orderId)) {
|
|
1141
|
+
if (gridOrder.orderId != null && mgr._committedOrderIds?.has(gridOrder.orderId)) {
|
|
1132
1142
|
const commitAge = Date.now() - (mgr._committedOrderIdsBuiltAt || 0);
|
|
1133
1143
|
const isGhost = gridOrder.size <= 0 && gridOrder.state === ORDER_STATES.PARTIAL;
|
|
1134
1144
|
if (!isGhost && commitAge < TIMING.SYNC_LOCK_TIMEOUT_MS) {
|
|
@@ -1167,13 +1177,14 @@ class SyncEngine {
|
|
|
1167
1177
|
// PASS 2: CHAIN → GRID - Nearest-slot deterministic adoption (genesis-frozen)
|
|
1168
1178
|
// ====================================================================
|
|
1169
1179
|
const genesis = mgr._genesis;
|
|
1180
|
+
const genesisLadder = genesis;
|
|
1170
1181
|
// Genesis is mandatory for any populated grid, but an EMPTY grid
|
|
1171
1182
|
// (slotCount 0) passes the E2 gate without a ladder, so the
|
|
1172
1183
|
// `!hasGenesis` branch below is reachable when live chain orders exist
|
|
1173
1184
|
// against no slots. There the anchor is meaningless and only orders the
|
|
1174
1185
|
// deferred holds (every price is measured against 0, i.e. ascending).
|
|
1175
1186
|
const hasGenesis = hasGenesisLadder(genesis);
|
|
1176
|
-
const anchorPrice = hasGenesis ? genesis
|
|
1187
|
+
const anchorPrice = hasGenesis ? (genesis?.startPrice ?? 0) : 0;
|
|
1177
1188
|
const sortedChainEntries = [...parsedChainOrders.entries()].sort((a, b) => {
|
|
1178
1189
|
const pa = toFiniteNumber(a[1].price);
|
|
1179
1190
|
const pb = toFiniteNumber(b[1].price);
|
|
@@ -1200,7 +1211,7 @@ class SyncEngine {
|
|
|
1200
1211
|
}
|
|
1201
1212
|
let idx;
|
|
1202
1213
|
try {
|
|
1203
|
-
idx = slotIndexForPrice(chainOrder.price,
|
|
1214
|
+
idx = slotIndexForPrice(chainOrder.price, genesisLadder);
|
|
1204
1215
|
}
|
|
1205
1216
|
catch {
|
|
1206
1217
|
unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'no-available-nearest-slot' });
|
|
@@ -1217,13 +1228,13 @@ class SyncEngine {
|
|
|
1217
1228
|
// sitting below a fresh grid after a reset.
|
|
1218
1229
|
{
|
|
1219
1230
|
const precision = (chainOrder.type === ORDER_TYPES.SELL) ? assetAPrecision : assetBPrecision;
|
|
1220
|
-
if (isChainPriceOutOfGrid(chainOrder.price,
|
|
1231
|
+
if (isChainPriceOutOfGrid(chainOrder.price, genesisLadder, precision)) {
|
|
1221
1232
|
unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'out-of-grid-deferred', candidateSlotId: slotId });
|
|
1222
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');
|
|
1223
1234
|
continue;
|
|
1224
1235
|
}
|
|
1225
1236
|
}
|
|
1226
|
-
const gapSlots = genesis
|
|
1237
|
+
const gapSlots = genesis?.gapSlots ?? mgr._gapSlots ?? 0;
|
|
1227
1238
|
const boundaryIdx = mgr.boundaryIdx;
|
|
1228
1239
|
// Pre-boundary sync: gap geometry is unknown, so adoption is
|
|
1229
1240
|
// deferred entirely — touch nothing (no adopt, no cancelOnly).
|
|
@@ -1293,6 +1304,9 @@ class SyncEngine {
|
|
|
1293
1304
|
return null;
|
|
1294
1305
|
}
|
|
1295
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');
|
|
1296
1310
|
// A SPREAD slot can carry an on-chain order (e.g. spread-correction
|
|
1297
1311
|
// activation). Resolve the real side from the fill's pays asset so the
|
|
1298
1312
|
// transition result is BUY/SELL — never SPREAD with an on-chain state,
|
|
@@ -1302,22 +1316,22 @@ class SyncEngine {
|
|
|
1302
1316
|
// into a fill result (which would drop the boundary shift downstream).
|
|
1303
1317
|
let orderType = matchedGridOrder.type;
|
|
1304
1318
|
if (orderType === ORDER_TYPES.SPREAD) {
|
|
1305
|
-
if (paysAssetId ===
|
|
1319
|
+
if (paysAssetId === assets.assetB.id)
|
|
1306
1320
|
orderType = ORDER_TYPES.BUY;
|
|
1307
|
-
else if (paysAssetId ===
|
|
1321
|
+
else if (paysAssetId === assets.assetA.id)
|
|
1308
1322
|
orderType = ORDER_TYPES.SELL;
|
|
1309
1323
|
else
|
|
1310
1324
|
orderType = resolveSpreadOrderSide(matchedGridOrder.price, mgr.config.startPrice);
|
|
1311
1325
|
}
|
|
1312
1326
|
const currentSize = toFiniteNumber(matchedGridOrder.size);
|
|
1313
|
-
const precision = (orderType === ORDER_TYPES.SELL) ?
|
|
1327
|
+
const precision = (orderType === ORDER_TYPES.SELL) ? assets.assetA.precision : assets.assetB.precision;
|
|
1314
1328
|
let filledAmount = 0;
|
|
1315
1329
|
if (orderType === ORDER_TYPES.SELL) {
|
|
1316
|
-
if (paysAssetId ===
|
|
1330
|
+
if (paysAssetId === assets.assetA.id)
|
|
1317
1331
|
filledAmount = blockchainToFloat(paysAmountRaw, precision);
|
|
1318
1332
|
}
|
|
1319
1333
|
else {
|
|
1320
|
-
if (paysAssetId ===
|
|
1334
|
+
if (paysAssetId === assets.assetB.id)
|
|
1321
1335
|
filledAmount = blockchainToFloat(paysAmountRaw, precision);
|
|
1322
1336
|
}
|
|
1323
1337
|
const currentSizeIntFromGrid = floatToBlockchainInt(currentSize, precision);
|
|
@@ -1355,7 +1369,8 @@ class SyncEngine {
|
|
|
1355
1369
|
// sweep it.
|
|
1356
1370
|
let residualCancel = null;
|
|
1357
1371
|
if (!isEffectivelyFull) {
|
|
1358
|
-
const
|
|
1372
|
+
const assets = mgr.assets;
|
|
1373
|
+
const otherPrecision = (orderType === ORDER_TYPES.SELL) ? assets.assetB.precision : assets.assetA.precision;
|
|
1359
1374
|
const otherSidePrice = matchedGridOrder.price;
|
|
1360
1375
|
const otherSize = (orderType === ORDER_TYPES.SELL) ? newSize * otherSidePrice : newSize / otherSidePrice;
|
|
1361
1376
|
if (floatToBlockchainInt(otherSize, otherPrecision) <= 0) {
|
|
@@ -1387,7 +1402,7 @@ class SyncEngine {
|
|
|
1387
1402
|
}
|
|
1388
1403
|
else {
|
|
1389
1404
|
try {
|
|
1390
|
-
const residualOrder = await readSingleOrderSeam(mgr, matchedGridOrder.orderId, 3000);
|
|
1405
|
+
const residualOrder = await readSingleOrderSeam(mgr, matchedGridOrder.orderId ?? '', 3000);
|
|
1391
1406
|
residualForSale = residualOrder ? toFiniteNumber(residualOrder.for_sale, null) : null;
|
|
1392
1407
|
}
|
|
1393
1408
|
catch (residualErr) {
|
|
@@ -1396,7 +1411,7 @@ class SyncEngine {
|
|
|
1396
1411
|
// authoritative fill transition.
|
|
1397
1412
|
mgr.logger.log(`[SYNC] Order ${matchedGridOrder.orderId} (slot ${matchedGridOrder.id}) other-side (${otherSize}) rounds to 0. ` +
|
|
1398
1413
|
`Fill is authoritative: treating as full fill for rotation. Residual verification read failed (${getErrorMessage(residualErr)}); ` +
|
|
1399
|
-
`relying on reconciliation for
|
|
1414
|
+
`relying on reconciliation for residuals.`, 'warn');
|
|
1400
1415
|
}
|
|
1401
1416
|
}
|
|
1402
1417
|
if (Number.isFinite(residualForSale) && Math.round(residualForSale) > 0) {
|
|
@@ -1477,6 +1492,10 @@ class SyncEngine {
|
|
|
1477
1492
|
const blockNum = fill.block_num;
|
|
1478
1493
|
const historyId = fill.id;
|
|
1479
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
|
+
}
|
|
1480
1499
|
if (fillOp.is_maker === undefined) {
|
|
1481
1500
|
mgr.logger.log(`[SYNC] is_maker flag missing from fill data for order ${orderId}; defaulting to maker`, 'warn');
|
|
1482
1501
|
}
|
|
@@ -1549,7 +1568,7 @@ class SyncEngine {
|
|
|
1549
1568
|
}
|
|
1550
1569
|
}
|
|
1551
1570
|
catch (refetchErr) {
|
|
1552
|
-
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');
|
|
1553
1572
|
}
|
|
1554
1573
|
}
|
|
1555
1574
|
const result = await this._computeFillTransitionResult(mgr, {
|
|
@@ -1669,7 +1688,7 @@ class SyncEngine {
|
|
|
1669
1688
|
return { filledOrders: [], updatedOrders: [], partialFill: false, requiresOpenOrdersSync: anyRequiresSync };
|
|
1670
1689
|
}
|
|
1671
1690
|
// Phase 2: Lock all unique order IDs once
|
|
1672
|
-
const allOrderIds = [...new Set(fillEntries.map(e => e.orderId))];
|
|
1691
|
+
const allOrderIds = [...new Set(fillEntries.map(e => e.orderId))].filter((id) => typeof id === 'string');
|
|
1673
1692
|
// Raise the fill-batch in-flight guard BEFORE the accountTotals refresh.
|
|
1674
1693
|
// The refresh fetches post-fill balances, but the grid still holds the
|
|
1675
1694
|
// filled orders as committed until the batch's grid mutation (Phase 7),
|
|
@@ -1727,7 +1746,7 @@ class SyncEngine {
|
|
|
1727
1746
|
}
|
|
1728
1747
|
const ctx = this._computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw);
|
|
1729
1748
|
mgr.logger.log(`[SYNC] Order ${orderId} (${ctx.orderType}) currentSize=${ctx.currentSize}, filledAmount=${ctx.filledAmount}`, 'debug');
|
|
1730
|
-
if (ctx.driftSignal) {
|
|
1749
|
+
if (ctx.driftSignal && orderId) {
|
|
1731
1750
|
driftOrderIds.add(orderId);
|
|
1732
1751
|
}
|
|
1733
1752
|
entryContexts.push({
|
|
@@ -1781,7 +1800,7 @@ class SyncEngine {
|
|
|
1781
1800
|
}
|
|
1782
1801
|
}
|
|
1783
1802
|
catch (refetchErr) {
|
|
1784
|
-
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');
|
|
1785
1804
|
}
|
|
1786
1805
|
}
|
|
1787
1806
|
// Phase 6: Compute state transitions and collect grid updates.
|
|
@@ -1822,7 +1841,7 @@ class SyncEngine {
|
|
|
1822
1841
|
if (group.length > 1) {
|
|
1823
1842
|
mgr.logger.log(`[SYNC] Aggregated ${group.length} fill(s) for order ${orderId} (slot ${matchedGridOrder.id}): total filled=${totalFilledAmount}`, 'debug');
|
|
1824
1843
|
}
|
|
1825
|
-
const refetchInfo = refetchMap.get(orderId);
|
|
1844
|
+
const refetchInfo = refetchMap.get(orderId ?? '');
|
|
1826
1845
|
const chainRefetched = refetchInfo?.chainRefetched || false;
|
|
1827
1846
|
const chainConfirmsEmpty = refetchInfo?.chainConfirmsEmpty || false;
|
|
1828
1847
|
const effectiveRawForSale = refetchInfo?.effectiveRawForSale != null ? refetchInfo.effectiveRawForSale : rawForSaleInt;
|
|
@@ -1843,14 +1862,14 @@ class SyncEngine {
|
|
|
1843
1862
|
});
|
|
1844
1863
|
if (result.isFull) {
|
|
1845
1864
|
mgr.logger.log(`[SYNC] Full fill for order ${orderId} (slot ${matchedGridOrder.id}).`, 'info');
|
|
1846
|
-
gridUpdates.push({ id: matchedGridOrder.id,
|
|
1865
|
+
gridUpdates.push({ ...result.fullUpdate, id: matchedGridOrder.id, context: 'handle-fill-full' });
|
|
1847
1866
|
filledOrders.push(result.filledOrder);
|
|
1848
1867
|
if (result.residualCancel)
|
|
1849
1868
|
residualCancels.push(result.residualCancel);
|
|
1850
1869
|
}
|
|
1851
1870
|
else {
|
|
1852
1871
|
mgr.logger.log(`[SYNC] Partial fill for order ${orderId} (slot ${matchedGridOrder.id}): newSize=${result.newSize}`, 'info');
|
|
1853
|
-
gridUpdates.push({ id: matchedGridOrder.id,
|
|
1872
|
+
gridUpdates.push({ ...result.partialUpdate, id: matchedGridOrder.id, context: 'handle-fill-partial' });
|
|
1854
1873
|
updatedOrders.push(result.partialUpdate);
|
|
1855
1874
|
filledOrders.push(result.filledOrder);
|
|
1856
1875
|
anyPartialFill = true;
|
|
@@ -1962,14 +1981,14 @@ class SyncEngine {
|
|
|
1962
1981
|
*
|
|
1963
1982
|
* Non-throwing on purpose: the load-side gates (E1/E3) own the fail-closed
|
|
1964
1983
|
* decision, this one makes a bypass loud without stranding a live manager.
|
|
1965
|
-
* @param {
|
|
1984
|
+
* @param {unknown} mgr - OrderManager instance
|
|
1966
1985
|
* @returns {boolean} true when the grid may be synced (no slots, or a usable
|
|
1967
1986
|
* ladder is present); false when the sync must not run.
|
|
1968
1987
|
*/
|
|
1969
1988
|
_assertGenesisInvariant(mgr) {
|
|
1970
1989
|
try {
|
|
1971
1990
|
const orders = mgr?.orders;
|
|
1972
|
-
const slotCount = orders instanceof Map ? orders.size :
|
|
1991
|
+
const slotCount = orders instanceof Map ? orders.size : 0;
|
|
1973
1992
|
if (slotCount === 0)
|
|
1974
1993
|
return true;
|
|
1975
1994
|
if (hasGenesisLadder(mgr._genesis))
|
|
@@ -2001,7 +2020,7 @@ class SyncEngine {
|
|
|
2001
2020
|
async synchronizeWithChain(chainData, source) {
|
|
2002
2021
|
const mgr = this.manager;
|
|
2003
2022
|
if (!mgr.assets)
|
|
2004
|
-
return { newOrders: [], ordersNeedingCorrection: [] };
|
|
2023
|
+
return { newOrders: [], filledOrders: [], updatedOrders: [], ordersNeedingCorrection: [] };
|
|
2005
2024
|
switch (source) {
|
|
2006
2025
|
case 'createOrder': {
|
|
2007
2026
|
const { gridOrderId, chainOrderId, isPartialPlacement, expectedType, fee } = chainData;
|
|
@@ -2055,7 +2074,7 @@ class SyncEngine {
|
|
|
2055
2074
|
...gridOrder,
|
|
2056
2075
|
type: normalizedExpectedType || gridOrder.type,
|
|
2057
2076
|
state: newState,
|
|
2058
|
-
orderId: chainOrderId,
|
|
2077
|
+
orderId: chainOrderId ?? null,
|
|
2059
2078
|
};
|
|
2060
2079
|
// Restore btsFeeState from raw chain order data if provided.
|
|
2061
2080
|
// After a grid reset, in-memory orders have no fee state but the
|
|
@@ -2067,10 +2086,22 @@ class SyncEngine {
|
|
|
2067
2086
|
}
|
|
2068
2087
|
// Deduced fee (createFee or updateFee) must always be applied to reflect blockchain cost
|
|
2069
2088
|
const actualFee = fee;
|
|
2070
|
-
await mgr._applyOrderUpdate(updatedOrder, 'fill-place', {
|
|
2089
|
+
const linked = await mgr._applyOrderUpdate(updatedOrder, 'fill-place', {
|
|
2071
2090
|
skipAccounting: chainData.skipAccounting || false,
|
|
2072
2091
|
fee: actualFee
|
|
2073
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
|
+
}
|
|
2074
2105
|
}
|
|
2075
2106
|
else {
|
|
2076
2107
|
// Unknown grid id: the broadcast landed but master no
|
|
@@ -2258,7 +2289,7 @@ class SyncEngine {
|
|
|
2258
2289
|
const gridOrder = Array.from(mgr.orders.values()).find((o) => o && o.orderId === orderId);
|
|
2259
2290
|
if (gridOrder) {
|
|
2260
2291
|
// Lock both chain orderId and grid order ID to prevent concurrent modifications
|
|
2261
|
-
const orderIds = [orderId, gridOrder.id].filter(Boolean);
|
|
2292
|
+
const orderIds = [orderId, gridOrder.id].filter((x) => Boolean(x));
|
|
2262
2293
|
mgr.lockOrders(orderIds);
|
|
2263
2294
|
try {
|
|
2264
2295
|
// Re-fetch to ensure we have latest state after acquiring lock
|
|
@@ -2288,8 +2319,8 @@ class SyncEngine {
|
|
|
2288
2319
|
// CRITICAL: Even if order not in grid, the cancellation fee was still paid on blockchain
|
|
2289
2320
|
// Deduct it from account totals to prevent drift.
|
|
2290
2321
|
const btsSide = getBtsSide(mgr.config?.assetA, mgr.config?.assetB);
|
|
2291
|
-
if (btsSide && btsFeeData?.cancelFee > 0) {
|
|
2292
|
-
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');
|
|
2293
2324
|
}
|
|
2294
2325
|
}
|
|
2295
2326
|
};
|
|
@@ -2317,7 +2348,7 @@ class SyncEngine {
|
|
|
2317
2348
|
});
|
|
2318
2349
|
}
|
|
2319
2350
|
}
|
|
2320
|
-
return { newOrders: [], ordersNeedingCorrection: [] };
|
|
2351
|
+
return { newOrders: [], filledOrders: [], updatedOrders: [], ordersNeedingCorrection: [] };
|
|
2321
2352
|
}
|
|
2322
2353
|
/**
|
|
2323
2354
|
* Fetch account balances from blockchain and update optimistic fund totals.
|
|
@@ -2393,8 +2424,8 @@ class SyncEngine {
|
|
|
2393
2424
|
assetList.push(NATIVE_CLIENT.CHAIN.CORE_ASSET_ID);
|
|
2394
2425
|
}
|
|
2395
2426
|
const lookup = await chainOrders.getOnChainAssetBalances(accountIdOrName, assetList);
|
|
2396
|
-
const aInfo = lookup?.[assetAId] || lookup?.[mgr.config.assetA];
|
|
2397
|
-
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)];
|
|
2398
2429
|
if (aInfo && bInfo) {
|
|
2399
2430
|
await mgr.setAccountTotals({ sell: aInfo.total, sellFree: aInfo.free, buy: bInfo.total, buyFree: bInfo.free });
|
|
2400
2431
|
}
|
|
@@ -2402,7 +2433,7 @@ class SyncEngine {
|
|
|
2402
2433
|
if (mgr.config.assetA !== 'BTS' && mgr.config.assetB !== 'BTS') {
|
|
2403
2434
|
const btsInfo = lookup?.[NATIVE_CLIENT.CHAIN.CORE_ASSET_ID];
|
|
2404
2435
|
if (btsInfo) {
|
|
2405
|
-
mgr.btsBalance = { free: btsInfo.free, total: btsInfo.total, locked: 0 };
|
|
2436
|
+
mgr.btsBalance = { free: btsInfo.free ?? 0, total: btsInfo.total ?? 0, locked: 0 };
|
|
2406
2437
|
}
|
|
2407
2438
|
}
|
|
2408
2439
|
}
|
|
@@ -2477,8 +2508,8 @@ class SyncEngine {
|
|
|
2477
2508
|
};
|
|
2478
2509
|
try {
|
|
2479
2510
|
mgr.assets = {
|
|
2480
|
-
assetA: await fetchAssetWithFallback(mgr.config.assetA, 'A'),
|
|
2481
|
-
assetB: await fetchAssetWithFallback(mgr.config.assetB, 'B')
|
|
2511
|
+
assetA: await fetchAssetWithFallback(mgr.config.assetA ?? '', 'A'),
|
|
2512
|
+
assetB: await fetchAssetWithFallback(mgr.config.assetB ?? '', 'B')
|
|
2482
2513
|
};
|
|
2483
2514
|
}
|
|
2484
2515
|
catch (err) {
|