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
|
@@ -75,7 +75,7 @@ import * as Format from '../format.js';
|
|
|
75
75
|
import * as MathUtils from './math.js';
|
|
76
76
|
import Logger from '../../order/logger.js';
|
|
77
77
|
import { sleep } from './system.js';
|
|
78
|
-
import { getErrorMessage } from '../../utils/errors.js';
|
|
78
|
+
import { getErrorMessage, getErrorCode, getErrorName } from '../../utils/errors.js';
|
|
79
79
|
import { hasGenesisLadder } from '../genesis_policy.js';
|
|
80
80
|
import { parseSlotIndex as parseSlotIndexShared } from './slot.js';
|
|
81
81
|
const { isValidNumber, toFiniteNumber } = Format;
|
|
@@ -202,7 +202,7 @@ function _filterUnmatchedChainOrders(manager, chainOrderId) {
|
|
|
202
202
|
* Record a fresh on-chain placement timestamp for surplus-cancel grace.
|
|
203
203
|
* Called when a slot gains a chain orderId it did not have before (create,
|
|
204
204
|
* adopt, rotation target). Powers isFreshlyPlacedOrder below.
|
|
205
|
-
* @param {
|
|
205
|
+
* @param {unknown} manager - OrderManager instance (owns `_placedAt`)
|
|
206
206
|
* @param {string} chainOrderId - Chain order id that was just placed
|
|
207
207
|
*/
|
|
208
208
|
function recordOrderPlacement(manager, chainOrderId) {
|
|
@@ -228,7 +228,7 @@ function recordOrderPlacement(manager, chainOrderId) {
|
|
|
228
228
|
* window. Surplus sweeps must skip such orders: a fill landing between two
|
|
229
229
|
* controllers' count snapshots otherwise makes the second cancel what the
|
|
230
230
|
* first just placed (fee bleed + empty levels, no net change).
|
|
231
|
-
* @param {
|
|
231
|
+
* @param {unknown} manager - OrderManager instance
|
|
232
232
|
* @param {string} chainOrderId - Chain order id to test
|
|
233
233
|
* @param {number} [graceMs] - Override grace window (defaults to TIMING.SURPLUS_CANCEL_GRACE_MS)
|
|
234
234
|
* @returns {boolean} True while the order is still inside its grace window
|
|
@@ -398,7 +398,7 @@ function _validatePriceCorrectionEntry(manager, entry) {
|
|
|
398
398
|
if (!hasGenesisLadder(manager?._genesis)) {
|
|
399
399
|
return { valid: false, reason: `no price ladder (INV-GRID-004) — slot ${slotId} has no authoritative price` };
|
|
400
400
|
}
|
|
401
|
-
if (!priceSlotEqual(slot.price, entry.expectedPrice, precision)) {
|
|
401
|
+
if (!priceSlotEqual(slot.price, Number(entry.expectedPrice), Number(precision))) {
|
|
402
402
|
return { valid: false, reason: `slot ${slotId} now targets ${slot.price} (entry queued ${entry.expectedPrice})` };
|
|
403
403
|
}
|
|
404
404
|
// Size check: the broadcast sends amountToSell from the QUEUED snapshot.
|
|
@@ -436,7 +436,7 @@ function parseChainOrder(chainOrder, assets) {
|
|
|
436
436
|
if (!chainOrder || !chainOrder.sell_price || !assets)
|
|
437
437
|
return null;
|
|
438
438
|
const { base, quote } = chainOrder.sell_price;
|
|
439
|
-
if (!base || !quote || !base.asset_id || !quote.asset_id || base.amount === 0)
|
|
439
|
+
if (!base || !quote || !base.asset_id || !quote.asset_id || toFiniteNumber(base.amount) === 0)
|
|
440
440
|
return null;
|
|
441
441
|
let price;
|
|
442
442
|
let type;
|
|
@@ -444,16 +444,18 @@ function parseChainOrder(chainOrder, assets) {
|
|
|
444
444
|
const scaleFactor = precisionDelta >= 0
|
|
445
445
|
? Math.pow(10, precisionDelta)
|
|
446
446
|
: Math.pow(10, Math.abs(precisionDelta));
|
|
447
|
+
const baseAmount = toFiniteNumber(base.amount);
|
|
448
|
+
const quoteAmount = toFiniteNumber(quote.amount);
|
|
447
449
|
if (base.asset_id === assets.assetA.id && quote.asset_id === assets.assetB.id) {
|
|
448
450
|
price = precisionDelta >= 0
|
|
449
|
-
? (
|
|
450
|
-
: (
|
|
451
|
+
? (quoteAmount / baseAmount) * scaleFactor
|
|
452
|
+
: (quoteAmount / baseAmount) / scaleFactor;
|
|
451
453
|
type = ORDER_TYPES.SELL;
|
|
452
454
|
}
|
|
453
455
|
else if (base.asset_id === assets.assetB.id && quote.asset_id === assets.assetA.id) {
|
|
454
456
|
price = precisionDelta >= 0
|
|
455
|
-
? (
|
|
456
|
-
: (
|
|
457
|
+
? (baseAmount / quoteAmount) * scaleFactor
|
|
458
|
+
: (baseAmount / quoteAmount) / scaleFactor;
|
|
457
459
|
type = ORDER_TYPES.BUY;
|
|
458
460
|
}
|
|
459
461
|
else
|
|
@@ -534,7 +536,9 @@ function _currentCorrectionGridOrder(manager, correctionInfo) {
|
|
|
534
536
|
if (!slotId || !(manager?.orders instanceof Map))
|
|
535
537
|
return null;
|
|
536
538
|
const liveSlot = manager.orders.get(slotId);
|
|
537
|
-
|
|
539
|
+
if (!liveSlot || liveSlot.orderId !== correctionInfo?.chainOrderId)
|
|
540
|
+
return null;
|
|
541
|
+
return liveSlot;
|
|
538
542
|
}
|
|
539
543
|
/**
|
|
540
544
|
* Correct a single order's price on blockchain.
|
|
@@ -551,6 +555,11 @@ function _currentCorrectionGridOrder(manager, correctionInfo) {
|
|
|
551
555
|
*/
|
|
552
556
|
async function correctOrderPriceOnChain(manager, correctionInfo, accountName, privateKey, accountOrders) {
|
|
553
557
|
const { gridOrder, chainOrderId, expectedPrice, size, type, isSurplus, cancelOnly } = correctionInfo;
|
|
558
|
+
if (!chainOrderId)
|
|
559
|
+
return { success: false, error: 'missing chainOrderId' };
|
|
560
|
+
const expectedPriceNum = Number(expectedPrice);
|
|
561
|
+
const sizeNum = Number(size);
|
|
562
|
+
const typeStr = type == null ? '' : String(type);
|
|
554
563
|
const stillNeeded = manager.ordersNeedingPriceCorrection?.some((c) => c.chainOrderId === chainOrderId);
|
|
555
564
|
if (!stillNeeded)
|
|
556
565
|
return { success: true, skipped: true };
|
|
@@ -628,12 +637,12 @@ async function correctOrderPriceOnChain(manager, correctionInfo, accountName, pr
|
|
|
628
637
|
}
|
|
629
638
|
let amountToSell, minToReceive;
|
|
630
639
|
if (type === ORDER_TYPES.SELL) {
|
|
631
|
-
amountToSell =
|
|
632
|
-
minToReceive =
|
|
640
|
+
amountToSell = sizeNum;
|
|
641
|
+
minToReceive = sizeNum * expectedPriceNum;
|
|
633
642
|
}
|
|
634
643
|
else {
|
|
635
|
-
amountToSell =
|
|
636
|
-
minToReceive =
|
|
644
|
+
amountToSell = sizeNum;
|
|
645
|
+
minToReceive = sizeNum / expectedPriceNum;
|
|
637
646
|
}
|
|
638
647
|
let shouldRemove = false;
|
|
639
648
|
// CROSSING-PLACEMENT GUARD: re-pricing the chain order to its slot's
|
|
@@ -644,9 +653,9 @@ async function correctOrderPriceOnChain(manager, correctionInfo, accountName, pr
|
|
|
644
653
|
// the next sync's price-mismatch detection re-queues the correction
|
|
645
654
|
// once the crossed order is resolved (same lifecycle as a 'skipped'
|
|
646
655
|
// update below).
|
|
647
|
-
const crossed = MathUtils.findCrossedOrder(buildCrossingCheckCandidates(manager),
|
|
656
|
+
const crossed = MathUtils.findCrossedOrder(buildCrossingCheckCandidates(manager), expectedPriceNum, typeStr, manager.assets, (o) => isCrossingCheckCandidate(o, chainOrderId));
|
|
648
657
|
if (crossed) {
|
|
649
|
-
manager.logger?.log?.(`[CROSS-GUARD] Skipping price correction for ${chainOrderId} -> ${
|
|
658
|
+
manager.logger?.log?.(`[CROSS-GUARD] Skipping price correction for ${chainOrderId} -> ${typeStr} @${expectedPriceNum}: ` +
|
|
650
659
|
`crosses live ${crossed.type} ${crossed.id} (${crossed.orderId}) @${crossed.price}; ` +
|
|
651
660
|
`retried after the crossed order resolves.`, 'warn');
|
|
652
661
|
// The guard returns before the try/finally below, so drop the entry
|
|
@@ -676,7 +685,7 @@ async function correctOrderPriceOnChain(manager, correctionInfo, accountName, pr
|
|
|
676
685
|
shouldRemove = true;
|
|
677
686
|
_filterUnmatchedChainOrders(manager, chainOrderId);
|
|
678
687
|
}
|
|
679
|
-
else if (error
|
|
688
|
+
else if (getErrorCode(error) === 'BROADCAST_UNCERTAIN' || getErrorName(error) === 'BroadcastUncertainError') {
|
|
680
689
|
// Uncertain update: the delta may have landed. Re-applying the same
|
|
681
690
|
// delta on a later (possibly lagging) read would double-shrink the
|
|
682
691
|
// order. Drop the entry instead of re-queueing blindly — the next
|
|
@@ -702,6 +711,8 @@ async function correctOrderPriceOnChain(manager, correctionInfo, accountName, pr
|
|
|
702
711
|
*/
|
|
703
712
|
async function _resolveCancelledCorrection(manager, entry) {
|
|
704
713
|
const chainOrderId = entry.chainOrderId;
|
|
714
|
+
if (!chainOrderId)
|
|
715
|
+
return;
|
|
705
716
|
if (entry.cancelOnly) {
|
|
706
717
|
clearDuplicateOrphanDetection(chainOrderId);
|
|
707
718
|
}
|
|
@@ -786,7 +797,7 @@ async function _batchCancelCorrections(manager, entries, accountName, privateKey
|
|
|
786
797
|
catch (err) {
|
|
787
798
|
// Op construction failed (e.g. account resolution): fall back entirely.
|
|
788
799
|
logger?.log?.(`[CORRECTION] Batch cancel build failed (${presentIds.length} order(s)): ${getErrorMessage(err)}; falling back to serial cancels`, 'warn');
|
|
789
|
-
return { corrected, failed, unresolved: entries.filter((e) => presentIds.includes(e.chainOrderId)) };
|
|
800
|
+
return { corrected, failed, unresolved: entries.filter((e) => e.chainOrderId != null && presentIds.includes(e.chainOrderId)) };
|
|
790
801
|
}
|
|
791
802
|
const configuredMax = Number(COW_PERFORMANCE?.MAX_CANCELS_PER_BROADCAST);
|
|
792
803
|
const maxCancels = Number.isFinite(configuredMax) && configuredMax >= 1 ? Math.floor(configuredMax) : 1;
|
|
@@ -842,7 +853,7 @@ async function _batchCancelCorrections(manager, entries, accountName, privateKey
|
|
|
842
853
|
* cannot hold _gridLock (no acquisition timeout) for minutes. Reads the bot
|
|
843
854
|
* config override first, then the frozen default. Non-finite/non-positive
|
|
844
855
|
* falls back to the frozen default, then to 4000ms.
|
|
845
|
-
* @param {
|
|
856
|
+
* @param {unknown} manager
|
|
846
857
|
* @returns {number} Positive hold budget in milliseconds
|
|
847
858
|
*/
|
|
848
859
|
function resolveCorrectionHoldBudget(manager) {
|
|
@@ -858,7 +869,7 @@ function resolveCorrectionHoldBudget(manager) {
|
|
|
858
869
|
* on top of the hold-time budget: unset (null/undefined/non-finite) means no
|
|
859
870
|
* count cap and the elapsed-time budget alone governs; a finite value >= 0 is
|
|
860
871
|
* honored verbatim (0 intentionally drains no updates this cycle).
|
|
861
|
-
* @param {
|
|
872
|
+
* @param {unknown} manager
|
|
862
873
|
* @returns {number} Finite cap, or Infinity when uncapped
|
|
863
874
|
*/
|
|
864
875
|
function resolveCorrectionMaxUpdates(manager) {
|
|
@@ -871,10 +882,28 @@ function resolveCorrectionMaxUpdates(manager) {
|
|
|
871
882
|
return Math.floor(n);
|
|
872
883
|
return Infinity;
|
|
873
884
|
}
|
|
885
|
+
/**
|
|
886
|
+
* Resolve the inter-op delay between successive correction broadcasts.
|
|
887
|
+
* Reads the bot config override first, then the frozen default, falling back
|
|
888
|
+
* to TIMING.SYNC_DELAY_MS. A finite value >= 0 is honored verbatim (0 lets
|
|
889
|
+
* tests drive the drain with no wall-clock sleeps).
|
|
890
|
+
* @param {unknown} manager
|
|
891
|
+
* @returns {number} Non-negative delay in milliseconds
|
|
892
|
+
*/
|
|
893
|
+
function resolveCorrectionInterOpDelayMs(manager) {
|
|
894
|
+
const raw = manager?.config?.fillProcessing?.CORRECTION_INTER_OP_DELAY_MS
|
|
895
|
+
?? FILL_PROCESSING?.CORRECTION_INTER_OP_DELAY_MS;
|
|
896
|
+
if (raw != null) {
|
|
897
|
+
const n = Number(raw);
|
|
898
|
+
if (Number.isFinite(n) && n >= 0)
|
|
899
|
+
return Math.floor(n);
|
|
900
|
+
}
|
|
901
|
+
return TIMING.SYNC_DELAY_MS;
|
|
902
|
+
}
|
|
874
903
|
/**
|
|
875
904
|
* Resolve the correction-backlog warn threshold (see
|
|
876
905
|
* CORRECTION_QUEUE_WARN_THRESHOLD). Non-positive disables the alarm.
|
|
877
|
-
* @param {
|
|
906
|
+
* @param {unknown} manager
|
|
878
907
|
* @returns {number}
|
|
879
908
|
*/
|
|
880
909
|
function resolveCorrectionWarnThreshold(manager) {
|
|
@@ -887,7 +916,7 @@ function resolveCorrectionWarnThreshold(manager) {
|
|
|
887
916
|
}
|
|
888
917
|
/**
|
|
889
918
|
* Resolve the correction-backlog warn rate-limit window.
|
|
890
|
-
* @param {
|
|
919
|
+
* @param {unknown} manager
|
|
891
920
|
* @returns {number}
|
|
892
921
|
*/
|
|
893
922
|
function resolveCorrectionWarnRateLimitMs(manager) {
|
|
@@ -1006,6 +1035,7 @@ async function correctAllPriceMismatches(manager, accountName, privateKey, accou
|
|
|
1006
1035
|
return true;
|
|
1007
1036
|
});
|
|
1008
1037
|
const updateEntries = liveEntries.filter((c) => !(c.cancelOnly === true || c.isSurplus === true));
|
|
1038
|
+
const interOpDelayMs = resolveCorrectionInterOpDelayMs(manager);
|
|
1009
1039
|
const canBatch = cancelEntries.length > 1
|
|
1010
1040
|
&& typeof accountOrders?.buildCancelOrderOp === 'function'
|
|
1011
1041
|
&& typeof accountOrders?.executeBatch === 'function';
|
|
@@ -1024,7 +1054,7 @@ async function correctAllPriceMismatches(manager, accountName, privateKey, accou
|
|
|
1024
1054
|
corrected++;
|
|
1025
1055
|
else
|
|
1026
1056
|
failed++;
|
|
1027
|
-
await sleep(
|
|
1057
|
+
await sleep(interOpDelayMs);
|
|
1028
1058
|
}
|
|
1029
1059
|
// Price updates are bounded by wall-clock lock-hold budget (primary)
|
|
1030
1060
|
// plus an optional hard count cap. The window opens *after* cancels so
|
|
@@ -1050,7 +1080,7 @@ async function correctAllPriceMismatches(manager, accountName, privateKey, accou
|
|
|
1050
1080
|
else
|
|
1051
1081
|
failed++;
|
|
1052
1082
|
updatesProcessed++;
|
|
1053
|
-
await sleep(
|
|
1083
|
+
await sleep(interOpDelayMs);
|
|
1054
1084
|
}
|
|
1055
1085
|
// Persist master grid mutations from surplus-type-mismatch cancellations.
|
|
1056
1086
|
// Without this, corrections that cancel an order and convert its grid slot
|
|
@@ -1178,7 +1208,7 @@ function resolveConfiguredPriceBound(value, fallback, startPrice, mode) {
|
|
|
1178
1208
|
const hint = mode === 'min'
|
|
1179
1209
|
? `'Nx' means center/N for minPrice, so use a value > 1 (e.g. '1.43x' to place the bound at 70% of center)`
|
|
1180
1210
|
: `'Nx' means center*N for maxPrice, so use a value > 1`;
|
|
1181
|
-
throw new Error(`Invalid ${boundName} '${configuredValue.trim()}': a bound multiplier must be > 1. ${hint}.`);
|
|
1211
|
+
throw new Error(`Invalid ${boundName} '${String(configuredValue).trim()}': a bound multiplier must be > 1. ${hint}.`);
|
|
1182
1212
|
}
|
|
1183
1213
|
const relative = MathUtils.resolveRelativePrice(configuredValue, startPrice, mode);
|
|
1184
1214
|
if (Number.isFinite(relative)) {
|
|
@@ -1191,13 +1221,6 @@ function resolveConfiguredPriceBound(value, fallback, startPrice, mode) {
|
|
|
1191
1221
|
}
|
|
1192
1222
|
return numeric;
|
|
1193
1223
|
}
|
|
1194
|
-
/**
|
|
1195
|
-
* Convert order to virtual state.
|
|
1196
|
-
* Clears on-chain ID and raw blockchain data, marks as VIRTUAL.
|
|
1197
|
-
*
|
|
1198
|
-
* @param {Object} order - Order to virtualize
|
|
1199
|
-
* @returns {Object} Virtualized order (VIRTUAL state, no orderId)
|
|
1200
|
-
*/
|
|
1201
1224
|
function virtualizeOrder(order) {
|
|
1202
1225
|
if (!order)
|
|
1203
1226
|
return order;
|
|
@@ -1358,12 +1381,28 @@ function resolveSpreadOrderSide(price, startPrice) {
|
|
|
1358
1381
|
/**
|
|
1359
1382
|
* Parse a grid slot id ("slot-123") to its rail index. Delegates to
|
|
1360
1383
|
* shared slot.ts single source (GRID_PRICE_SLOT_DETERMINISM_PLAN §2.1).
|
|
1361
|
-
* @param {
|
|
1384
|
+
* @param {unknown} id - grid slot id string
|
|
1362
1385
|
* @returns {number|null}
|
|
1363
1386
|
*/
|
|
1364
1387
|
function parseSlotIndex(id) {
|
|
1365
1388
|
return parseSlotIndexShared(id);
|
|
1366
1389
|
}
|
|
1390
|
+
/**
|
|
1391
|
+
* Precision governing both price and size comparison for a parsed chain
|
|
1392
|
+
* order: base (assetA) for sells, quote (assetB) for buys.
|
|
1393
|
+
*/
|
|
1394
|
+
function slotMatchPrecision(type, assets) {
|
|
1395
|
+
return type === ORDER_TYPES.SELL ? assets.assetA.precision : assets.assetB.precision;
|
|
1396
|
+
}
|
|
1397
|
+
/**
|
|
1398
|
+
* Whether a parsed chain order's size matches a slot's, within the shared
|
|
1399
|
+
* 1%-of-size tolerance (min 2 quanta). Single source of truth for adoption
|
|
1400
|
+
* size matching so the strict and tolerant matchers cannot disagree.
|
|
1401
|
+
*/
|
|
1402
|
+
function slotSizeMatches(parsed, slot, precision) {
|
|
1403
|
+
const sizeTolerance = Math.max(2, Math.floor(floatToBlockchainInt(slot.size, precision) * 0.01));
|
|
1404
|
+
return Math.abs(floatToBlockchainInt(parsed.size, precision) - floatToBlockchainInt(slot.size, precision)) <= sizeTolerance;
|
|
1405
|
+
}
|
|
1367
1406
|
/**
|
|
1368
1407
|
* Whether a parsed chain order matches a grid slot exactly:
|
|
1369
1408
|
* type-compatible (slot may be SPREAD), price strictly equal via integer
|
|
@@ -1384,16 +1423,10 @@ function chainOrderMatchesSlot(parsed, slot, assets) {
|
|
|
1384
1423
|
if (parsed.type !== slot.type && slot.type !== ORDER_TYPES.SPREAD)
|
|
1385
1424
|
return false;
|
|
1386
1425
|
// Genesis-frozen: price equality via integer round-trip (single epsilon); slot id is handled by caller via slotIndexForPrice
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
if (!priceSlotEqual(parsed.price, slot.price, precision))
|
|
1390
|
-
return false;
|
|
1391
|
-
}
|
|
1392
|
-
const precision = parsed.type === ORDER_TYPES.SELL ? assets.assetA.precision : assets.assetB.precision;
|
|
1393
|
-
const sizeTolerance = Math.max(2, Math.floor(floatToBlockchainInt(slot.size, precision) * 0.01));
|
|
1394
|
-
if (Math.abs(floatToBlockchainInt(parsed.size, precision) - floatToBlockchainInt(slot.size, precision)) > sizeTolerance)
|
|
1426
|
+
const precision = slotMatchPrecision(parsed.type, assets);
|
|
1427
|
+
if (!priceSlotEqual(parsed.price, slot.price, precision))
|
|
1395
1428
|
return false;
|
|
1396
|
-
return
|
|
1429
|
+
return slotSizeMatches(parsed, slot, precision);
|
|
1397
1430
|
}
|
|
1398
1431
|
/**
|
|
1399
1432
|
* Whether a parsed chain order matches a grid slot within price tolerance:
|
|
@@ -1415,10 +1448,10 @@ function chainOrderMatchesSlotWithTolerance(parsed, slot, assets) {
|
|
|
1415
1448
|
return false;
|
|
1416
1449
|
if (parsed.type !== slot.type && slot.type !== ORDER_TYPES.SPREAD)
|
|
1417
1450
|
return false;
|
|
1418
|
-
const precision = parsed.type
|
|
1451
|
+
const precision = slotMatchPrecision(parsed.type, assets);
|
|
1419
1452
|
let tolerance = null;
|
|
1420
1453
|
try {
|
|
1421
|
-
tolerance = MathUtils.calculatePriceTolerance(Math.min(parsed.price, slot.price), Math.max(parsed.size, slot.size), parsed.type, assets);
|
|
1454
|
+
tolerance = MathUtils.calculatePriceTolerance(Math.min(parsed.price, slot.price), Math.max(Number(parsed.size) || 0, slot.size), parsed.type, assets);
|
|
1422
1455
|
}
|
|
1423
1456
|
catch {
|
|
1424
1457
|
tolerance = null;
|
|
@@ -1433,10 +1466,7 @@ function chainOrderMatchesSlotWithTolerance(parsed, slot, assets) {
|
|
|
1433
1466
|
tolerance = Math.min(tolerance, quantumCap);
|
|
1434
1467
|
if (Math.abs(parsed.price - slot.price) > tolerance)
|
|
1435
1468
|
return false;
|
|
1436
|
-
|
|
1437
|
-
if (Math.abs(floatToBlockchainInt(parsed.size, precision) - floatToBlockchainInt(slot.size, precision)) > sizeTolerance)
|
|
1438
|
-
return false;
|
|
1439
|
-
return true;
|
|
1469
|
+
return slotSizeMatches(parsed, slot, precision);
|
|
1440
1470
|
}
|
|
1441
1471
|
/**
|
|
1442
1472
|
* Identity of a crossing-check candidate. Master orders carry orderId,
|
|
@@ -1500,7 +1530,7 @@ function isCrossingCheckCandidate(o, excludeChainOrderId = null, cancelOpIndexBy
|
|
|
1500
1530
|
* master-grid-only checks cannot see (the pending/unmatched batch guards
|
|
1501
1531
|
* fire only for CREATE batches).
|
|
1502
1532
|
* @param {Object} manager - OrderManager instance (orders Map, _pendingBroadcasts, _lastUnmatchedChainOrders)
|
|
1503
|
-
* @returns {
|
|
1533
|
+
* @returns {unknown[]} Candidate orders/wrappers for findCrossedOrder
|
|
1504
1534
|
*/
|
|
1505
1535
|
function buildCrossingCheckCandidates(manager) {
|
|
1506
1536
|
if (!manager)
|
|
@@ -1577,10 +1607,12 @@ function buildOutsideInPairGroups(items, { isValid = Boolean, getType, getPrice
|
|
|
1577
1607
|
* @returns {Array} Array of operation result tuples, or empty array if unrecognized.
|
|
1578
1608
|
*/
|
|
1579
1609
|
function extractBatchOperationResults(result) {
|
|
1580
|
-
const
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
(
|
|
1610
|
+
const r = result;
|
|
1611
|
+
const asArray = Array.isArray(result) ? result : null;
|
|
1612
|
+
const ops = ((r && Array.isArray(r.operation_results) && r.operation_results) ||
|
|
1613
|
+
(r && r.raw && Array.isArray(r.raw.operation_results) && r.raw.operation_results) ||
|
|
1614
|
+
(r && r.raw && r.raw.trx && Array.isArray(r.raw.trx.operation_results) && r.raw.trx.operation_results) ||
|
|
1615
|
+
(asArray && asArray[0] && asArray[0].trx && Array.isArray(asArray[0].trx.operation_results) && asArray[0].trx.operation_results) ||
|
|
1584
1616
|
null);
|
|
1585
1617
|
return (ops && ops.length > 0) ? ops : null;
|
|
1586
1618
|
}
|
|
@@ -1594,10 +1626,10 @@ function formatUnmatchedChainOrder(order) {
|
|
|
1594
1626
|
if (!order)
|
|
1595
1627
|
return 'unknown unmatched order';
|
|
1596
1628
|
const parts = [
|
|
1597
|
-
`${order.chainOrderId || 'unknown'}:${order.type || 'unknown'}@${Format.formatPrice6(order.price)}`,
|
|
1629
|
+
`${order.chainOrderId || 'unknown'}:${order.type || 'unknown'}@${Format.formatPrice6(Number(order.price))}`,
|
|
1598
1630
|
];
|
|
1599
1631
|
if (order.size !== undefined)
|
|
1600
|
-
parts.push(`size=${Format.formatAmount(order.size)}`);
|
|
1632
|
+
parts.push(`size=${Format.formatAmount(Number(order.size))}`);
|
|
1601
1633
|
if (order.slotId)
|
|
1602
1634
|
parts.push(`slot=${order.slotId}`);
|
|
1603
1635
|
if (order.reason)
|
|
@@ -1686,7 +1718,7 @@ function isStrandedHoldOrder(order) {
|
|
|
1686
1718
|
*
|
|
1687
1719
|
* @param {string} slotId - Grid slot id (slot-<idx>)
|
|
1688
1720
|
* @param {number} price - Price about to be emitted
|
|
1689
|
-
* @param {
|
|
1721
|
+
* @param {unknown} genesis - manager._genesis (priceLevels table)
|
|
1690
1722
|
* @returns {{ok: boolean, reason: string, expected: number|null, idx: number|null, drift: number|null}}
|
|
1691
1723
|
*/
|
|
1692
1724
|
function checkGridPriceInvariant(slotId, price, genesis) {
|
|
@@ -1727,7 +1759,7 @@ function checkGridPriceInvariant(slotId, price, genesis) {
|
|
|
1727
1759
|
* reconcile sites treat `false` as blocking (skip the emission and let the next
|
|
1728
1760
|
* cycle re-plan). See docs/GRID_PRICE_INVARIANT.md.
|
|
1729
1761
|
*
|
|
1730
|
-
* @param {
|
|
1762
|
+
* @param {unknown} manager - OrderManager (reads _genesis, writes logger)
|
|
1731
1763
|
* @param {string} slotId - Destination slot id whose level the price must match
|
|
1732
1764
|
* @param {number} price - Price about to be emitted
|
|
1733
1765
|
* @param {string} site - Emitting site label (CREATE / UPDATE / RECONCILE-*)
|
|
@@ -1737,7 +1769,7 @@ function checkGridPriceInvariant(slotId, price, genesis) {
|
|
|
1737
1769
|
*/
|
|
1738
1770
|
function reportGridPriceInvariant(manager, slotId, price, site) {
|
|
1739
1771
|
try {
|
|
1740
|
-
const inv = checkGridPriceInvariant(slotId, price, manager?._genesis);
|
|
1772
|
+
const inv = checkGridPriceInvariant(slotId, price, hasGenesisLadder(manager?._genesis) ? manager._genesis : null);
|
|
1741
1773
|
if (inv.ok)
|
|
1742
1774
|
return true;
|
|
1743
1775
|
manager?.logger?.log?.(`[GRID-PRICE-INVARIANT] ${site} for ${slotId} at ${Format.formatPrice6(Number(price))} ` +
|
|
@@ -1778,10 +1810,10 @@ function isOrderOnChain(order) {
|
|
|
1778
1810
|
* @param {Object} ORDER_TYPES - ORDER_TYPES constants
|
|
1779
1811
|
* @returns {string} Type to keep for the on-chain slot
|
|
1780
1812
|
*/
|
|
1781
|
-
function resolveOnChainRetypeType(slot, idx, buyEndIdx,
|
|
1782
|
-
return (slot.type ===
|
|
1813
|
+
function resolveOnChainRetypeType(slot, idx, buyEndIdx, orderTypes) {
|
|
1814
|
+
return (slot.type === orderTypes.BUY || slot.type === orderTypes.SELL)
|
|
1783
1815
|
? slot.type
|
|
1784
|
-
: (idx <= buyEndIdx ?
|
|
1816
|
+
: (idx <= buyEndIdx ? orderTypes.BUY : orderTypes.SELL);
|
|
1785
1817
|
}
|
|
1786
1818
|
/**
|
|
1787
1819
|
* Check if order is virtual (not on blockchain yet).
|
|
@@ -1956,33 +1988,19 @@ function calculateIdealBoundary(allSlots, referencePrice, gapSlots) {
|
|
|
1956
1988
|
if (!Number.isFinite(Number(referencePrice))) {
|
|
1957
1989
|
return railCenterIndex(allSlots.length, gapSlots);
|
|
1958
1990
|
}
|
|
1959
|
-
let splitIdx = allSlots.findIndex((s) => s.price >= referencePrice);
|
|
1991
|
+
let splitIdx = allSlots.findIndex((s) => Number(s.price) >= Number(referencePrice));
|
|
1960
1992
|
if (splitIdx === -1)
|
|
1961
1993
|
splitIdx = allSlots.length;
|
|
1962
1994
|
const buySpread = Math.floor(gapSlots / 2);
|
|
1963
1995
|
return Math.max(0, Math.min(allSlots.length - 1, splitIdx - buySpread - 1));
|
|
1964
1996
|
}
|
|
1965
|
-
/**
|
|
1966
|
-
* Assign BUY/SELL/SPREAD roles to grid slots based on boundary.
|
|
1967
|
-
* Slots below boundary are BUY, above boundary are SELL, between are SPREAD.
|
|
1968
|
-
* Can optionally override even on-chain orders.
|
|
1969
|
-
*
|
|
1970
|
-
* @param {Array<Object>} allSlots - All grid slots to assign
|
|
1971
|
-
* @param {number} boundaryIdx - Boundary index
|
|
1972
|
-
* @param {number} gapSlots - Number of gap slots between buy and sell
|
|
1973
|
-
* @param {Object} ORDER_TYPES - ORDER_TYPES constants
|
|
1974
|
-
* @param {Object} ORDER_STATES - ORDER_STATES constants
|
|
1975
|
-
* @param {Object} [options={}] - Options
|
|
1976
|
-
* @param {boolean} [options.assignOnChain=false] - Override on-chain orders if true
|
|
1977
|
-
* @returns {Array<Object>} Slots with updated type assignments
|
|
1978
|
-
*/
|
|
1979
1997
|
function assignGridRoles(allSlots, boundaryIdx, gapSlots, ORDER_TYPES, _ORDER_STATES, options = {}) {
|
|
1980
1998
|
const assignOnChain = options.assignOnChain === true;
|
|
1981
1999
|
const getCurrentSlot = (typeof options.getCurrentSlot === 'function') ? options.getCurrentSlot : null;
|
|
1982
2000
|
const buyEndIdx = boundaryIdx;
|
|
1983
2001
|
const sellStartIdx = MathUtils.getSellStartIdx(boundaryIdx, gapSlots);
|
|
1984
2002
|
return allSlots.map((slot, i) => {
|
|
1985
|
-
const liveSlot = getCurrentSlot ? (getCurrentSlot(slot.id) || slot) : slot;
|
|
2003
|
+
const liveSlot = getCurrentSlot && slot.id ? (getCurrentSlot(slot.id) || slot) : slot;
|
|
1986
2004
|
// Empty VIRTUAL slots (size 0, no orderId) keep their RAIL type by
|
|
1987
2005
|
// geometry (Phase 2): an in-rail hole stays BUY/SELL VIRTUAL so
|
|
1988
2006
|
// candidate-selection and evacuation geometry keep working; only
|
|
@@ -2291,7 +2309,7 @@ function isShiftEligibleFill(fill) {
|
|
|
2291
2309
|
return fill?.isPartial !== true || fill?.isDelayedRotationTrigger === true;
|
|
2292
2310
|
}
|
|
2293
2311
|
function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSlots, crossChunkBudget, pendingCrawls, edgeAnchors) {
|
|
2294
|
-
let newBoundaryIdx = currentBoundaryIdx;
|
|
2312
|
+
let newBoundaryIdx = currentBoundaryIdx ?? null;
|
|
2295
2313
|
// Recovery when the committed boundary is unknown (GRID-LOAD rejected a
|
|
2296
2314
|
// poisoned snapshot, re-derivation failed, and no fill has re-anchored
|
|
2297
2315
|
// since). Anchor tiers are position signals, weakest last. What must
|
|
@@ -2426,12 +2444,12 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
|
|
|
2426
2444
|
&& (e.side === ORDER_TYPES.BUY || e.side === ORDER_TYPES.SELL)
|
|
2427
2445
|
&& !(e.side === ORDER_TYPES.BUY && reserveBuyIds && reserveBuyIds.has(e.slotId))
|
|
2428
2446
|
&& !(e.side === ORDER_TYPES.SELL && reserveSellIds && reserveSellIds.has(e.slotId)));
|
|
2429
|
-
for (const fill of fills) {
|
|
2447
|
+
for (const fill of fills ?? []) {
|
|
2430
2448
|
if (!isShiftEligibleFill(fill))
|
|
2431
2449
|
continue;
|
|
2432
|
-
if (fill && fill.type === ORDER_TYPES.BUY && reserveBuyIds && reserveBuyIds.has(fill.id))
|
|
2450
|
+
if (fill && fill.type === ORDER_TYPES.BUY && reserveBuyIds && fill.id != null && reserveBuyIds.has(fill.id))
|
|
2433
2451
|
continue;
|
|
2434
|
-
if (fill && fill.type === ORDER_TYPES.SELL && reserveSellIds && reserveSellIds.has(fill.id))
|
|
2452
|
+
if (fill && fill.type === ORDER_TYPES.SELL && reserveSellIds && fill.id != null && reserveSellIds.has(fill.id))
|
|
2435
2453
|
continue;
|
|
2436
2454
|
if (fill.type === ORDER_TYPES.SELL)
|
|
2437
2455
|
netShift++;
|
|
@@ -2455,7 +2473,7 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
|
|
|
2455
2473
|
// consumes from the same pool so the total across all chunks
|
|
2456
2474
|
// never exceeds half the active window.
|
|
2457
2475
|
// Falls back to a per-call cap when no budget is set.
|
|
2458
|
-
const fallbackCap = Math.max(Math.floor((config
|
|
2476
|
+
const fallbackCap = Math.max(Math.floor((config?.activeOrders?.sell ?? 1) / 2), Math.floor((config?.activeOrders?.buy ?? 1) / 2), 1);
|
|
2459
2477
|
const effectiveBudget = crossChunkBudget ?? fallbackCap;
|
|
2460
2478
|
const cap = Math.min(Math.abs(effectiveBudget), fallbackCap);
|
|
2461
2479
|
if (recovered && anchoredFromFills) {
|
|
@@ -2502,7 +2520,7 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
|
|
|
2502
2520
|
* dropped rather than stranding live orders. Commits clear the record, so
|
|
2503
2521
|
* entries present here predate every commit since recording — always owed.
|
|
2504
2522
|
*
|
|
2505
|
-
* @param {
|
|
2523
|
+
* @param {unknown} manager - OrderManager (boundaryIdx, orders, config restored)
|
|
2506
2524
|
* @returns {{applied: boolean, from?: number, to?: number, count?: number, reason?: string}}
|
|
2507
2525
|
*/
|
|
2508
2526
|
export function consumePendingFillCrawls(manager) {
|
|
@@ -2564,7 +2582,9 @@ export function consumePendingFillCrawls(manager) {
|
|
|
2564
2582
|
clear();
|
|
2565
2583
|
return { applied: false, reason: 'nothing-owed' };
|
|
2566
2584
|
}
|
|
2567
|
-
const
|
|
2585
|
+
const activeOrdersCfg = config?.activeOrders;
|
|
2586
|
+
const activeOrdersObj = (activeOrdersCfg && typeof activeOrdersCfg === 'object') ? activeOrdersCfg : {};
|
|
2587
|
+
const fallbackCap = Math.max(Math.floor(Number(activeOrdersObj.sell ?? 1) / 2), Math.floor(Number(activeOrdersObj.buy ?? 1) / 2), 1);
|
|
2568
2588
|
if (Math.abs(netShift) > fallbackCap)
|
|
2569
2589
|
netShift = Math.sign(netShift) * fallbackCap;
|
|
2570
2590
|
let gapSlots = Number(manager?._gapSlots);
|
|
@@ -2587,7 +2607,7 @@ export function consumePendingFillCrawls(manager) {
|
|
|
2587
2607
|
check = MathUtils.validatePersistedBoundary(candidate, slots, gapSlots);
|
|
2588
2608
|
}
|
|
2589
2609
|
catch (err) {
|
|
2590
|
-
check = { ok: false, reason: 'validator-threw', detail:
|
|
2610
|
+
check = { ok: false, reason: 'validator-threw', detail: getErrorMessage(err) };
|
|
2591
2611
|
}
|
|
2592
2612
|
if (!check || check.ok !== true) {
|
|
2593
2613
|
clear();
|
|
@@ -2686,7 +2706,7 @@ function reserveEdgeIdSet(allSlots, config, orderType, anchorPrice = null, exclu
|
|
|
2686
2706
|
.filter((s) => s && s.id != null && s.price != null && s.type === type && parseSlotIndex(s.id) !== null)
|
|
2687
2707
|
.sort((a, b) => Number(a.price) - Number(b.price));
|
|
2688
2708
|
for (const s of selectReserveEdgeSlots(ascending, n, excludeIds, isSell ? 'ceiling' : 'floor', anchor)) {
|
|
2689
|
-
ids.add(s.id);
|
|
2709
|
+
ids.add(String(s.id));
|
|
2690
2710
|
}
|
|
2691
2711
|
return ids;
|
|
2692
2712
|
}
|
|
@@ -2730,7 +2750,7 @@ function windowIdSetFromSlots(allSlots, config, orderType, boundaryIdx, gapSlots
|
|
|
2730
2750
|
// Same type filter as the window pickers with known geometry: the
|
|
2731
2751
|
// side's concrete type plus SPREAD placeholders (normalized empties
|
|
2732
2752
|
// sitting in this side's rail).
|
|
2733
|
-
const typeFilter = (o) => o && o.id != null && o.price != null && (o.type === type || o.type === ORDER_TYPES.SPREAD);
|
|
2753
|
+
const typeFilter = (o) => !!o && o.id != null && o.price != null && (o.type === type || o.type === ORDER_TYPES.SPREAD);
|
|
2734
2754
|
const ids = allSlots
|
|
2735
2755
|
.filter(typeFilter)
|
|
2736
2756
|
.filter(inRail)
|
|
@@ -2748,7 +2768,7 @@ function windowIdSetFromSlots(allSlots, config, orderType, boundaryIdx, gapSlots
|
|
|
2748
2768
|
* windowIdSetFromSlots). Delegates so the manager and explicit-geometry
|
|
2749
2769
|
* callers share one definition.
|
|
2750
2770
|
*
|
|
2751
|
-
* @param {
|
|
2771
|
+
* @param {unknown} manager - OrderManager (orders Map, config, boundaryIdx)
|
|
2752
2772
|
* @param {string} orderType - ORDER_TYPES.BUY or ORDER_TYPES.SELL
|
|
2753
2773
|
* @returns {Set<string>|null} Window slot ids, or null when geometry unknown
|
|
2754
2774
|
*/
|
|
@@ -2793,7 +2813,7 @@ function liveWindowIdSet(manager, orderType) {
|
|
|
2793
2813
|
* @param {Iterable<Object>} [options.slots] - Master slots (reserve classification)
|
|
2794
2814
|
* @param {{buy?: number|null, sell?: number|null}} [options.edgeAnchors] - Live
|
|
2795
2815
|
* edge anchors (same pair the strategy classifies reserve fills against)
|
|
2796
|
-
* @param {
|
|
2816
|
+
* @param {unknown} [options.manager] - OrderManager for the window exclusion (same
|
|
2797
2817
|
* set the placement pickers exclude); omit to fall back to the previous
|
|
2798
2818
|
* exclusion-free classification (fail-open)
|
|
2799
2819
|
* @returns {string[]} Refill slot ids (CREATE ids minus reserve edge ids)
|
|
@@ -2816,7 +2836,7 @@ function collectRefillSlotIds(actions, options = {}) {
|
|
|
2816
2836
|
// required — Array.from(map) would hand reserveEdgeIdSet pairs.
|
|
2817
2837
|
const allSlots = Array.isArray(slots)
|
|
2818
2838
|
? slots
|
|
2819
|
-
: (typeof slots
|
|
2839
|
+
: (slots && typeof slots.values === 'function'
|
|
2820
2840
|
? Array.from(slots.values())
|
|
2821
2841
|
: Array.from(slots));
|
|
2822
2842
|
// Window exclusion keeps classification in agreement with the
|
|
@@ -3003,6 +3023,8 @@ function getActiveOrdersTotal(config) {
|
|
|
3003
3023
|
* @returns {number} Available budget for the side
|
|
3004
3024
|
*/
|
|
3005
3025
|
function getSideBudget(side, funds, config, totalTarget) {
|
|
3026
|
+
if (!funds)
|
|
3027
|
+
return 0;
|
|
3006
3028
|
const isBuy = side === 'buy';
|
|
3007
3029
|
const allocated = isBuy ? (funds.allocatedBuy || 0) : (funds.allocatedSell || 0);
|
|
3008
3030
|
if (allocated <= 0)
|
|
@@ -3042,7 +3064,7 @@ function calculateBudgetedSizes(slots, side, budget, weightDist, incrementPercen
|
|
|
3042
3064
|
// Precision not available — floatToBlockchainInt will throw
|
|
3043
3065
|
}
|
|
3044
3066
|
}
|
|
3045
|
-
const incrementFactor = incrementPercent / 100;
|
|
3067
|
+
const incrementFactor = Number(incrementPercent) / 100;
|
|
3046
3068
|
return MathUtils.allocateFundsByWeights(budget, slots.length, weightDist, incrementFactor, isBuy, // Reverse for BUY (Market-Close is last in array)
|
|
3047
3069
|
0, precision);
|
|
3048
3070
|
}
|
|
@@ -3092,7 +3114,7 @@ function detectCrossedBookPlan(manager, actions) {
|
|
|
3092
3114
|
try {
|
|
3093
3115
|
const startPrice = Number(manager?.config?.startPrice);
|
|
3094
3116
|
const book = new Map();
|
|
3095
|
-
for (const o of
|
|
3117
|
+
for (const o of manager.orders.values()) {
|
|
3096
3118
|
if (!o || !o.orderId || o.price == null)
|
|
3097
3119
|
continue;
|
|
3098
3120
|
const price = Number(o.price);
|
|
@@ -3166,9 +3188,9 @@ function detectCrossedBookPlan(manager, actions) {
|
|
|
3166
3188
|
* - the batch's fresh CREATE ids extracted from the broadcast result
|
|
3167
3189
|
* (operation_results[i][1] aligns positionally with placedContexts[i]).
|
|
3168
3190
|
*
|
|
3169
|
-
* @param {
|
|
3170
|
-
* @param {
|
|
3171
|
-
* @param {
|
|
3191
|
+
* @param {unknown} mgr - bot.manager
|
|
3192
|
+
* @param {unknown} placedResults - broadcast result (has operation_results); null when unavailable
|
|
3193
|
+
* @param {unknown[]} placedContexts - opContexts (aligned with operation_results); null when unavailable
|
|
3172
3194
|
* @param {string[]|null} [extraCreateIds=null] - fresh CREATE chain ids from another
|
|
3173
3195
|
* authoritative source (e.g. the uncertain-broadcast poll confirmation) when
|
|
3174
3196
|
* no broadcast result exists; merged into createIds so the lagging-create
|
|
@@ -3177,7 +3199,7 @@ function detectCrossedBookPlan(manager, actions) {
|
|
|
3177
3199
|
*/
|
|
3178
3200
|
function collectKnownOnChainOrderIds(mgr, placedResults, placedContexts, extraCreateIds = null) {
|
|
3179
3201
|
const masterIds = new Set();
|
|
3180
|
-
const grid = mgr
|
|
3202
|
+
const grid = mgr.grid;
|
|
3181
3203
|
if (Array.isArray(grid)) {
|
|
3182
3204
|
for (const slot of grid) {
|
|
3183
3205
|
if (slot && slot.orderId && /^1\.7\.\d+$/.test(String(slot.orderId))) {
|
|
@@ -3204,9 +3226,10 @@ function collectKnownOnChainOrderIds(mgr, placedResults, placedContexts, extraCr
|
|
|
3204
3226
|
const ctx = placedContexts[i];
|
|
3205
3227
|
if (!ctx || ctx.kind !== 'create')
|
|
3206
3228
|
continue;
|
|
3207
|
-
const
|
|
3208
|
-
|
|
3209
|
-
|
|
3229
|
+
const rawOpResult = opResults[i] ? opResults[i][1] : undefined;
|
|
3230
|
+
const opResult = typeof rawOpResult === 'string' ? rawOpResult : null;
|
|
3231
|
+
if (opResult && /^1\.7\.\d+$/.test(opResult)) {
|
|
3232
|
+
createIds.add(opResult);
|
|
3210
3233
|
}
|
|
3211
3234
|
}
|
|
3212
3235
|
}
|
|
@@ -4,5 +4,5 @@
|
|
|
4
4
|
* Extracted per GRID_PRICE_SLOT_DETERMINISM_PLAN §2.1 to unify duplicate
|
|
5
5
|
* parsers in math.ts:1611 and order.ts:915 and make fail-closed explicit.
|
|
6
6
|
*/
|
|
7
|
-
export declare function parseSlotIndex(id:
|
|
7
|
+
export declare function parseSlotIndex(id: unknown): number | null;
|
|
8
8
|
//# sourceMappingURL=slot.d.ts.map
|