dexbot 1.6.11 → 1.6.13
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 +67 -4
- package/README.md +2 -1
- package/analysis/README.md +11 -11
- package/analysis/ama_fitting/README.md +5 -3
- package/analysis/tradingview/README.md +1 -1
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
- package/claw/README.md +1 -0
- package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
- package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
- package/claw/modules/chain_broadcast.ts +7 -1
- package/claw/modules/claw_bridge.ts +0 -3
- package/claw/modules/claw_launcher.ts +1 -1
- package/claw/modules/claw_skill_md.ts +1 -0
- package/claw/modules/launcher_mode_detector.ts +9 -2
- package/claw/package.json +3 -3
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/claw/tsconfig.json +2 -2
- 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 +3 -21
- package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
- package/dist/analysis/ama_fitting/fetch_lp_candles.js +55 -45
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -8
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +45 -24
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js +34 -78
- package/dist/analysis/analyze_args.d.ts +43 -0
- package/dist/analysis/analyze_args.js +61 -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 +221 -28
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js +23 -103
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +32 -150
- package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
- package/dist/analysis/bot_fitting/shared_utils.d.ts +77 -9
- package/dist/analysis/bot_fitting/shared_utils.js +125 -9
- 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 +35 -3
- package/dist/analysis/chart_ui.js +43 -4
- package/dist/analysis/chart_utils.d.ts +5 -5
- package/dist/analysis/chart_utils.js +9 -0
- package/dist/analysis/fills_cache.d.ts +4 -24
- package/dist/analysis/fills_cache.js +3 -84
- package/dist/analysis/fills_source.d.ts +33 -3
- package/dist/analysis/fills_source.js +83 -13
- package/dist/analysis/grid_correction_check.d.ts +2 -24
- package/dist/analysis/grid_correction_check.js +27 -69
- package/dist/analysis/math_utils.d.ts +91 -6
- package/dist/analysis/math_utils.js +119 -7
- package/dist/analysis/pnl_report.js +29 -29
- package/dist/analysis/price_sources.d.ts +30 -9
- package/dist/analysis/price_sources.js +28 -4
- package/dist/analysis/resolve_bot_accounts.js +2 -2
- package/dist/analysis/resolve_source.d.ts +1 -1
- package/dist/analysis/resolve_source.js +31 -10
- package/dist/analysis/trade_profitability.d.ts +29 -2
- package/dist/analysis/trade_profitability.js +73 -147
- package/dist/analysis/tradingview/analyze_tradingview.d.ts +3 -8
- package/dist/analysis/tradingview/analyze_tradingview.js +7 -6
- 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 +20 -34
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +26 -84
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +16 -41
- 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/analysis/trend_detection/volatility_chart_generator.js +9 -10
- package/dist/analysis/worker_pool.d.ts +38 -0
- package/dist/analysis/worker_pool.js +67 -0
- package/dist/credential-daemon.js +34 -20
- package/dist/dexbot.js +78 -59
- package/dist/market_adapter/ama_signal_runner.js +21 -54
- package/dist/market_adapter/candle_utils.d.ts +29 -19
- package/dist/market_adapter/candle_utils.js +35 -21
- package/dist/market_adapter/cli_args.d.ts +22 -0
- package/dist/market_adapter/cli_args.js +30 -0
- 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/config_normalizers.js +11 -6
- package/dist/market_adapter/core/kibana_candles.d.ts +56 -19
- package/dist/market_adapter/core/kibana_candles.js +12 -9
- 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 +320 -153
- package/dist/market_adapter/core/market_adapter_service.js +228 -269
- package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
- package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
- package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
- package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
- 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 -2
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +160 -332
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +50 -8
- package/dist/market_adapter/inputs/fetch_lp_data.js +47 -22
- package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
- package/dist/market_adapter/inputs/kibana_feed_source.js +26 -41
- 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 +93 -156
- package/dist/market_adapter/inputs/window_cache.js +59 -184
- package/dist/market_adapter/interval_utils.d.ts +15 -5
- package/dist/market_adapter/interval_utils.js +16 -1
- 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 +10 -7
- package/dist/market_adapter/lp_chart_runner.js +37 -19
- 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 +94 -120
- 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 +49 -2
- package/dist/market_adapter/utils/data_discovery.js +220 -27
- 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/month_shards.d.ts +84 -0
- package/dist/market_adapter/utils/month_shards.js +237 -0
- 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 +578 -21
- package/dist/modules/account_bots.js +272 -267
- package/dist/modules/account_orders.d.ts +79 -30
- package/dist/modules/account_orders.js +60 -64
- 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 +39 -4
- package/dist/modules/bitshares-native/chain_client.js +59 -59
- 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/resolvers.js +22 -25
- 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 +73 -108
- 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 +8 -16
- 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 +4 -3
- 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 +94 -60
- package/dist/modules/chain_orders.js +81 -118
- package/dist/modules/cli_start_onboarding.d.ts +2 -1
- package/dist/modules/constants.d.ts +534 -32
- package/dist/modules/constants.js +35 -48
- package/dist/modules/cr_planner.d.ts +41 -3
- package/dist/modules/cr_planner.js +1 -5
- 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 +43 -6
- package/dist/modules/credit_pricing.js +70 -60
- package/dist/modules/credit_runtime.d.ts +283 -118
- package/dist/modules/credit_runtime.js +500 -231
- 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/daemon_node_health.d.ts +4 -3
- package/dist/modules/dexbot_class.d.ts +213 -146
- package/dist/modules/dexbot_class.js +183 -86
- package/dist/modules/dexbot_cow_runtime.d.ts +160 -87
- package/dist/modules/dexbot_cow_runtime.js +302 -234
- package/dist/modules/dexbot_credential_client.d.ts +19 -18
- package/dist/modules/dexbot_credential_client.js +1 -2
- package/dist/modules/dexbot_fill_runtime.d.ts +63 -49
- package/dist/modules/dexbot_fill_runtime.js +53 -47
- package/dist/modules/dexbot_maintenance_runtime.d.ts +127 -71
- package/dist/modules/dexbot_maintenance_runtime.js +187 -147
- package/dist/modules/dexbot_startup_runtime.d.ts +11 -11
- package/dist/modules/dexbot_startup_runtime.js +56 -57
- 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 +19 -13
- 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 -7
- 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/lazy_shim.d.ts +11 -0
- package/dist/modules/lazy_shim.js +16 -0
- package/dist/modules/market_adapter_whitelist.d.ts +9 -3
- package/dist/modules/market_adapter_whitelist.js +15 -3
- package/dist/modules/node_connect_policy.d.ts +3 -2
- package/dist/modules/node_failure_ledger.d.ts +6 -5
- 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 +16 -7
- package/dist/modules/order/format.js +15 -3
- package/dist/modules/order/genesis_policy.d.ts +24 -21
- package/dist/modules/order/genesis_policy.js +17 -10
- package/dist/modules/order/grid.d.ts +144 -36
- package/dist/modules/order/grid.js +226 -145
- 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 +264 -1
- package/dist/modules/order/logger.d.ts +46 -19
- package/dist/modules/order/logger.js +38 -49
- package/dist/modules/order/logger_state.d.ts +4 -4
- package/dist/modules/order/manager.d.ts +232 -191
- package/dist/modules/order/manager.js +110 -130
- 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 +153 -126
- package/dist/modules/order/utils/slot.d.ts +1 -1
- package/dist/modules/order/utils/system.d.ts +156 -26
- package/dist/modules/order/utils/system.js +103 -71
- package/dist/modules/order/utils/validate.d.ts +89 -41
- package/dist/modules/order/utils/validate.js +26 -24
- package/dist/modules/order/utils/withPoolRef.d.ts +6 -4
- 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 +33 -61
- 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 +14 -11
- 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 +9 -5
- 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 +1090 -6
- 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 +24 -4
- 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 +23 -11
- package/dist/modules/version_notice.js +6 -4
- package/dist/pm2.d.ts +28 -27
- package/dist/pm2.js +61 -40
- package/dist/scripts/analyze-credit.d.ts +2 -1
- package/dist/scripts/analyze-credit.js +23 -24
- package/dist/scripts/analyze-git.js +2 -15
- 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 +15 -13
- package/dist/scripts/check_any.d.ts +22 -0
- package/dist/scripts/check_any.js +158 -0
- package/dist/scripts/diagnose-pool-history.js +13 -13
- package/dist/scripts/print_grid.js +0 -1
- package/dist/scripts/run-tests.js +39 -8
- package/dist/scripts/runner.js +1 -1
- package/dist/scripts/sync-version.js +0 -10
- 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 +10 -12
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -2
- package/docs/COW_INVARIANTS.md +13 -6
- package/docs/DEXBOT_COMPARISON.md +8 -8
- package/docs/EVOLUTION.md +10 -8
- 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/WORKFLOW.md +1 -0
- package/docs/architecture.md +31 -19
- package/docs/developer_guide.md +6 -6
- package/market_adapter/README.md +12 -5
- package/modules/README.md +4 -1
- package/package.json +9 -9
- package/scripts/README.md +43 -38
- package/tests/README.md +25 -10
- package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
- package/dist/scripts/diagnose-kibana-candles.js +0 -82
- package/scripts/git-viewer.sh +0 -489
- package/scripts/postinstall.js +0 -16
|
@@ -6,7 +6,7 @@ import { getStorage } from './storage/index.js';
|
|
|
6
6
|
import * as client from './bitshares_client.js';
|
|
7
7
|
const { BitShares, waitForConnected } = client;
|
|
8
8
|
import * as chainOrders from './chain_orders.js';
|
|
9
|
-
import { blockchainToFloat, floatToBlockchainInt, resolveConfigValue, isPercentageString, parsePercentageString, roundToDecimals } from './order/utils/math.js';
|
|
9
|
+
import { blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, resolveConfigValue, isPercentageString, parsePercentageString, roundToDecimals } from './order/utils/math.js';
|
|
10
10
|
import { toFiniteNumber } from './order/format.js';
|
|
11
11
|
import { createBotKey } from './account_orders.js';
|
|
12
12
|
import * as fundRegistry from './fund_registry.js';
|
|
@@ -18,22 +18,28 @@ import { PATHS } from './paths.js';
|
|
|
18
18
|
import { deriveLiquidityPoolTokenValue, derivePriceWithBridges, ensureDir as ensureDirSync, } from './order/utils/system.js';
|
|
19
19
|
const storage = getStorage();
|
|
20
20
|
import { buildCollateralFallbackPlan, buildDebtFirstCrPlan, positiveOrNull, resolveMinCollateralIncreaseThreshold, resolveTargetCollateralRatio, } from './cr_planner.js';
|
|
21
|
-
import { borrowAmountForCollateral as sharedBorrowAmountForCollateral, collateralValueFromOfferPrice as sharedCollateralValueFromOfferPrice, creditDealFee as sharedCreditDealFee, dailyOfferFeeRate as sharedDailyOfferFeeRate, extractOfferConversionRate as sharedExtractOfferConversionRate, normalizeCollateralMap, requiredCollateralForBorrow as sharedRequiredCollateralForBorrow, } from './credit_pricing.js';
|
|
21
|
+
import { borrowAmountForCollateral as sharedBorrowAmountForCollateral, capBorrowToCollateral as sharedCapBorrowToCollateral, collateralValueFromOfferPrice as sharedCollateralValueFromOfferPrice, creditDealFee as sharedCreditDealFee, dailyOfferFeeRate as sharedDailyOfferFeeRate, extractOfferConversionRate as sharedExtractOfferConversionRate, normalizeCollateralMap, requiredCollateralForBorrow as sharedRequiredCollateralForBorrow, } from './credit_pricing.js';
|
|
22
22
|
import { getErrorMessage, resolveSeamMsOrNull } from './utils/errors.js';
|
|
23
23
|
const CREDIT_FEE_RATE_DENOM = FEE_PARAMETERS.GRAPHENE_FEE_RATE_DENOM;
|
|
24
24
|
const ZERO_ASSET_ID = NATIVE_CLIENT.CHAIN.CORE_ASSET_ID;
|
|
25
25
|
const DEFAULT_STATE_DIR = PATHS.CREDIT_RUNTIME_DIR;
|
|
26
26
|
const GRAPHENE_COLLATERAL_RATIO_DENOM = FEE_PARAMETERS.GRAPHENE_COLLATERAL_RATIO_DENOM;
|
|
27
|
+
// Raw debt-asset units kept unspent by a renewal repay, so the repay still fits
|
|
28
|
+
// if the free balance drifts by a tick between the balance read and broadcast.
|
|
29
|
+
// The on-chain repay fee is exact, so without this the sizing can land precisely
|
|
30
|
+
// on the free balance and any one-unit drift would fail the whole batch.
|
|
31
|
+
const CREDIT_REBORROW_FREE_BALANCE_BUFFER_INT = 1;
|
|
27
32
|
function deepClone(value) {
|
|
28
33
|
return value === undefined ? undefined : JSON.parse(JSON.stringify(value));
|
|
29
34
|
}
|
|
30
35
|
function normalizeResolvedPriceResult(value, liveSource, missingSource) {
|
|
31
36
|
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
32
|
-
const
|
|
37
|
+
const v = value;
|
|
38
|
+
const price = positiveOrNull(v.price);
|
|
33
39
|
return {
|
|
34
40
|
price,
|
|
35
41
|
source: price !== null
|
|
36
|
-
? (typeof
|
|
42
|
+
? (typeof v.source === 'string' && v.source ? v.source : liveSource)
|
|
37
43
|
: missingSource,
|
|
38
44
|
};
|
|
39
45
|
}
|
|
@@ -65,7 +71,8 @@ function toGrapheneCollateralRatio(value) {
|
|
|
65
71
|
return Number.isInteger(scaled) && scaled > 0 && scaled <= 0xffff ? scaled : null;
|
|
66
72
|
}
|
|
67
73
|
function getPriceQuoteAssetId(price) {
|
|
68
|
-
|
|
74
|
+
const p = price;
|
|
75
|
+
return p?.quote?.asset_id || null;
|
|
69
76
|
}
|
|
70
77
|
function toAmountObject(amount, assetId) {
|
|
71
78
|
return {
|
|
@@ -126,9 +133,10 @@ function normalizeAmountSpec(spec) {
|
|
|
126
133
|
return { amount: spec, assetId: null };
|
|
127
134
|
}
|
|
128
135
|
if (typeof spec === 'object') {
|
|
136
|
+
const s = spec;
|
|
129
137
|
return {
|
|
130
|
-
amount:
|
|
131
|
-
assetId:
|
|
138
|
+
amount: s.amount ?? s.value ?? null,
|
|
139
|
+
assetId: s.asset_id || s.assetId || s.asset || null,
|
|
132
140
|
};
|
|
133
141
|
}
|
|
134
142
|
return null;
|
|
@@ -166,58 +174,87 @@ function parseFullAccount(fullAccountResult) {
|
|
|
166
174
|
function parseCallOrders(accountObj) {
|
|
167
175
|
if (!accountObj || typeof accountObj !== 'object')
|
|
168
176
|
return [];
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
177
|
+
const obj = accountObj;
|
|
178
|
+
if (Array.isArray(obj.call_orders))
|
|
179
|
+
return obj.call_orders;
|
|
180
|
+
if (obj.account && Array.isArray(obj.account.call_orders))
|
|
181
|
+
return obj.account.call_orders;
|
|
173
182
|
return [];
|
|
174
183
|
}
|
|
184
|
+
/**
|
|
185
|
+
* Shared ranking fields for a credit-offer candidate. Every selector scores
|
|
186
|
+
* offers through this helper so the ranking inputs cannot drift apart.
|
|
187
|
+
*/
|
|
188
|
+
function offerRankingFields(dailyRate, offer) {
|
|
189
|
+
return {
|
|
190
|
+
dailyRate,
|
|
191
|
+
feeRate: toFiniteNumber(offer.fee_rate, Number.MAX_SAFE_INTEGER),
|
|
192
|
+
balance: toFiniteNumber(offer.current_balance, 0),
|
|
193
|
+
duration: toFiniteNumber(offer.max_duration_seconds, 0),
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Canonical credit-offer ranking policy: cheapest daily rate first, then the
|
|
198
|
+
* lowest fee rate, then the longest duration, then the largest remaining
|
|
199
|
+
* balance, then a stable tie-break on offer id. Single source of truth for
|
|
200
|
+
* all offer selectors.
|
|
201
|
+
*/
|
|
202
|
+
function compareCreditOfferCandidates(a, b) {
|
|
203
|
+
return a.dailyRate - b.dailyRate
|
|
204
|
+
|| a.feeRate - b.feeRate
|
|
205
|
+
|| b.duration - a.duration
|
|
206
|
+
|| b.balance - a.balance
|
|
207
|
+
|| String(a.offer.id).localeCompare(String(b.offer.id));
|
|
208
|
+
}
|
|
175
209
|
function parseDealSummary(deal) {
|
|
176
210
|
if (!deal || typeof deal !== 'object')
|
|
177
211
|
return null;
|
|
212
|
+
const d = deal;
|
|
178
213
|
return {
|
|
179
|
-
id:
|
|
180
|
-
borrower:
|
|
181
|
-
offerId:
|
|
182
|
-
offerOwner:
|
|
183
|
-
debtAssetId:
|
|
184
|
-
debtAmount: toFiniteNumber(
|
|
185
|
-
collateralAssetId:
|
|
186
|
-
collateralAmount: toFiniteNumber(
|
|
187
|
-
feeRate: toFiniteNumber(
|
|
188
|
-
latestRepayTime:
|
|
189
|
-
autoRepay: toFiniteNumber(
|
|
214
|
+
id: d.id,
|
|
215
|
+
borrower: d.borrower,
|
|
216
|
+
offerId: d.offerId || d.offer_id || null,
|
|
217
|
+
offerOwner: d.offerOwner || d.offer_owner || null,
|
|
218
|
+
debtAssetId: d.debtAssetId || d.debt_asset || null,
|
|
219
|
+
debtAmount: toFiniteNumber(d.debtAmount ?? d.debt_amount, 0) || 0,
|
|
220
|
+
collateralAssetId: d.collateralAssetId || d.collateral_asset || null,
|
|
221
|
+
collateralAmount: toFiniteNumber(d.collateralAmount ?? d.collateral_amount, 0) || 0,
|
|
222
|
+
feeRate: toFiniteNumber(d.feeRate ?? d.fee_rate, 0) || 0,
|
|
223
|
+
latestRepayTime: d.latestRepayTime || d.latest_repay_time || null,
|
|
224
|
+
autoRepay: toFiniteNumber(d.autoRepay ?? d.auto_repay, 0) || 0,
|
|
190
225
|
};
|
|
191
226
|
}
|
|
192
227
|
function parseCallOrderSummary(order) {
|
|
193
228
|
if (!order || typeof order !== 'object')
|
|
194
229
|
return null;
|
|
230
|
+
const o = order;
|
|
195
231
|
return {
|
|
196
|
-
id:
|
|
197
|
-
borrower:
|
|
198
|
-
debtAssetId:
|
|
199
|
-
debtAmount: toFiniteNumber(
|
|
200
|
-
collateralAssetId:
|
|
201
|
-
collateralAmount: toFiniteNumber(
|
|
202
|
-
debt:
|
|
203
|
-
collateral:
|
|
204
|
-
call_price:
|
|
232
|
+
id: o.id || null,
|
|
233
|
+
borrower: o.borrower || null,
|
|
234
|
+
debtAssetId: o.debtAssetId || o.call_price?.quote?.asset_id || null,
|
|
235
|
+
debtAmount: toFiniteNumber(o.debt?.amount ?? o.debtAmount, 0) || 0,
|
|
236
|
+
collateralAssetId: o.collateralAssetId || o.call_price?.base?.asset_id || null,
|
|
237
|
+
collateralAmount: toFiniteNumber(o.collateral?.amount ?? o.collateralAmount, 0) || 0,
|
|
238
|
+
debt: o.debt || null,
|
|
239
|
+
collateral: o.collateral || null,
|
|
240
|
+
call_price: o.call_price || null,
|
|
205
241
|
};
|
|
206
242
|
}
|
|
207
243
|
function parseCreditOfferSummary(offer) {
|
|
208
244
|
if (!offer || typeof offer !== 'object')
|
|
209
245
|
return null;
|
|
246
|
+
const o = offer;
|
|
210
247
|
return {
|
|
211
|
-
id:
|
|
212
|
-
ownerAccount:
|
|
213
|
-
assetType:
|
|
214
|
-
totalBalance: toFiniteNumber(
|
|
215
|
-
currentBalance: toFiniteNumber(
|
|
216
|
-
feeRate: toFiniteNumber(
|
|
217
|
-
maxDurationSeconds: toFiniteNumber(
|
|
218
|
-
minDealAmount: toFiniteNumber(
|
|
219
|
-
enabled: !!
|
|
220
|
-
acceptableCollateral:
|
|
248
|
+
id: o.id || null,
|
|
249
|
+
ownerAccount: o.owner_account || o.ownerAccount || null,
|
|
250
|
+
assetType: o.asset_type || o.assetType || null,
|
|
251
|
+
totalBalance: toFiniteNumber(o.total_balance ?? o.totalBalance, 0) || 0,
|
|
252
|
+
currentBalance: toFiniteNumber(o.current_balance ?? o.currentBalance, 0) || 0,
|
|
253
|
+
feeRate: toFiniteNumber(o.fee_rate ?? o.feeRate, 0) || 0,
|
|
254
|
+
maxDurationSeconds: toFiniteNumber(o.max_duration_seconds ?? o.maxDurationSeconds, 0) || 0,
|
|
255
|
+
minDealAmount: toFiniteNumber(o.min_deal_amount ?? o.minDealAmount, 0) || 0,
|
|
256
|
+
enabled: !!o.enabled,
|
|
257
|
+
acceptableCollateral: o.acceptable_collateral || o.acceptableCollateral || null,
|
|
221
258
|
};
|
|
222
259
|
}
|
|
223
260
|
class CreditRuntime {
|
|
@@ -227,6 +264,8 @@ class CreditRuntime {
|
|
|
227
264
|
log;
|
|
228
265
|
warn;
|
|
229
266
|
botKey;
|
|
267
|
+
_getOnChainAssetBalancesFn;
|
|
268
|
+
_lastResolvedSettleDelayMs;
|
|
230
269
|
stateDir;
|
|
231
270
|
statePath;
|
|
232
271
|
_assetCache;
|
|
@@ -246,7 +285,7 @@ class CreditRuntime {
|
|
|
246
285
|
this.log = typeof this.bot._log === 'function' ? this.bot._log.bind(this.bot) : console.log.bind(console);
|
|
247
286
|
this.warn = typeof this.bot._warn === 'function' ? this.bot._warn.bind(this.bot) : console.warn.bind(console);
|
|
248
287
|
this.botKey = this.config.botKey
|
|
249
|
-
|| createBotKey(this.config, this.config.botIndex ?? 0);
|
|
288
|
+
|| createBotKey(this.config, Number(this.config.botIndex ?? 0));
|
|
250
289
|
this.stateDir = this.options.stateDir || DEFAULT_STATE_DIR;
|
|
251
290
|
this.statePath = path.join(this.stateDir, `${this.botKey}.json`);
|
|
252
291
|
this._assetCache = new Map();
|
|
@@ -280,9 +319,8 @@ class CreditRuntime {
|
|
|
280
319
|
};
|
|
281
320
|
}
|
|
282
321
|
get debtPolicy() {
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
: null;
|
|
322
|
+
const dp = this.config?.debtPolicy;
|
|
323
|
+
return dp && typeof dp === 'object' ? dp : null;
|
|
286
324
|
}
|
|
287
325
|
isEnabled() {
|
|
288
326
|
const dp = this.debtPolicy;
|
|
@@ -303,7 +341,7 @@ class CreditRuntime {
|
|
|
303
341
|
continue;
|
|
304
342
|
let cached = this._assetCache.get(String(item.asset));
|
|
305
343
|
if (!cached && item.asset) {
|
|
306
|
-
cached = await this._resolveAsset(item.asset);
|
|
344
|
+
cached = (await this._resolveAsset(item.asset)) ?? undefined;
|
|
307
345
|
}
|
|
308
346
|
if (cached && String(cached.id) === String(assetId)) {
|
|
309
347
|
return item;
|
|
@@ -381,16 +419,18 @@ class CreditRuntime {
|
|
|
381
419
|
async _resolveAccountId(accountRef) {
|
|
382
420
|
if (!accountRef)
|
|
383
421
|
return null;
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
422
|
+
const ref = String(accountRef);
|
|
423
|
+
if (/^1\.2\.\d+$/.test(ref))
|
|
424
|
+
return ref;
|
|
425
|
+
return chainOrders.resolveAccountId(ref);
|
|
387
426
|
}
|
|
388
427
|
async _resolveAccountName(accountRef) {
|
|
389
428
|
if (!accountRef)
|
|
390
429
|
return null;
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
430
|
+
const ref = String(accountRef);
|
|
431
|
+
if (!/^1\.2\.\d+$/.test(ref))
|
|
432
|
+
return ref;
|
|
433
|
+
return chainOrders.resolveAccountName(ref);
|
|
394
434
|
}
|
|
395
435
|
async _getFullAccount(accountRef) {
|
|
396
436
|
if (!accountRef)
|
|
@@ -400,8 +440,8 @@ class CreditRuntime {
|
|
|
400
440
|
}
|
|
401
441
|
const accounts = await this._dbCall('get_full_accounts', [[accountRef], false]);
|
|
402
442
|
const account = parseFullAccount(accounts);
|
|
403
|
-
this._fullAccountCache = { ref: String(accountRef), account: account
|
|
404
|
-
return account
|
|
443
|
+
this._fullAccountCache = { ref: String(accountRef), account: (account ?? null) };
|
|
444
|
+
return (account ?? null);
|
|
405
445
|
}
|
|
406
446
|
async _resolveAsset(assetRef) {
|
|
407
447
|
if (!assetRef)
|
|
@@ -411,7 +451,7 @@ class CreditRuntime {
|
|
|
411
451
|
// their own cache slot for the same asset.
|
|
412
452
|
const cacheKey = normalizeAssetRef(assetRef);
|
|
413
453
|
if (this._assetCache.has(cacheKey)) {
|
|
414
|
-
return this._assetCache.get(cacheKey);
|
|
454
|
+
return this._assetCache.get(cacheKey) ?? null;
|
|
415
455
|
}
|
|
416
456
|
await waitForConnected();
|
|
417
457
|
const asset = await resolveAssetByRef(BitShares, cacheKey);
|
|
@@ -428,11 +468,11 @@ class CreditRuntime {
|
|
|
428
468
|
}
|
|
429
469
|
async _resolveBitassetData(assetRef) {
|
|
430
470
|
const asset = await this._resolveAsset(assetRef);
|
|
431
|
-
const bitassetDataId = asset?.bitasset_data_id
|
|
471
|
+
const bitassetDataId = asset?.bitasset_data_id != null ? String(asset.bitasset_data_id) : null;
|
|
432
472
|
if (!bitassetDataId)
|
|
433
473
|
return null;
|
|
434
474
|
if (this._objectCache.has(bitassetDataId)) {
|
|
435
|
-
return this._objectCache.get(bitassetDataId);
|
|
475
|
+
return this._objectCache.get(bitassetDataId) ?? null;
|
|
436
476
|
}
|
|
437
477
|
const objects = await this._dbCall('get_objects', [[bitassetDataId]]);
|
|
438
478
|
const bitassetData = Array.isArray(objects) ? objects[0] : null;
|
|
@@ -521,17 +561,17 @@ class CreditRuntime {
|
|
|
521
561
|
}
|
|
522
562
|
else {
|
|
523
563
|
if (!accountRef) {
|
|
524
|
-
throw new Error(`Unable to resolve account for percentage amount on ${asset.id}`);
|
|
564
|
+
throw new Error(`Unable to resolve account for percentage amount on ${String(asset.id)}`);
|
|
525
565
|
}
|
|
526
|
-
const balances = await chainOrders.getOnChainAssetBalances(accountRef, [asset.id]);
|
|
527
|
-
const balance = balances
|
|
566
|
+
const balances = await chainOrders.getOnChainAssetBalances(accountRef, [String(asset.id)]);
|
|
567
|
+
const balance = this._pickOnChainBalanceEntry(balances, asset.id, asset);
|
|
528
568
|
total = toFiniteNumber(balance?.[balanceField], NaN);
|
|
529
569
|
if (!Number.isFinite(total) || total < 0) {
|
|
530
|
-
throw new Error(`Unable to resolve ${referenceLabel} for ${asset.id}`);
|
|
570
|
+
throw new Error(`Unable to resolve ${referenceLabel} for ${String(asset.id)}`);
|
|
531
571
|
}
|
|
532
572
|
}
|
|
533
573
|
if (!Number.isFinite(total) || total < 0) {
|
|
534
|
-
throw new Error(`Unable to resolve account for percentage amount on ${asset.id}`);
|
|
574
|
+
throw new Error(`Unable to resolve account for percentage amount on ${String(asset.id)}`);
|
|
535
575
|
}
|
|
536
576
|
}
|
|
537
577
|
const resolved = resolveConfigValue(normalized.amount, total);
|
|
@@ -539,7 +579,7 @@ class CreditRuntime {
|
|
|
539
579
|
return null;
|
|
540
580
|
}
|
|
541
581
|
if (isPercent && total !== null && resolved > total) {
|
|
542
|
-
throw new Error(`Requested amount ${resolved} exceeds available ${balanceField} balance ${total} for ${asset.id}`);
|
|
582
|
+
throw new Error(`Requested amount ${resolved} exceeds available ${balanceField} balance ${total} for ${String(asset.id)}`);
|
|
543
583
|
}
|
|
544
584
|
const intValue = floatToBlockchainInt(resolved, asset.precision);
|
|
545
585
|
if (!Number.isFinite(intValue) || intValue <= 0) {
|
|
@@ -556,7 +596,7 @@ class CreditRuntime {
|
|
|
556
596
|
continue;
|
|
557
597
|
let cached = this._assetCache.get(String(item.asset));
|
|
558
598
|
if (!cached && item.asset) {
|
|
559
|
-
cached = await this._resolveAsset(item.asset);
|
|
599
|
+
cached = (await this._resolveAsset(item.asset)) ?? undefined;
|
|
560
600
|
}
|
|
561
601
|
if (cached && String(cached.id) === String(offerDebtAssetId)) {
|
|
562
602
|
return item;
|
|
@@ -710,7 +750,7 @@ class CreditRuntime {
|
|
|
710
750
|
// resolved above.
|
|
711
751
|
if (!cachedIsFresh) {
|
|
712
752
|
if (collateralAsset?.for_liquidity_pool && debtAsset?.id) {
|
|
713
|
-
const poolRate = await deriveLiquidityPoolTokenValue(BitShares, collateralAsset.id, debtAsset.id, 'auto', true).catch((e) => {
|
|
753
|
+
const poolRate = await deriveLiquidityPoolTokenValue(BitShares, String(collateralAsset.id), String(debtAsset.id), 'auto', true).catch((e) => {
|
|
714
754
|
this.log(`credit runtime: pool token rate derivation failed for ${collateralAsset.id}/${debtAsset.id}: ${getErrorMessage(e)}`);
|
|
715
755
|
return null;
|
|
716
756
|
});
|
|
@@ -723,7 +763,7 @@ class CreditRuntime {
|
|
|
723
763
|
}
|
|
724
764
|
}
|
|
725
765
|
if (collateralAsset?.id && debtAsset?.id) {
|
|
726
|
-
const bridged = await derivePriceWithBridges(BitShares, collateralAsset.id, debtAsset.id).catch((e) => {
|
|
766
|
+
const bridged = await derivePriceWithBridges(BitShares, String(collateralAsset.id), String(debtAsset.id)).catch((e) => {
|
|
727
767
|
this.log(`credit runtime: market rate derivation failed for ${collateralAsset.id}/${debtAsset.id}: ${getErrorMessage(e)}`);
|
|
728
768
|
return null;
|
|
729
769
|
});
|
|
@@ -770,12 +810,12 @@ class CreditRuntime {
|
|
|
770
810
|
allGroupsResolved = false;
|
|
771
811
|
continue;
|
|
772
812
|
}
|
|
773
|
-
const totalCollateralAvailable = await this._getCollateralPercentageBase(accountRef, collateralAsset.id);
|
|
813
|
+
const totalCollateralAvailable = await this._getCollateralPercentageBase(accountRef, String(collateralAsset.id));
|
|
774
814
|
const totalMaxCollateral = resolveConfigValue(dp.maxCollateralAmount ?? '100%', totalCollateralAvailable);
|
|
775
815
|
const C_total = Math.min(totalCollateralAvailable, totalMaxCollateral);
|
|
776
816
|
let groupHasNoUsablePrice = false;
|
|
777
817
|
const weightEntries = await Promise.all(items.map(async (item) => {
|
|
778
|
-
const ratio = item.outputWeight ?? 1;
|
|
818
|
+
const ratio = Number(item.outputWeight ?? 1);
|
|
779
819
|
const resolvedAsset = await this._resolveAsset(item.asset);
|
|
780
820
|
const assetId = resolvedAsset?.id ? String(resolvedAsset.id) : null;
|
|
781
821
|
let targetCr = 1.0;
|
|
@@ -827,7 +867,7 @@ class CreditRuntime {
|
|
|
827
867
|
const resolvedAsset = await this._resolveAsset(item.asset);
|
|
828
868
|
const assetId = resolvedAsset?.id ? String(resolvedAsset.id) : null;
|
|
829
869
|
if (assetId && collateralAsset.id) {
|
|
830
|
-
const posKey = this._positionKey(assetId, collateralAsset.id);
|
|
870
|
+
const posKey = this._positionKey(assetId, String(collateralAsset.id));
|
|
831
871
|
validAssetIds.add(posKey);
|
|
832
872
|
}
|
|
833
873
|
}
|
|
@@ -842,7 +882,7 @@ class CreditRuntime {
|
|
|
842
882
|
for (const { weight, assetId } of weightEntries) {
|
|
843
883
|
if (!assetId || !collateralAsset.id)
|
|
844
884
|
continue;
|
|
845
|
-
const posKey = this._positionKey(assetId, collateralAsset.id);
|
|
885
|
+
const posKey = this._positionKey(assetId, String(collateralAsset.id));
|
|
846
886
|
validAssetIds.add(posKey);
|
|
847
887
|
const C_i = (C_total * weight) / totalWeight;
|
|
848
888
|
if (!this.state.positions[posKey])
|
|
@@ -894,21 +934,23 @@ class CreditRuntime {
|
|
|
894
934
|
}
|
|
895
935
|
}
|
|
896
936
|
_getCreditDebtForAsset(asset) {
|
|
897
|
-
|
|
898
|
-
const deals = Array.isArray(this.state?.creditDeals) ? this.state.creditDeals : [];
|
|
899
|
-
return deals.reduce((sum, deal) => {
|
|
900
|
-
if (String(deal?.debtAssetId) === String(assetId)) {
|
|
901
|
-
return sum + (blockchainAmountToFloat(deal?.debtAmount, asset) || 0);
|
|
902
|
-
}
|
|
903
|
-
return sum;
|
|
904
|
-
}, 0);
|
|
937
|
+
return this._sumCreditFieldForAsset(asset, 'debtAssetId', 'debtAmount');
|
|
905
938
|
}
|
|
906
939
|
_getCreditCollateralForAsset(asset) {
|
|
907
|
-
|
|
940
|
+
return this._sumCreditFieldForAsset(asset, 'collateralAssetId', 'collateralAmount');
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* Sum a raw credit-deal amount across all deals matching `asset` on the
|
|
944
|
+
* given asset-id field, converted to float at the asset's precision.
|
|
945
|
+
* Shared by the debt and collateral totals (see _getCreditDebtForAsset and
|
|
946
|
+
* _getCreditCollateralForAsset).
|
|
947
|
+
*/
|
|
948
|
+
_sumCreditFieldForAsset(asset, assetField, amountField) {
|
|
949
|
+
const assetId = asset?.id ?? asset;
|
|
908
950
|
const deals = Array.isArray(this.state?.creditDeals) ? this.state.creditDeals : [];
|
|
909
951
|
return deals.reduce((sum, deal) => {
|
|
910
|
-
if (String(deal?.
|
|
911
|
-
return sum + (blockchainAmountToFloat(deal?.
|
|
952
|
+
if (String(deal?.[assetField]) === String(assetId)) {
|
|
953
|
+
return sum + (blockchainAmountToFloat(deal?.[amountField], asset) || 0);
|
|
912
954
|
}
|
|
913
955
|
return sum;
|
|
914
956
|
}, 0);
|
|
@@ -920,11 +962,11 @@ class CreditRuntime {
|
|
|
920
962
|
if (!asset)
|
|
921
963
|
return null;
|
|
922
964
|
const [balances, account, deals] = await Promise.all([
|
|
923
|
-
chainOrders.getOnChainAssetBalances(accountId, [assetId]),
|
|
965
|
+
chainOrders.getOnChainAssetBalances(accountId, [String(assetId)]),
|
|
924
966
|
this._getFullAccount(accountId).catch(() => null),
|
|
925
967
|
this._fetchBorrowerDeals().catch(() => []),
|
|
926
968
|
]);
|
|
927
|
-
const balance = balances
|
|
969
|
+
const balance = this._pickOnChainBalanceEntry(balances, assetId, asset);
|
|
928
970
|
const onChainTotal = toFiniteNumber(balance?.total, NaN);
|
|
929
971
|
if (!Number.isFinite(onChainTotal)) {
|
|
930
972
|
return null;
|
|
@@ -947,7 +989,7 @@ class CreditRuntime {
|
|
|
947
989
|
const accountName = getAccountName(this.bot);
|
|
948
990
|
const botName = this.botKey;
|
|
949
991
|
if (accountName && botName) {
|
|
950
|
-
const effective = fundRegistry.getEffectiveCollateralAllocationSync(accountName, botName, assetId, total);
|
|
992
|
+
const effective = fundRegistry.getEffectiveCollateralAllocationSync(accountName, botName, String(assetId), total);
|
|
951
993
|
if (effective !== null)
|
|
952
994
|
return effective;
|
|
953
995
|
}
|
|
@@ -964,7 +1006,7 @@ class CreditRuntime {
|
|
|
964
1006
|
return;
|
|
965
1007
|
const referenceAmount = await this._getCollateralPercentageBase(accountId, collateralAsset.id);
|
|
966
1008
|
if (!Number.isFinite(referenceAmount)) {
|
|
967
|
-
throw new Error(`Unable to resolve collateral percentage base for ${collateralAsset.id}`);
|
|
1009
|
+
throw new Error(`Unable to resolve collateral percentage base for ${String(collateralAsset.id)}`);
|
|
968
1010
|
}
|
|
969
1011
|
limitFloat = resolveConfigValue(maxCollateralAmountValue, referenceAmount);
|
|
970
1012
|
}
|
|
@@ -1023,7 +1065,7 @@ class CreditRuntime {
|
|
|
1023
1065
|
if (!Number.isFinite(collateralAmountFloat) || collateralAmountFloat <= 0) {
|
|
1024
1066
|
return null;
|
|
1025
1067
|
}
|
|
1026
|
-
const valuePerShare = await deriveLiquidityPoolTokenValue(BitShares, collateralAsset.id, debtAsset.id, 'auto', true);
|
|
1068
|
+
const valuePerShare = await deriveLiquidityPoolTokenValue(BitShares, String(collateralAsset.id), String(debtAsset.id), 'auto', true);
|
|
1027
1069
|
if (valuePerShare == null || !Number.isFinite(valuePerShare) || valuePerShare <= 0) {
|
|
1028
1070
|
return null;
|
|
1029
1071
|
}
|
|
@@ -1044,7 +1086,7 @@ class CreditRuntime {
|
|
|
1044
1086
|
if (!accountId)
|
|
1045
1087
|
return [];
|
|
1046
1088
|
const dealObjects = await this._dbCall('get_credit_deals_by_borrower', [accountId]);
|
|
1047
|
-
const normalized = Array.isArray(dealObjects) ? dealObjects.map(parseDealSummary).filter(
|
|
1089
|
+
const normalized = Array.isArray(dealObjects) ? dealObjects.map(parseDealSummary).filter((d) => d !== null) : [];
|
|
1048
1090
|
this._borrowerDealsCache = normalized;
|
|
1049
1091
|
return normalized;
|
|
1050
1092
|
}
|
|
@@ -1055,7 +1097,7 @@ class CreditRuntime {
|
|
|
1055
1097
|
}
|
|
1056
1098
|
const accountId = await this._resolveAccountId(accountRef) || accountRef;
|
|
1057
1099
|
const offers = await this._dbCall('get_credit_offers_by_owner', [accountId]);
|
|
1058
|
-
return Array.isArray(offers) ? offers.map(parseCreditOfferSummary).filter(
|
|
1100
|
+
return Array.isArray(offers) ? offers.map(parseCreditOfferSummary).filter((o) => o !== null) : [];
|
|
1059
1101
|
}
|
|
1060
1102
|
async _buildDebtSnapshot() {
|
|
1061
1103
|
const snapshot = {
|
|
@@ -1082,19 +1124,22 @@ class CreditRuntime {
|
|
|
1082
1124
|
}
|
|
1083
1125
|
snapshot.assets[key][field] += amount;
|
|
1084
1126
|
};
|
|
1085
|
-
for (const
|
|
1127
|
+
for (const entry of snapshot.mpaCallOrders) {
|
|
1128
|
+
const order = entry;
|
|
1086
1129
|
const debtAsset = order?.debtAssetId ? await this._resolveAsset(order.debtAssetId) : null;
|
|
1087
1130
|
const collateralAsset = order?.collateralAssetId ? await this._resolveAsset(order.collateralAssetId) : null;
|
|
1088
1131
|
bump(order?.debtAssetId, 'mpaDebt', blockchainAmountToFloat(order?.debtAmount, debtAsset) || 0);
|
|
1089
1132
|
bump(order?.collateralAssetId, 'mpaCollateral', blockchainAmountToFloat(order?.collateralAmount, collateralAsset) || 0);
|
|
1090
1133
|
}
|
|
1091
|
-
for (const
|
|
1134
|
+
for (const entry of snapshot.creditDeals) {
|
|
1135
|
+
const deal = entry;
|
|
1092
1136
|
const debtAsset = deal?.debtAssetId ? await this._resolveAsset(deal.debtAssetId) : null;
|
|
1093
1137
|
const collateralAsset = deal?.collateralAssetId ? await this._resolveAsset(deal.collateralAssetId) : null;
|
|
1094
1138
|
bump(deal?.debtAssetId, 'creditDebt', blockchainAmountToFloat(deal?.debtAmount, debtAsset) || 0);
|
|
1095
1139
|
bump(deal?.collateralAssetId, 'creditCollateral', blockchainAmountToFloat(deal?.collateralAmount, collateralAsset) || 0);
|
|
1096
1140
|
}
|
|
1097
|
-
for (const
|
|
1141
|
+
for (const entry of snapshot.ownedCreditOffers) {
|
|
1142
|
+
const offer = entry;
|
|
1098
1143
|
const asset = offer?.assetType ? await this._resolveAsset(offer.assetType) : null;
|
|
1099
1144
|
bump(offer?.assetType, 'offeredBalance', blockchainAmountToFloat(offer?.currentBalance, asset) || 0);
|
|
1100
1145
|
}
|
|
@@ -1123,7 +1168,7 @@ class CreditRuntime {
|
|
|
1123
1168
|
this.state.mpaCallOrders = callOrders;
|
|
1124
1169
|
const configuredCollateralAsset = await this._resolveAsset(lendingItem.collateralAsset);
|
|
1125
1170
|
const configuredCollateralAssetId = configuredCollateralAsset?.id ? String(configuredCollateralAsset.id) : null;
|
|
1126
|
-
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : assetId;
|
|
1171
|
+
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : String(assetId);
|
|
1127
1172
|
const candidateOrders = callOrders.filter((entry) => String(entry?.call_price?.quote?.asset_id) === assetId);
|
|
1128
1173
|
const createEmptyState = (reason) => {
|
|
1129
1174
|
const empty = {
|
|
@@ -1167,15 +1212,16 @@ class CreditRuntime {
|
|
|
1167
1212
|
const balancesFn = typeof this._getOnChainAssetBalancesFn === 'function'
|
|
1168
1213
|
? this._getOnChainAssetBalancesFn
|
|
1169
1214
|
: (acct, assets) => chainOrders.getOnChainAssetBalances(acct, assets);
|
|
1170
|
-
const collateralBalances = callOrderCollateralAssetId ? await balancesFn(accountRef, [callOrderCollateralAssetId]) : {};
|
|
1171
|
-
const
|
|
1215
|
+
const collateralBalances = callOrderCollateralAssetId ? await balancesFn(accountRef, [String(callOrderCollateralAssetId)]) : {};
|
|
1216
|
+
const collateralMap = collateralBalances;
|
|
1217
|
+
const collateralBalance = callOrderCollateralAssetId ? (collateralMap?.[String(callOrderCollateralAssetId)] || collateralMap?.[String(collateralAsset?.symbol)] || null) : null;
|
|
1172
1218
|
let currentCollateralFundsTotal = toFiniteNumber(collateralBalance?.total, undefined);
|
|
1173
1219
|
// Apply registry proportional split for shared-account credit bots
|
|
1174
1220
|
if (currentCollateralFundsTotal !== null && callOrderCollateralAssetId) {
|
|
1175
1221
|
const accountName = getAccountName(this.bot);
|
|
1176
1222
|
const botName = this.botKey;
|
|
1177
1223
|
if (accountName && botName) {
|
|
1178
|
-
const effective = fundRegistry.getEffectiveCollateralAllocationSync(accountName, botName, callOrderCollateralAssetId, currentCollateralFundsTotal);
|
|
1224
|
+
const effective = fundRegistry.getEffectiveCollateralAllocationSync(accountName, botName, String(callOrderCollateralAssetId), currentCollateralFundsTotal);
|
|
1179
1225
|
if (effective !== null)
|
|
1180
1226
|
currentCollateralFundsTotal = effective;
|
|
1181
1227
|
}
|
|
@@ -1190,7 +1236,7 @@ class CreditRuntime {
|
|
|
1190
1236
|
? collateralAmount / (debtAmount * feedPrice)
|
|
1191
1237
|
: null;
|
|
1192
1238
|
const posState = {
|
|
1193
|
-
activeCallOrderId: callOrder
|
|
1239
|
+
activeCallOrderId: callOrder?.id || null,
|
|
1194
1240
|
debtAssetId: assetId,
|
|
1195
1241
|
currentCollateralAssetId: callOrderCollateralAssetId,
|
|
1196
1242
|
currentDebtAmount: debtAmount,
|
|
@@ -1219,10 +1265,10 @@ class CreditRuntime {
|
|
|
1219
1265
|
}
|
|
1220
1266
|
const assetId = String(debtAsset.id);
|
|
1221
1267
|
const normalizedDeals = Array.isArray(options.deals)
|
|
1222
|
-
? options.deals.map(parseDealSummary).filter(
|
|
1268
|
+
? options.deals.map(parseDealSummary).filter((d) => d !== null)
|
|
1223
1269
|
: await this._fetchBorrowerDeals();
|
|
1224
1270
|
const ownedCreditOffers = Array.isArray(options.ownedCreditOffers)
|
|
1225
|
-
? options.ownedCreditOffers.map(parseCreditOfferSummary).filter(
|
|
1271
|
+
? options.ownedCreditOffers.map(parseCreditOfferSummary).filter((o) => o !== null)
|
|
1226
1272
|
: await this._fetchOwnedCreditOffers();
|
|
1227
1273
|
const trackedOffers = new Map();
|
|
1228
1274
|
const offerIdsFromDeals = normalizedDeals.map((deal) => deal.offerId).filter(Boolean);
|
|
@@ -1239,7 +1285,7 @@ class CreditRuntime {
|
|
|
1239
1285
|
}
|
|
1240
1286
|
const expectedCollateralAssetObj = await this._resolveAsset(lendingItem.collateralAsset);
|
|
1241
1287
|
const expectedCollateralId = expectedCollateralAssetObj?.id ? String(expectedCollateralAssetObj.id) : null;
|
|
1242
|
-
const posKey = expectedCollateralId ? this._positionKey(assetId, expectedCollateralId) : assetId;
|
|
1288
|
+
const posKey = expectedCollateralId ? this._positionKey(assetId, expectedCollateralId) : String(assetId);
|
|
1243
1289
|
// Cache conversion rate from discovered offers to avoid duplicate fetches in distribution.
|
|
1244
1290
|
// This is a price for the debt+collateral asset pair, not for a specific offer id.
|
|
1245
1291
|
// In practice, offers for the same pair should expose interchangeable acceptable-collateral pricing.
|
|
@@ -1361,7 +1407,7 @@ class CreditRuntime {
|
|
|
1361
1407
|
}
|
|
1362
1408
|
const collateralAsset = await this._resolveAsset(lendingItem.collateralAsset);
|
|
1363
1409
|
const collateralAssetId = collateralAsset?.id;
|
|
1364
|
-
const posKey = collateralAssetId ? this._positionKey(assetId, collateralAssetId) : assetId;
|
|
1410
|
+
const posKey = collateralAssetId ? this._positionKey(assetId, collateralAssetId) : String(assetId);
|
|
1365
1411
|
const posState = this.state.positions[posKey];
|
|
1366
1412
|
if (!posState)
|
|
1367
1413
|
return null;
|
|
@@ -1377,7 +1423,7 @@ class CreditRuntime {
|
|
|
1377
1423
|
targetCollateralRatio: lendingItem.targetCollateralRatio,
|
|
1378
1424
|
maxBorrowAmount: lendingItem.maxBorrowAmount,
|
|
1379
1425
|
maxBorrowAmountPerOperation: lendingItem.maxBorrowAmountPerOperation,
|
|
1380
|
-
maxCollateralAmount: posState.assignedCollateralBudget ?? lendingItem.maxCollateralAmount,
|
|
1426
|
+
maxCollateralAmount: (posState.assignedCollateralBudget ?? lendingItem.maxCollateralAmount),
|
|
1381
1427
|
collateralLimitReferenceAmount: posState.currentCollateralFundsTotal,
|
|
1382
1428
|
minCollateralIncreaseThreshold: lendingItem.minCollateralIncreaseThreshold,
|
|
1383
1429
|
debtOnly: lendingItem.debtOnly,
|
|
@@ -1399,11 +1445,11 @@ class CreditRuntime {
|
|
|
1399
1445
|
if (!policy || !plan)
|
|
1400
1446
|
return null;
|
|
1401
1447
|
if (plan.blocked) {
|
|
1402
|
-
throw new Error(plan.reason || 'MPA plan blocked');
|
|
1448
|
+
throw new Error(String(plan.reason || 'MPA plan blocked'));
|
|
1403
1449
|
}
|
|
1404
1450
|
const collateralAsset = await this._resolveAsset(lendingItem.collateralAsset);
|
|
1405
1451
|
const collateralAssetId = collateralAsset?.id;
|
|
1406
|
-
const posKey = collateralAssetId ? this._positionKey(assetId, collateralAssetId) : assetId;
|
|
1452
|
+
const posKey = collateralAssetId ? this._positionKey(assetId, collateralAssetId) : String(assetId);
|
|
1407
1453
|
const posState = this.state.positions[posKey];
|
|
1408
1454
|
if (!posState)
|
|
1409
1455
|
return null;
|
|
@@ -1422,8 +1468,8 @@ class CreditRuntime {
|
|
|
1422
1468
|
}
|
|
1423
1469
|
const debtDelta = leg === 'collateral' ? 0 : plan.debtDelta;
|
|
1424
1470
|
const collateralDelta = leg === 'debt' ? 0 : plan.collateralDelta;
|
|
1425
|
-
const debtInt = floatToBlockchainInt(debtDelta, debtAsset.precision);
|
|
1426
|
-
const collateralInt = floatToBlockchainInt(collateralDelta, callOrderCollateralAsset.precision);
|
|
1471
|
+
const debtInt = floatToBlockchainInt(debtDelta, Number(debtAsset.precision));
|
|
1472
|
+
const collateralInt = floatToBlockchainInt(collateralDelta, Number(callOrderCollateralAsset.precision));
|
|
1427
1473
|
if (debtInt === 0 && collateralInt === 0) {
|
|
1428
1474
|
return null;
|
|
1429
1475
|
}
|
|
@@ -1437,13 +1483,13 @@ class CreditRuntime {
|
|
|
1437
1483
|
op_data: {
|
|
1438
1484
|
fee: { amount: 0, asset_id: ZERO_ASSET_ID },
|
|
1439
1485
|
funding_account: accountId,
|
|
1440
|
-
delta_collateral: toAmountObject(collateralInt, callOrderCollateralAsset.id),
|
|
1441
|
-
delta_debt: toAmountObject(debtInt, debtAsset.id),
|
|
1486
|
+
delta_collateral: toAmountObject(collateralInt, String(callOrderCollateralAsset.id)),
|
|
1487
|
+
delta_debt: toAmountObject(debtInt, String(debtAsset.id)),
|
|
1442
1488
|
extensions,
|
|
1443
1489
|
}
|
|
1444
1490
|
};
|
|
1445
1491
|
}
|
|
1446
|
-
async buildCreditOfferAcceptOperation({ offer, borrowAmount, collateralAmount, autoRepay = false, specificPolicy = null, pendingRepayAmount = null, pendingReleaseCollateralAmount = null } = {}) {
|
|
1492
|
+
async buildCreditOfferAcceptOperation({ offer, borrowAmount, collateralAmount, autoRepay = false, specificPolicy = null, pendingRepayAmount = null, pendingReleaseCollateralAmount = null, availableCollateralAmount = null } = {}) {
|
|
1447
1493
|
let policy = specificPolicy;
|
|
1448
1494
|
if (!policy) {
|
|
1449
1495
|
const dp = this.debtPolicy;
|
|
@@ -1455,7 +1501,7 @@ class CreditRuntime {
|
|
|
1455
1501
|
continue;
|
|
1456
1502
|
let cached = this._assetCache.get(String(item.asset));
|
|
1457
1503
|
if (!cached && item.asset) {
|
|
1458
|
-
cached = await this._resolveAsset(item.asset);
|
|
1504
|
+
cached = (await this._resolveAsset(item.asset)) ?? undefined;
|
|
1459
1505
|
}
|
|
1460
1506
|
if (cached && String(cached.id) === String(offerDebtAssetId)) {
|
|
1461
1507
|
policy = item;
|
|
@@ -1480,7 +1526,7 @@ class CreditRuntime {
|
|
|
1480
1526
|
}
|
|
1481
1527
|
const validation = this._validateCreditPolicy(policy, offerObj, null);
|
|
1482
1528
|
if (!validation.allow) {
|
|
1483
|
-
throw new Error(validation.reason || 'credit offer rejected by policy');
|
|
1529
|
+
throw new Error(String(validation.reason || 'credit offer rejected by policy'));
|
|
1484
1530
|
}
|
|
1485
1531
|
const accountId = await this._resolveAccountId(getAccountRef(this.bot));
|
|
1486
1532
|
if (!accountId) {
|
|
@@ -1516,6 +1562,8 @@ class CreditRuntime {
|
|
|
1516
1562
|
}
|
|
1517
1563
|
let borrowInt = null;
|
|
1518
1564
|
let requiredCollateralInt = null;
|
|
1565
|
+
let requestedBorrowInt = null;
|
|
1566
|
+
let clampedByCollateral = false;
|
|
1519
1567
|
const requestedBorrowAmount = borrowAmount !== undefined && borrowAmount !== null
|
|
1520
1568
|
? positiveOrNull(borrowAmount)
|
|
1521
1569
|
: null;
|
|
@@ -1523,28 +1571,54 @@ class CreditRuntime {
|
|
|
1523
1571
|
throw new Error('borrowAmount must be positive');
|
|
1524
1572
|
}
|
|
1525
1573
|
if (requestedBorrowAmount !== null) {
|
|
1526
|
-
borrowInt = floatToBlockchainInt(requestedBorrowAmount, debtAsset.precision);
|
|
1574
|
+
borrowInt = floatToBlockchainInt(requestedBorrowAmount, Number(debtAsset.precision));
|
|
1527
1575
|
if (!Number.isFinite(borrowInt) || borrowInt <= 0) {
|
|
1528
1576
|
throw new Error('borrowAmount must be positive');
|
|
1529
1577
|
}
|
|
1578
|
+
requestedBorrowInt = borrowInt;
|
|
1579
|
+
// A reborrow can only lock the collateral the repay just released.
|
|
1580
|
+
// If the requested borrow needs more than that (for example the
|
|
1581
|
+
// market moved against the collateral since the deal was opened),
|
|
1582
|
+
// scale the borrow down to what the budget supports instead of
|
|
1583
|
+
// emitting an op that cannot be collateralized.
|
|
1584
|
+
const hasCollateralBudget = availableCollateralAmount !== null && availableCollateralAmount !== undefined && availableCollateralAmount > 0;
|
|
1585
|
+
if (hasCollateralBudget) {
|
|
1586
|
+
const cappedBorrowInt = sharedCapBorrowToCollateral(borrowInt, availableCollateralAmount, collateralPrice, String(debtAsset.id), String(collateralAsset.id));
|
|
1587
|
+
if (cappedBorrowInt === null || cappedBorrowInt <= 0) {
|
|
1588
|
+
throw new Error('released collateral cannot support any reborrow at offer price');
|
|
1589
|
+
}
|
|
1590
|
+
if (cappedBorrowInt < borrowInt) {
|
|
1591
|
+
this.log(`credit runtime: shrinking reborrow from ${blockchainToFloat(borrowInt, Number(debtAsset.precision))} to ${blockchainToFloat(cappedBorrowInt, Number(debtAsset.precision))} — released collateral ${blockchainToFloat(availableCollateralAmount, Number(collateralAsset.precision))} ${collateralAsset.symbol} supports only that much`);
|
|
1592
|
+
borrowInt = cappedBorrowInt;
|
|
1593
|
+
clampedByCollateral = true;
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1530
1596
|
this._enforceMaxBorrowAmount(policy, borrowInt, debtAsset, { pendingRepayAmount });
|
|
1531
1597
|
const minimumCollateralInt = this._calculateRequiredCollateral(borrowInt, collateralPrice, debtAsset, collateralAsset);
|
|
1532
1598
|
const collateralReferenceAmount = isPercentageAmountSpec(collateralSpec)
|
|
1533
|
-
? await this._getCollateralPercentageBase(accountId, collateralAsset.id)
|
|
1599
|
+
? await this._getCollateralPercentageBase(accountId, String(collateralAsset.id))
|
|
1534
1600
|
: null;
|
|
1535
1601
|
requiredCollateralInt = collateralSpec?.amount !== null && collateralSpec?.amount !== undefined
|
|
1536
1602
|
? await this._resolveAmountToBlockchainInt(collateralSpec, collateralAsset, accountId, { balanceField: 'total', referenceAmount: collateralReferenceAmount, referenceLabel: 'total collateral balance' })
|
|
1537
1603
|
: minimumCollateralInt;
|
|
1604
|
+
// An explicit collateral amount (e.g. a percentage spec) may still
|
|
1605
|
+
// exceed the released budget; cap it so the op cannot over-lock. Do
|
|
1606
|
+
// NOT recompute the borrow here — it was already clamped above and
|
|
1607
|
+
// must never grow back past the requested amount.
|
|
1608
|
+
if (hasCollateralBudget && requiredCollateralInt != null && requiredCollateralInt > availableCollateralAmount) {
|
|
1609
|
+
requiredCollateralInt = availableCollateralAmount;
|
|
1610
|
+
}
|
|
1538
1611
|
if (minimumCollateralInt != null && requiredCollateralInt != null && requiredCollateralInt < minimumCollateralInt) {
|
|
1539
1612
|
throw new Error(`collateral amount ${requiredCollateralInt} is below required collateral ${minimumCollateralInt}`);
|
|
1540
1613
|
}
|
|
1541
1614
|
}
|
|
1542
1615
|
else {
|
|
1543
1616
|
const collateralReferenceAmount = isPercentageAmountSpec(collateralSpec)
|
|
1544
|
-
? await this._getCollateralPercentageBase(accountId, collateralAsset.id)
|
|
1617
|
+
? await this._getCollateralPercentageBase(accountId, String(collateralAsset.id))
|
|
1545
1618
|
: null;
|
|
1546
1619
|
requiredCollateralInt = await this._resolveAmountToBlockchainInt(collateralSpec, collateralAsset, accountId, { balanceField: 'total', referenceAmount: collateralReferenceAmount, referenceLabel: 'total collateral balance' });
|
|
1547
1620
|
borrowInt = this._calculateBorrowAmountFromCollateral(requiredCollateralInt, collateralPrice, debtAsset, collateralAsset);
|
|
1621
|
+
requestedBorrowInt = borrowInt;
|
|
1548
1622
|
if (borrowInt != null && Number.isFinite(borrowInt) && borrowInt > 0) {
|
|
1549
1623
|
this._enforceMaxBorrowAmount(policy, borrowInt, debtAsset, { pendingRepayAmount });
|
|
1550
1624
|
}
|
|
@@ -1552,7 +1626,7 @@ class CreditRuntime {
|
|
|
1552
1626
|
// Enforce per-operation borrow limit
|
|
1553
1627
|
const maxPerOp = positiveOrNull(policy?.maxBorrowAmountPerOperation);
|
|
1554
1628
|
if (maxPerOp !== null && borrowInt != null && borrowInt > 0) {
|
|
1555
|
-
const borrowFloat = blockchainToFloat(borrowInt, debtAsset.precision);
|
|
1629
|
+
const borrowFloat = blockchainToFloat(borrowInt, Number(debtAsset.precision));
|
|
1556
1630
|
if (Number.isFinite(borrowFloat) && borrowFloat > maxPerOp) {
|
|
1557
1631
|
throw new Error(`borrowAmount ${borrowFloat} exceeds maxBorrowAmountPerOperation ${maxPerOp}`);
|
|
1558
1632
|
}
|
|
@@ -1592,7 +1666,7 @@ class CreditRuntime {
|
|
|
1592
1666
|
if (maxCollateralRatioValue === null) {
|
|
1593
1667
|
throw new Error('creditOffer maxCollateralRatio is required');
|
|
1594
1668
|
}
|
|
1595
|
-
const borrowAmountFloat = blockchainToFloat(borrowInt, debtAsset.precision);
|
|
1669
|
+
const borrowAmountFloat = blockchainToFloat(borrowInt, Number(debtAsset.precision));
|
|
1596
1670
|
const collateralValueInDebtAsset = await this._calculateCollateralValueInDebtAsset(requiredCollateralInt, collateralAsset, debtAsset, collateralPrice);
|
|
1597
1671
|
const offerCollateralValueInDebtAsset = this._calculateCreditOfferCollateralValueInDebtAsset(requiredCollateralInt, collateralAsset, debtAsset, collateralPrice);
|
|
1598
1672
|
if (collateralValueInDebtAsset == null || offerCollateralValueInDebtAsset == null || borrowAmountFloat <= 0 || collateralValueInDebtAsset <= 0 || offerCollateralValueInDebtAsset <= 0) {
|
|
@@ -1615,8 +1689,8 @@ class CreditRuntime {
|
|
|
1615
1689
|
fee: { amount: 0, asset_id: ZERO_ASSET_ID },
|
|
1616
1690
|
borrower: accountId,
|
|
1617
1691
|
offer_id: offerId,
|
|
1618
|
-
borrow_amount: toAmountObject(borrowInt, debtAsset.id),
|
|
1619
|
-
collateral: toAmountObject(requiredCollateralInt, collateralAsset.id),
|
|
1692
|
+
borrow_amount: toAmountObject(borrowInt, String(debtAsset.id)),
|
|
1693
|
+
collateral: toAmountObject(requiredCollateralInt, String(collateralAsset.id)),
|
|
1620
1694
|
max_fee_rate: offerFeeRate,
|
|
1621
1695
|
min_duration_seconds: minDuration,
|
|
1622
1696
|
extensions,
|
|
@@ -1625,7 +1699,9 @@ class CreditRuntime {
|
|
|
1625
1699
|
this.state.lastBorrowRequest = {
|
|
1626
1700
|
offerId: String(offerId),
|
|
1627
1701
|
borrowAmount: borrowInt,
|
|
1702
|
+
requestedBorrowAmount: requestedBorrowInt,
|
|
1628
1703
|
collateralAmount: requiredCollateralInt,
|
|
1704
|
+
clampedByCollateral,
|
|
1629
1705
|
autoReborrow: !!policy?.autoReborrow,
|
|
1630
1706
|
requestedAt: nowIso()
|
|
1631
1707
|
};
|
|
@@ -1650,7 +1726,7 @@ class CreditRuntime {
|
|
|
1650
1726
|
if (!debtAsset) {
|
|
1651
1727
|
throw new Error('Unable to resolve debt asset metadata for credit repay');
|
|
1652
1728
|
}
|
|
1653
|
-
const repayInt = floatToBlockchainInt(repayAmount, debtAsset.precision);
|
|
1729
|
+
const repayInt = floatToBlockchainInt(repayAmount, Number(debtAsset.precision));
|
|
1654
1730
|
if (!Number.isFinite(repayInt) || repayInt <= 0) {
|
|
1655
1731
|
throw new Error('repayAmount must be positive');
|
|
1656
1732
|
}
|
|
@@ -1664,8 +1740,8 @@ class CreditRuntime {
|
|
|
1664
1740
|
fee: { amount: 0, asset_id: ZERO_ASSET_ID },
|
|
1665
1741
|
account: accountId,
|
|
1666
1742
|
deal_id: dealSummary.id,
|
|
1667
|
-
repay_amount: toAmountObject(repayInt, debtAsset.id),
|
|
1668
|
-
credit_fee: toAmountObject(creditFee, debtAsset.id),
|
|
1743
|
+
repay_amount: toAmountObject(repayInt, String(debtAsset.id)),
|
|
1744
|
+
credit_fee: toAmountObject(creditFee, String(debtAsset.id)),
|
|
1669
1745
|
extensions: [],
|
|
1670
1746
|
}
|
|
1671
1747
|
};
|
|
@@ -1739,7 +1815,7 @@ class CreditRuntime {
|
|
|
1739
1815
|
}
|
|
1740
1816
|
const repayOp = await this.buildCreditDealRepayOperation(dealSummary, repayAmount);
|
|
1741
1817
|
const operations = [repayOp];
|
|
1742
|
-
const reborrowPolicy = options.specificPolicy || await this._findLendingItemForAsset(dealSummary.debtAssetId, 'creditOffer') || {};
|
|
1818
|
+
const reborrowPolicy = (options.specificPolicy || await this._findLendingItemForAsset(dealSummary.debtAssetId, 'creditOffer') || {});
|
|
1743
1819
|
let shouldAutoReborrow = options.autoReborrow !== false && !!reborrowPolicy.autoReborrow;
|
|
1744
1820
|
if (shouldAutoReborrow) {
|
|
1745
1821
|
const disallowedDealIds = this._normalizePolicyList(reborrowPolicy.disallowedDealIds);
|
|
@@ -1749,7 +1825,15 @@ class CreditRuntime {
|
|
|
1749
1825
|
}
|
|
1750
1826
|
let deferredReborrowRequest = null;
|
|
1751
1827
|
let inlineReborrowPlanned = false;
|
|
1828
|
+
let availableReborrowCollateralInt = null;
|
|
1829
|
+
// Snapshot the deals that already exist before this repay broadcasts.
|
|
1830
|
+
// A later pending reborrow can then distinguish a genuine replacement
|
|
1831
|
+
// (a deal that appeared after the repay) from a sibling deal that was
|
|
1832
|
+
// already present on the same offer and must not suppress the reborrow.
|
|
1833
|
+
const preRepayDealIds = this._collectActiveDealIds();
|
|
1752
1834
|
if (shouldAutoReborrow) {
|
|
1835
|
+
// Collateral this repay frees — the ceiling a reborrow may lock.
|
|
1836
|
+
availableReborrowCollateralInt = await this._computeReleasedCollateralInt(dealSummary, repayAmount, options);
|
|
1753
1837
|
const reborrowAmount = options.reborrowAmount !== undefined && options.reborrowAmount !== null
|
|
1754
1838
|
? options.reborrowAmount
|
|
1755
1839
|
: repayAmount;
|
|
@@ -1782,58 +1866,11 @@ class CreditRuntime {
|
|
|
1782
1866
|
}
|
|
1783
1867
|
}
|
|
1784
1868
|
const policyHasAutoRepay = Object.prototype.hasOwnProperty.call(reborrowPolicy, 'autoRepay');
|
|
1785
|
-
const autoRepaySetting = options.autoRepay !== undefined
|
|
1869
|
+
const autoRepaySetting = (options.autoRepay !== undefined
|
|
1786
1870
|
? options.autoRepay
|
|
1787
|
-
: (policyHasAutoRepay ? reborrowPolicy.autoRepay : (dealSummary.autoRepay ?? false));
|
|
1871
|
+
: (policyHasAutoRepay ? reborrowPolicy.autoRepay : (dealSummary.autoRepay ?? false)));
|
|
1788
1872
|
const offer = await this._getOfferById(dealSummary.offerId);
|
|
1789
|
-
|
|
1790
|
-
try {
|
|
1791
|
-
const acceptOp = await this.buildCreditOfferAcceptOperation({
|
|
1792
|
-
offer,
|
|
1793
|
-
borrowAmount: reborrowAmount,
|
|
1794
|
-
collateralAmount: reborrowCollateralAmount,
|
|
1795
|
-
autoRepay: autoRepaySetting,
|
|
1796
|
-
specificPolicy: options.specificPolicy,
|
|
1797
|
-
pendingRepayAmount: repayAmount,
|
|
1798
|
-
pendingReleaseCollateralAmount: options.pendingReleaseCollateralAmount,
|
|
1799
|
-
});
|
|
1800
|
-
operations.push(acceptOp);
|
|
1801
|
-
inlineReborrowPlanned = true;
|
|
1802
|
-
}
|
|
1803
|
-
catch (err) {
|
|
1804
|
-
const fallback = await this._selectFallbackCreditOffer({
|
|
1805
|
-
debtAssetId: dealSummary.debtAssetId,
|
|
1806
|
-
collateralAssetId: effectiveCollateralAssetId,
|
|
1807
|
-
policy: reborrowPolicy,
|
|
1808
|
-
borrowAmount: reborrowAmount,
|
|
1809
|
-
collateralAmount: reborrowCollateralAmount,
|
|
1810
|
-
autoRepay: autoRepaySetting,
|
|
1811
|
-
pendingRepayAmount: repayAmount,
|
|
1812
|
-
pendingReleaseCollateralAmount: options.pendingReleaseCollateralAmount,
|
|
1813
|
-
excludeOfferId: dealSummary.offerId,
|
|
1814
|
-
});
|
|
1815
|
-
if (fallback) {
|
|
1816
|
-
this.warn(`credit runtime: fallback reborrow offer ${fallback.offer.id} selected after original offer ${dealSummary.offerId} failed: ${getErrorMessage(err)}`);
|
|
1817
|
-
operations.push(fallback.op);
|
|
1818
|
-
inlineReborrowPlanned = true;
|
|
1819
|
-
}
|
|
1820
|
-
else {
|
|
1821
|
-
deferredReborrowRequest = {
|
|
1822
|
-
sourceDealId: dealSummary.id,
|
|
1823
|
-
offerId: dealSummary.offerId,
|
|
1824
|
-
borrowAmount: reborrowAmount,
|
|
1825
|
-
collateralAmount: reborrowCollateralAmount,
|
|
1826
|
-
autoRepay: autoRepaySetting,
|
|
1827
|
-
specificPolicy: reborrowPolicy,
|
|
1828
|
-
pendingRepayAmount: repayAmount,
|
|
1829
|
-
pendingReleaseCollateralAmount: options.pendingReleaseCollateralAmount,
|
|
1830
|
-
requestedAt: nowIso(),
|
|
1831
|
-
reason: getErrorMessage(err),
|
|
1832
|
-
};
|
|
1833
|
-
}
|
|
1834
|
-
}
|
|
1835
|
-
}
|
|
1836
|
-
else {
|
|
1873
|
+
const selectFallbackReborrow = async (deferReason, selectionNote) => {
|
|
1837
1874
|
const fallback = await this._selectFallbackCreditOffer({
|
|
1838
1875
|
debtAssetId: dealSummary.debtAssetId,
|
|
1839
1876
|
collateralAssetId: effectiveCollateralAssetId,
|
|
@@ -1843,28 +1880,52 @@ class CreditRuntime {
|
|
|
1843
1880
|
autoRepay: autoRepaySetting,
|
|
1844
1881
|
pendingRepayAmount: repayAmount,
|
|
1845
1882
|
pendingReleaseCollateralAmount: options.pendingReleaseCollateralAmount,
|
|
1883
|
+
availableCollateralAmount: availableReborrowCollateralInt,
|
|
1846
1884
|
excludeOfferId: dealSummary.offerId,
|
|
1847
1885
|
});
|
|
1848
1886
|
if (fallback) {
|
|
1849
|
-
this.warn(`credit runtime: fallback reborrow offer ${fallback.offer.id} selected
|
|
1887
|
+
this.warn(`credit runtime: fallback reborrow offer ${fallback.offer.id} selected ${selectionNote}`);
|
|
1850
1888
|
operations.push(fallback.op);
|
|
1851
1889
|
inlineReborrowPlanned = true;
|
|
1890
|
+
return;
|
|
1852
1891
|
}
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1892
|
+
deferredReborrowRequest = {
|
|
1893
|
+
sourceDealId: dealSummary.id,
|
|
1894
|
+
offerId: dealSummary.offerId,
|
|
1895
|
+
borrowAmount: reborrowAmount,
|
|
1896
|
+
collateralAmount: reborrowCollateralAmount,
|
|
1897
|
+
autoRepay: autoRepaySetting,
|
|
1898
|
+
specificPolicy: reborrowPolicy,
|
|
1899
|
+
preRepayDealIds,
|
|
1900
|
+
availableCollateralAmount: availableReborrowCollateralInt,
|
|
1901
|
+
pendingRepayAmount: repayAmount,
|
|
1902
|
+
pendingReleaseCollateralAmount: options.pendingReleaseCollateralAmount,
|
|
1903
|
+
requestedAt: nowIso(),
|
|
1904
|
+
reason: deferReason,
|
|
1905
|
+
};
|
|
1906
|
+
};
|
|
1907
|
+
if (offer) {
|
|
1908
|
+
try {
|
|
1909
|
+
const acceptOp = await this.buildCreditOfferAcceptOperation({
|
|
1910
|
+
offer,
|
|
1857
1911
|
borrowAmount: reborrowAmount,
|
|
1858
1912
|
collateralAmount: reborrowCollateralAmount,
|
|
1859
1913
|
autoRepay: autoRepaySetting,
|
|
1860
|
-
specificPolicy:
|
|
1914
|
+
specificPolicy: options.specificPolicy,
|
|
1861
1915
|
pendingRepayAmount: repayAmount,
|
|
1862
1916
|
pendingReleaseCollateralAmount: options.pendingReleaseCollateralAmount,
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1917
|
+
availableCollateralAmount: availableReborrowCollateralInt,
|
|
1918
|
+
});
|
|
1919
|
+
operations.push(acceptOp);
|
|
1920
|
+
inlineReborrowPlanned = true;
|
|
1921
|
+
}
|
|
1922
|
+
catch (err) {
|
|
1923
|
+
await selectFallbackReborrow(getErrorMessage(err), `after original offer ${dealSummary.offerId} failed: ${getErrorMessage(err)}`);
|
|
1866
1924
|
}
|
|
1867
1925
|
}
|
|
1926
|
+
else {
|
|
1927
|
+
await selectFallbackReborrow('offer unavailable', `because original offer ${dealSummary.offerId} is unavailable`);
|
|
1928
|
+
}
|
|
1868
1929
|
}
|
|
1869
1930
|
const result = await this.executeOperations(operations, 'credit repay');
|
|
1870
1931
|
this.state.lastRepayAt = nowIso();
|
|
@@ -1886,6 +1947,8 @@ class CreditRuntime {
|
|
|
1886
1947
|
? reborrowPolicy.autoRepay
|
|
1887
1948
|
: (dealSummary.autoRepay ?? false)),
|
|
1888
1949
|
specificPolicy: reborrowPolicy,
|
|
1950
|
+
preRepayDealIds,
|
|
1951
|
+
availableCollateralAmount: availableReborrowCollateralInt,
|
|
1889
1952
|
pendingRepayAmount: repayAmount,
|
|
1890
1953
|
pendingReleaseCollateralAmount: options.pendingReleaseCollateralAmount,
|
|
1891
1954
|
requestedAt: nowIso(),
|
|
@@ -1900,6 +1963,7 @@ class CreditRuntime {
|
|
|
1900
1963
|
autoRepay: reborrowRequest.autoRepay,
|
|
1901
1964
|
specificPolicy: reborrowRequest.specificPolicy,
|
|
1902
1965
|
pendingReleaseCollateralAmount: reborrowRequest.pendingReleaseCollateralAmount,
|
|
1966
|
+
availableCollateralAmount: reborrowRequest.availableCollateralAmount ?? null,
|
|
1903
1967
|
});
|
|
1904
1968
|
await this.executeOperations([acceptOp], 'credit reborrow');
|
|
1905
1969
|
await this.refreshState();
|
|
@@ -1940,6 +2004,9 @@ class CreditRuntime {
|
|
|
1940
2004
|
collateralAmount: request.collateralAmount ?? null,
|
|
1941
2005
|
autoRepay: request.autoRepay ?? false,
|
|
1942
2006
|
specificPolicy: request.specificPolicy || null,
|
|
2007
|
+
preRepayDealIds: Array.isArray(request.preRepayDealIds) ? request.preRepayDealIds.map((id) => String(id)) : null,
|
|
2008
|
+
availableCollateralAmount: request.availableCollateralAmount ?? null,
|
|
2009
|
+
reborrowAttempts: Number(request.reborrowAttempts) || 0,
|
|
1943
2010
|
pendingRepayAmount: request.pendingRepayAmount ?? null,
|
|
1944
2011
|
pendingReleaseCollateralAmount: request.pendingReleaseCollateralAmount ?? null,
|
|
1945
2012
|
requestedAt: request.requestedAt || nowIso(),
|
|
@@ -1954,6 +2021,158 @@ class CreditRuntime {
|
|
|
1954
2021
|
const num = Number(parts[parts.length - 1]);
|
|
1955
2022
|
return Number.isFinite(num) ? num : 0;
|
|
1956
2023
|
}
|
|
2024
|
+
_collectActiveDealIds() {
|
|
2025
|
+
// state.creditDeals is the flattened mirror of positions[*].creditDeals
|
|
2026
|
+
// rebuilt after every refresh, so it is the single source of truth here.
|
|
2027
|
+
const ids = new Set();
|
|
2028
|
+
const deals = Array.isArray(this.state.creditDeals) ? this.state.creditDeals : [];
|
|
2029
|
+
for (const deal of deals) {
|
|
2030
|
+
const id = deal?.id;
|
|
2031
|
+
if (id)
|
|
2032
|
+
ids.add(String(id));
|
|
2033
|
+
}
|
|
2034
|
+
return Array.from(ids);
|
|
2035
|
+
}
|
|
2036
|
+
/**
|
|
2037
|
+
* Pick a balance entry from a `getOnChainAssetBalances` result by asset id,
|
|
2038
|
+
* falling back to the asset symbol. Centralizes the lookup shape shared by
|
|
2039
|
+
* the percentage/amount resolvers and the credit helpers.
|
|
2040
|
+
*/
|
|
2041
|
+
_pickOnChainBalanceEntry(balances, assetId, asset) {
|
|
2042
|
+
const balanceMap = balances;
|
|
2043
|
+
const symbol = asset?.symbol;
|
|
2044
|
+
return (balanceMap?.[String(assetId)]
|
|
2045
|
+
|| (symbol != null ? balanceMap?.[String(symbol)] : undefined)
|
|
2046
|
+
|| null);
|
|
2047
|
+
}
|
|
2048
|
+
/**
|
|
2049
|
+
* Read the chain-free balance of the debt asset. Returns null when the
|
|
2050
|
+
* balance cannot be determined so callers can fall back to the legacy
|
|
2051
|
+
* (full-deal) renewal path instead of guessing.
|
|
2052
|
+
*/
|
|
2053
|
+
async _getFreeDebtAssetBalance(debtAssetId, debtAsset) {
|
|
2054
|
+
const accountRef = getAccountRef(this.bot);
|
|
2055
|
+
if (!accountRef || !debtAssetId)
|
|
2056
|
+
return null;
|
|
2057
|
+
try {
|
|
2058
|
+
const balances = await chainOrders.getOnChainAssetBalances(accountRef, [String(debtAssetId)]);
|
|
2059
|
+
const entry = this._pickOnChainBalanceEntry(balances, debtAssetId, debtAsset);
|
|
2060
|
+
const free = toFiniteNumber(entry?.free, NaN);
|
|
2061
|
+
return Number.isFinite(free) ? free : null;
|
|
2062
|
+
}
|
|
2063
|
+
catch (err) {
|
|
2064
|
+
this.warn(`credit runtime: unable to read free balance for ${String(debtAssetId)}: ${getErrorMessage(err)}`);
|
|
2065
|
+
return null;
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
/**
|
|
2069
|
+
* Raw collateral freed by a repay, used as the ceiling a reborrow can lock.
|
|
2070
|
+
* Precedence:
|
|
2071
|
+
* 1. explicit raw `options.availableCollateralAmount` (collateral-switch flow),
|
|
2072
|
+
* 2. exact on-chain `floor(repay * collateral / debt)` when the deal's own
|
|
2073
|
+
* collateral asset is used,
|
|
2074
|
+
* 3. explicit `options.pendingReleaseCollateralAmount` (float) as a fallback.
|
|
2075
|
+
* Returns null when it cannot be determined, so the accept builder keeps the
|
|
2076
|
+
* legacy (unclamped) behaviour.
|
|
2077
|
+
*/
|
|
2078
|
+
async _computeReleasedCollateralInt(dealSummary, repayAmount, options) {
|
|
2079
|
+
// 1. Explicit raw budget (collateral-switch flow) wins.
|
|
2080
|
+
const explicitRaw = toFiniteNumber(options?.availableCollateralAmount, null);
|
|
2081
|
+
if (explicitRaw !== null && explicitRaw > 0)
|
|
2082
|
+
return Math.floor(explicitRaw);
|
|
2083
|
+
const effectiveCollateralAssetId = options?.collateralAsset ?? dealSummary?.collateralAssetId ?? null;
|
|
2084
|
+
const dealCollateralAssetId = dealSummary?.collateralAssetId ?? null;
|
|
2085
|
+
const sameCollateralAsset = !dealCollateralAssetId || !effectiveCollateralAssetId
|
|
2086
|
+
|| String(dealCollateralAssetId) === String(effectiveCollateralAssetId);
|
|
2087
|
+
// 2. Exact on-chain release: floor(repay * collateral / debt), matching
|
|
2088
|
+
// credit_deal_repay_evaluator::do_apply. Preferred over the float
|
|
2089
|
+
// fallback so the budget never over-states the freed collateral.
|
|
2090
|
+
if (sameCollateralAsset) {
|
|
2091
|
+
const debtAsset = await this._resolveAsset(dealSummary?.debtAssetId);
|
|
2092
|
+
const debtPrecision = getAssetPrecision(debtAsset);
|
|
2093
|
+
if (debtPrecision !== null) {
|
|
2094
|
+
const repayInt = floatToBlockchainInt(repayAmount, debtPrecision);
|
|
2095
|
+
const debtInt = toFiniteNumber(dealSummary?.debtAmount, 0);
|
|
2096
|
+
const collateralInt = toFiniteNumber(dealSummary?.collateralAmount, 0);
|
|
2097
|
+
if (Number.isFinite(repayInt) && repayInt > 0 && debtInt > 0 && collateralInt > 0) {
|
|
2098
|
+
const released = Math.floor(collateralInt * Math.min(repayInt, debtInt) / debtInt);
|
|
2099
|
+
if (released > 0)
|
|
2100
|
+
return released;
|
|
2101
|
+
}
|
|
2102
|
+
}
|
|
2103
|
+
// 3. Fallback when raw deal amounts are unavailable: use an explicit
|
|
2104
|
+
// released float, floored at the collateral precision.
|
|
2105
|
+
if (options?.pendingReleaseCollateralAmount !== null && options?.pendingReleaseCollateralAmount !== undefined) {
|
|
2106
|
+
const collateralAsset = effectiveCollateralAssetId ? await this._resolveAsset(effectiveCollateralAssetId) : null;
|
|
2107
|
+
const collateralPrecision = getAssetPrecision(collateralAsset);
|
|
2108
|
+
if (collateralPrecision === null)
|
|
2109
|
+
return null;
|
|
2110
|
+
const explicitFloat = toFiniteNumber(options.pendingReleaseCollateralAmount, null);
|
|
2111
|
+
if (explicitFloat === null || explicitFloat <= 0)
|
|
2112
|
+
return null;
|
|
2113
|
+
const explicit = floorToBlockchainInt(explicitFloat, collateralPrecision);
|
|
2114
|
+
return Number.isFinite(explicit) && explicit > 0 ? explicit : null;
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
return null;
|
|
2118
|
+
}
|
|
2119
|
+
/**
|
|
2120
|
+
* Decide how much of a maturing deal can actually be repaid and reborrowed
|
|
2121
|
+
* with the currently free debt-asset balance. The repay leg is funded from
|
|
2122
|
+
* the borrower's free balance before the atomic reborrow returns anything,
|
|
2123
|
+
* so when the borrowed asset has been deployed into the grid the full deal
|
|
2124
|
+
* cannot be renewed in one shot. In that case we roll the largest affordable
|
|
2125
|
+
* piece (bounded by min_deal_amount and maxBorrowAmountPerOperation) and let
|
|
2126
|
+
* the remaining debt be handled on the next cycle.
|
|
2127
|
+
*
|
|
2128
|
+
* Returns null when sizing is not possible (unknown balance / malformed
|
|
2129
|
+
* deal) so the caller keeps the existing full-renewal behaviour.
|
|
2130
|
+
*/
|
|
2131
|
+
async _resolveRenewalSizing({ deal, debtAsset, offer, policy }) {
|
|
2132
|
+
const fullAmount = blockchainAmountToFloat(deal?.debtAmount, debtAsset);
|
|
2133
|
+
if (fullAmount == null || fullAmount <= 0)
|
|
2134
|
+
return null;
|
|
2135
|
+
const feeRate = Number(deal?.feeRate) || 0;
|
|
2136
|
+
const free = await this._getFreeDebtAssetBalance(deal?.debtAssetId, debtAsset);
|
|
2137
|
+
if (free === null)
|
|
2138
|
+
return null;
|
|
2139
|
+
// Work in raw debt units and reuse the on-chain (ceil) fee helper so the
|
|
2140
|
+
// sizing matches what the repay will actually require.
|
|
2141
|
+
const precisionRaw = Number(debtAsset?.precision);
|
|
2142
|
+
const decimals = Number.isFinite(precisionRaw) && precisionRaw >= 0 ? Math.trunc(precisionRaw) : 0;
|
|
2143
|
+
const fullInt = floorToBlockchainInt(fullAmount, decimals);
|
|
2144
|
+
const freeInt = floorToBlockchainInt(free, decimals);
|
|
2145
|
+
const requiredInt = fullInt + sharedCreditDealFee(fullInt, feeRate, CREDIT_FEE_RATE_DENOM);
|
|
2146
|
+
const required = blockchainToFloat(requiredInt, decimals);
|
|
2147
|
+
const spendableInt = freeInt - CREDIT_REBORROW_FREE_BALANCE_BUFFER_INT;
|
|
2148
|
+
if (spendableInt >= requiredInt) {
|
|
2149
|
+
return { partial: false, amount: fullAmount, free, required };
|
|
2150
|
+
}
|
|
2151
|
+
const minDealInt = toFiniteNumber(offer?.min_deal_amount, null);
|
|
2152
|
+
const minDeal = minDealInt !== null ? blockchainToFloat(minDealInt, decimals) : null;
|
|
2153
|
+
// Start from an upper estimate and step down until piece + ceil(fee)
|
|
2154
|
+
// fits the spendable balance; the loop runs at most a couple of iterations.
|
|
2155
|
+
let pieceInt = spendableInt > 0 ? Math.ceil(spendableInt / (1 + feeRate / CREDIT_FEE_RATE_DENOM)) : 0;
|
|
2156
|
+
while (pieceInt > 0 && pieceInt + sharedCreditDealFee(pieceInt, feeRate, CREDIT_FEE_RATE_DENOM) > spendableInt) {
|
|
2157
|
+
pieceInt -= 1;
|
|
2158
|
+
}
|
|
2159
|
+
const maxPerOp = positiveOrNull(policy?.maxBorrowAmountPerOperation);
|
|
2160
|
+
if (maxPerOp !== null && maxPerOp > 0) {
|
|
2161
|
+
const maxPerOpInt = floorToBlockchainInt(maxPerOp, decimals);
|
|
2162
|
+
if (maxPerOpInt < pieceInt)
|
|
2163
|
+
pieceInt = maxPerOpInt;
|
|
2164
|
+
}
|
|
2165
|
+
const affordable = blockchainToFloat(pieceInt, decimals);
|
|
2166
|
+
if (!Number.isFinite(affordable)
|
|
2167
|
+
|| affordable <= 0
|
|
2168
|
+
|| (minDeal !== null && minDeal > 0 && affordable < minDeal)) {
|
|
2169
|
+
return { partial: false, insufficient: true, amount: 0, free, required, minDeal };
|
|
2170
|
+
}
|
|
2171
|
+
if (affordable >= fullAmount) {
|
|
2172
|
+
return { partial: false, amount: fullAmount, free, required };
|
|
2173
|
+
}
|
|
2174
|
+
return { partial: true, amount: affordable, free, required, minDeal };
|
|
2175
|
+
}
|
|
1957
2176
|
async _getOfferById(offerId) {
|
|
1958
2177
|
if (!offerId)
|
|
1959
2178
|
return null;
|
|
@@ -1967,7 +2186,7 @@ class CreditRuntime {
|
|
|
1967
2186
|
// cause deal-split guards to pass against a value that no longer
|
|
1968
2187
|
// holds on-chain.
|
|
1969
2188
|
const OFFER_CACHE_TTL_MS = require('./constants').TIMING.OFFER_CACHE_TTL_MS;
|
|
1970
|
-
const cachedAt = cached._cachedAt || 0;
|
|
2189
|
+
const cachedAt = Number(cached._cachedAt) || 0;
|
|
1971
2190
|
if (Date.now() - cachedAt < OFFER_CACHE_TTL_MS) {
|
|
1972
2191
|
return cached;
|
|
1973
2192
|
}
|
|
@@ -2026,7 +2245,7 @@ class CreditRuntime {
|
|
|
2026
2245
|
collateralAssetId: collateralAsset?.id ? String(collateralAsset.id) : null,
|
|
2027
2246
|
};
|
|
2028
2247
|
}
|
|
2029
|
-
async _selectFallbackCreditOffer({ debtAssetId, collateralAssetId, policy, borrowAmount, collateralAmount, autoRepay, pendingRepayAmount = null, pendingReleaseCollateralAmount, excludeOfferId = null } = {}) {
|
|
2248
|
+
async _selectFallbackCreditOffer({ debtAssetId, collateralAssetId, policy, borrowAmount, collateralAmount, autoRepay, pendingRepayAmount = null, pendingReleaseCollateralAmount, availableCollateralAmount = null, excludeOfferId = null } = {}) {
|
|
2030
2249
|
const offers = await this._fetchCreditOffersByAsset(debtAssetId);
|
|
2031
2250
|
const candidates = [];
|
|
2032
2251
|
for (const offer of offers) {
|
|
@@ -2049,29 +2268,23 @@ class CreditRuntime {
|
|
|
2049
2268
|
offer,
|
|
2050
2269
|
borrowAmount,
|
|
2051
2270
|
collateralAmount,
|
|
2052
|
-
autoRepay,
|
|
2271
|
+
autoRepay: autoRepay,
|
|
2053
2272
|
specificPolicy: policy,
|
|
2054
2273
|
pendingRepayAmount,
|
|
2055
2274
|
pendingReleaseCollateralAmount,
|
|
2275
|
+
availableCollateralAmount,
|
|
2056
2276
|
});
|
|
2057
2277
|
candidates.push({
|
|
2058
2278
|
offer,
|
|
2059
2279
|
op,
|
|
2060
|
-
|
|
2061
|
-
feeRate: toFiniteNumber(offer.fee_rate, Number.MAX_SAFE_INTEGER),
|
|
2062
|
-
balance: toFiniteNumber(offer.current_balance, 0),
|
|
2063
|
-
duration: toFiniteNumber(offer.max_duration_seconds, 0),
|
|
2280
|
+
...offerRankingFields(this._calculateDailyFeeRate(offer), offer),
|
|
2064
2281
|
});
|
|
2065
2282
|
}
|
|
2066
2283
|
catch (_) {
|
|
2067
2284
|
// Candidate does not satisfy amount, ratio, balance, or duration policy.
|
|
2068
2285
|
}
|
|
2069
2286
|
}
|
|
2070
|
-
candidates.sort(
|
|
2071
|
-
|| a.feeRate - b.feeRate
|
|
2072
|
-
|| b.duration - a.duration
|
|
2073
|
-
|| b.balance - a.balance
|
|
2074
|
-
|| String(a.offer.id).localeCompare(String(b.offer.id))));
|
|
2287
|
+
candidates.sort(compareCreditOfferCandidates);
|
|
2075
2288
|
return candidates[0] || null;
|
|
2076
2289
|
}
|
|
2077
2290
|
async _selectCreditOfferForIncrease({ debtAssetId, collateralAssetId, policy, collateralAmount, minCollateralIncrease = 0, remainingBorrowCapacity = null, autoRepay } = {}) {
|
|
@@ -2129,7 +2342,7 @@ class CreditRuntime {
|
|
|
2129
2342
|
if (accountId && debtAsset && collateralAsset && effectiveBorrowCapacity !== null) {
|
|
2130
2343
|
const collateralSpec = normalizeAmountSpec(collateralAmount);
|
|
2131
2344
|
const collateralReferenceAmount = isPercentageAmountSpec(collateralSpec)
|
|
2132
|
-
? await this._getCollateralPercentageBase(accountId, collateralAsset.id)
|
|
2345
|
+
? await this._getCollateralPercentageBase(accountId, String(collateralAsset.id))
|
|
2133
2346
|
: null;
|
|
2134
2347
|
const requestedCollateralInt = await this._resolveAmountToBlockchainInt(collateralSpec, collateralAsset, accountId, {
|
|
2135
2348
|
balanceField: 'total',
|
|
@@ -2137,7 +2350,7 @@ class CreditRuntime {
|
|
|
2137
2350
|
referenceLabel: 'total collateral balance',
|
|
2138
2351
|
});
|
|
2139
2352
|
const desiredBorrowInt = this._calculateBorrowAmountFromCollateral(requestedCollateralInt, collateralPrice, debtAsset, collateralAsset);
|
|
2140
|
-
const desiredBorrowAmount = blockchainToFloat(desiredBorrowInt, debtAsset.precision);
|
|
2353
|
+
const desiredBorrowAmount = blockchainToFloat(desiredBorrowInt, Number(debtAsset.precision));
|
|
2141
2354
|
if (Number.isFinite(desiredBorrowAmount) && desiredBorrowAmount > effectiveBorrowCapacity) {
|
|
2142
2355
|
acceptArgs = {
|
|
2143
2356
|
offer,
|
|
@@ -2163,7 +2376,7 @@ class CreditRuntime {
|
|
|
2163
2376
|
offer,
|
|
2164
2377
|
borrowAmount: effectiveBorrowCapacity,
|
|
2165
2378
|
collateralAmount: { assetId: collateralAssetId },
|
|
2166
|
-
autoRepay,
|
|
2379
|
+
autoRepay: autoRepay,
|
|
2167
2380
|
specificPolicy: policy,
|
|
2168
2381
|
});
|
|
2169
2382
|
}
|
|
@@ -2182,21 +2395,14 @@ class CreditRuntime {
|
|
|
2182
2395
|
borrowAmount: opBorrowAmount,
|
|
2183
2396
|
collateralAmount: opCollateralAmount,
|
|
2184
2397
|
capped,
|
|
2185
|
-
|
|
2186
|
-
feeRate: toFiniteNumber(offer.fee_rate, Number.MAX_SAFE_INTEGER),
|
|
2187
|
-
balance: toFiniteNumber(offer.current_balance, 0),
|
|
2188
|
-
duration: toFiniteNumber(offer.max_duration_seconds, 0),
|
|
2398
|
+
...offerRankingFields(this._calculateDailyFeeRate(offer), offer),
|
|
2189
2399
|
});
|
|
2190
2400
|
}
|
|
2191
2401
|
catch (_) {
|
|
2192
2402
|
// Candidate does not satisfy amount, ratio, balance, or duration policy.
|
|
2193
2403
|
}
|
|
2194
2404
|
}
|
|
2195
|
-
candidates.sort(
|
|
2196
|
-
|| a.feeRate - b.feeRate
|
|
2197
|
-
|| b.duration - a.duration
|
|
2198
|
-
|| b.balance - a.balance
|
|
2199
|
-
|| String(a.offer.id).localeCompare(String(b.offer.id))));
|
|
2405
|
+
candidates.sort(compareCreditOfferCandidates);
|
|
2200
2406
|
return candidates[0] || null;
|
|
2201
2407
|
}
|
|
2202
2408
|
async _buildCreditIncreasePlan(lendingItem, assetId, posState) {
|
|
@@ -2312,9 +2518,9 @@ class CreditRuntime {
|
|
|
2312
2518
|
const dealOffer = await this._getOfferById(parseDealSummary(currentDeal)?.offerId);
|
|
2313
2519
|
const minDealAmount = toFiniteNumber(dealOffer?.min_deal_amount, null);
|
|
2314
2520
|
const numPieces = Math.ceil(dealDebt / maxPerOp);
|
|
2315
|
-
const pieceAmount = roundToDecimals(dealDebt / numPieces, debtAsset.precision);
|
|
2316
|
-
if (minDealAmount !== null && pieceAmount < blockchainToFloat(minDealAmount, debtAsset.precision)) {
|
|
2317
|
-
this.warn(`credit runtime: cannot split deal ${dealId} — piece amount ${pieceAmount} below min_deal_amount ${blockchainToFloat(minDealAmount, debtAsset.precision)} for offer ${dealOffer?.id}`);
|
|
2521
|
+
const pieceAmount = roundToDecimals(dealDebt / numPieces, Number(debtAsset.precision));
|
|
2522
|
+
if (minDealAmount !== null && pieceAmount < blockchainToFloat(minDealAmount, Number(debtAsset.precision))) {
|
|
2523
|
+
this.warn(`credit runtime: cannot split deal ${dealId} — piece amount ${pieceAmount} below min_deal_amount ${blockchainToFloat(minDealAmount, Number(debtAsset.precision))} for offer ${dealOffer?.id}`);
|
|
2318
2524
|
continue;
|
|
2319
2525
|
}
|
|
2320
2526
|
const dealPieces = Math.min(numPieces - 1, MAX_PIECES_PER_CYCLE - totalPiecesThisCycle);
|
|
@@ -2338,7 +2544,7 @@ class CreditRuntime {
|
|
|
2338
2544
|
});
|
|
2339
2545
|
}
|
|
2340
2546
|
// Re-fetch deal from current state (may have been refreshed by repayCreditDeal)
|
|
2341
|
-
const pos = this.state.positions?.[posKey];
|
|
2547
|
+
const pos = this.state.positions?.[String(posKey)];
|
|
2342
2548
|
const refreshed = Array.isArray(pos?.creditDeals)
|
|
2343
2549
|
? pos.creditDeals.find((d) => String(d.id) === dealId)
|
|
2344
2550
|
: null;
|
|
@@ -2384,8 +2590,8 @@ class CreditRuntime {
|
|
|
2384
2590
|
return null;
|
|
2385
2591
|
const accountId = await this._resolveAccountId(accountRef) || accountRef;
|
|
2386
2592
|
const dealObjects = await this._dbCall('get_credit_deals_by_borrower', [accountId]);
|
|
2387
|
-
const normalized = Array.isArray(dealObjects) ? dealObjects.map(parseDealSummary).filter(
|
|
2388
|
-
return normalized.find((entry) => String(entry
|
|
2593
|
+
const normalized = Array.isArray(dealObjects) ? dealObjects.map(parseDealSummary).filter((d) => d !== null) : [];
|
|
2594
|
+
return (normalized.find((entry) => String(entry?.id) === String(dealId)) || null);
|
|
2389
2595
|
}
|
|
2390
2596
|
async processPendingReborrows() {
|
|
2391
2597
|
if (!Array.isArray(this.state.pendingReborrows) || this.state.pendingReborrows.length === 0) {
|
|
@@ -2395,18 +2601,34 @@ class CreditRuntime {
|
|
|
2395
2601
|
return { skipped: true, reason: 'reborrow processing already in flight' };
|
|
2396
2602
|
}
|
|
2397
2603
|
this._reborrowsInFlight = true;
|
|
2604
|
+
const configuredMaxAttempts = Number(this.config?.timing?.CREDIT_REBORROW_MAX_ATTEMPTS);
|
|
2605
|
+
const maxReborrowAttempts = Number.isFinite(configuredMaxAttempts) && configuredMaxAttempts > 0
|
|
2606
|
+
? Math.trunc(configuredMaxAttempts)
|
|
2607
|
+
: TIMING.CREDIT_REBORROW_MAX_ATTEMPTS;
|
|
2398
2608
|
try {
|
|
2399
2609
|
const onChainDeals = await this._fetchBorrowerDeals();
|
|
2400
2610
|
const activeDealIds = new Set(onChainDeals.map((deal) => String(deal?.id)).filter(Boolean));
|
|
2401
2611
|
const nextQueue = [];
|
|
2402
2612
|
let processed = 0;
|
|
2613
|
+
// Bounded retry: build/broadcast failures increment the attempt count
|
|
2614
|
+
// and are dropped once the limit is reached. Transient deferrals
|
|
2615
|
+
// (offer missing/disabled, source deal still active) are not counted.
|
|
2616
|
+
const recordFailedAttempt = (request, label, err) => {
|
|
2617
|
+
const attempts = (Number(request.reborrowAttempts) || 0) + 1;
|
|
2618
|
+
if (attempts >= maxReborrowAttempts) {
|
|
2619
|
+
this.warn(`credit runtime: dropping ${label} for offer ${request.offerId} after ${attempts} failed attempt(s) — last error: ${getErrorMessage(err)}`);
|
|
2620
|
+
return;
|
|
2621
|
+
}
|
|
2622
|
+
this.warn(`credit runtime: ${label} for offer ${request.offerId} failed (attempt ${attempts}/${maxReborrowAttempts}): ${getErrorMessage(err)}`);
|
|
2623
|
+
nextQueue.push({ ...request, reborrowAttempts: attempts, reason: getErrorMessage(err) });
|
|
2624
|
+
};
|
|
2403
2625
|
for (const request of this.state.pendingReborrows) {
|
|
2404
2626
|
if (!request?.offerId || (request.borrowAmount == null && request.collateralAmount == null)) {
|
|
2405
2627
|
this.warn(`credit runtime: dropping invalid pending reborrow request${request?.sourceDealId ? ` for deal ${request.sourceDealId}` : ''} — missing offerId or borrow/collateral amounts`);
|
|
2406
2628
|
continue;
|
|
2407
2629
|
}
|
|
2408
2630
|
const offer = await this._getOfferById(request.offerId);
|
|
2409
|
-
const requestPolicy = request.specificPolicy || (offer ? await this._resolveLendingPolicyForOffer(offer) : null);
|
|
2631
|
+
const requestPolicy = (request.specificPolicy || (offer ? await this._resolveLendingPolicyForOffer(offer) : null));
|
|
2410
2632
|
if (!requestPolicy || !requestPolicy.autoReborrow) {
|
|
2411
2633
|
this.warn(`credit runtime: dropping pending reborrow for offer ${request.offerId}; autoReborrow disabled or policy missing`);
|
|
2412
2634
|
continue;
|
|
@@ -2429,8 +2651,19 @@ class CreditRuntime {
|
|
|
2429
2651
|
if (request.sourceDealId && request.offerId && requestPolicy?.renewOnly === true) {
|
|
2430
2652
|
const sourceNum = this._extractDealNumericId(request.sourceDealId);
|
|
2431
2653
|
if (sourceNum > 0) {
|
|
2432
|
-
const
|
|
2433
|
-
|
|
2654
|
+
const preRepaySnapshot = Array.isArray(request.preRepayDealIds)
|
|
2655
|
+
? new Set(request.preRepayDealIds.map((id) => String(id)))
|
|
2656
|
+
: null;
|
|
2657
|
+
const hasNewerReplacement = onChainDeals.some((d) => {
|
|
2658
|
+
if (String(d?.offerId) !== String(request.offerId))
|
|
2659
|
+
return false;
|
|
2660
|
+
if (this._extractDealNumericId(d.id) <= sourceNum)
|
|
2661
|
+
return false;
|
|
2662
|
+
// With a pre-repay snapshot, only deals that appeared
|
|
2663
|
+
// after the repay count as replacements. Sibling deals
|
|
2664
|
+
// already present on the same offer are not.
|
|
2665
|
+
return preRepaySnapshot ? !preRepaySnapshot.has(String(d.id)) : true;
|
|
2666
|
+
});
|
|
2434
2667
|
if (hasNewerReplacement) {
|
|
2435
2668
|
this.warn(`credit runtime: dropping stale pending reborrow for deal ${request.sourceDealId} — replacement deal already exists for offer ${request.offerId}`);
|
|
2436
2669
|
processed++;
|
|
@@ -2461,8 +2694,9 @@ class CreditRuntime {
|
|
|
2461
2694
|
policy: requestPolicy,
|
|
2462
2695
|
borrowAmount: request.borrowAmount,
|
|
2463
2696
|
collateralAmount: effectiveCollateralAmount,
|
|
2464
|
-
autoRepay: request.autoRepay ?? false,
|
|
2697
|
+
autoRepay: (request.autoRepay ?? false),
|
|
2465
2698
|
pendingReleaseCollateralAmount: request.pendingReleaseCollateralAmount,
|
|
2699
|
+
availableCollateralAmount: request.availableCollateralAmount ?? null,
|
|
2466
2700
|
excludeOfferId: request.offerId,
|
|
2467
2701
|
})
|
|
2468
2702
|
: null;
|
|
@@ -2473,8 +2707,7 @@ class CreditRuntime {
|
|
|
2473
2707
|
processed++;
|
|
2474
2708
|
}
|
|
2475
2709
|
catch (err) {
|
|
2476
|
-
|
|
2477
|
-
nextQueue.push({ ...request, reason: getErrorMessage(err) });
|
|
2710
|
+
recordFailedAttempt(request, 'fallback reborrow', err);
|
|
2478
2711
|
}
|
|
2479
2712
|
}
|
|
2480
2713
|
else {
|
|
@@ -2488,16 +2721,16 @@ class CreditRuntime {
|
|
|
2488
2721
|
offer,
|
|
2489
2722
|
borrowAmount: request.borrowAmount ?? null,
|
|
2490
2723
|
collateralAmount: effectiveCollateralAmount,
|
|
2491
|
-
autoRepay: request.autoRepay ?? false,
|
|
2492
|
-
specificPolicy: request.specificPolicy || requestPolicy,
|
|
2724
|
+
autoRepay: (request.autoRepay ?? false),
|
|
2725
|
+
specificPolicy: (request.specificPolicy || requestPolicy),
|
|
2493
2726
|
pendingReleaseCollateralAmount: request.pendingReleaseCollateralAmount,
|
|
2727
|
+
availableCollateralAmount: request.availableCollateralAmount ?? null,
|
|
2494
2728
|
});
|
|
2495
2729
|
await this.executeOperations([acceptOp], 'credit reborrow');
|
|
2496
2730
|
processed++;
|
|
2497
2731
|
}
|
|
2498
2732
|
catch (err) {
|
|
2499
|
-
|
|
2500
|
-
nextQueue.push({ ...request, reason: getErrorMessage(err) });
|
|
2733
|
+
recordFailedAttempt(request, 'pending reborrow', err);
|
|
2501
2734
|
}
|
|
2502
2735
|
}
|
|
2503
2736
|
this.state.pendingReborrows = nextQueue;
|
|
@@ -2551,14 +2784,14 @@ class CreditRuntime {
|
|
|
2551
2784
|
// Try collateral-only repair; if unavailable, surface the original broadcast failure.
|
|
2552
2785
|
const configuredCollateralAsset = await this._resolveAsset(lendingItem.collateralAsset);
|
|
2553
2786
|
const configuredCollateralAssetId = configuredCollateralAsset?.id;
|
|
2554
|
-
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : assetId;
|
|
2787
|
+
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : String(assetId);
|
|
2555
2788
|
const posState = this.state.positions[posKey];
|
|
2556
2789
|
const collateralPlan = buildCollateralFallbackPlan({
|
|
2557
2790
|
currentCollateralAmount: posState?.currentCollateralAmount,
|
|
2558
2791
|
currentDebtAmount: posState?.currentDebtAmount,
|
|
2559
2792
|
feedPrice: posState?.feedPrice,
|
|
2560
2793
|
targetCollateralRatio: plan.targetCollateralRatio,
|
|
2561
|
-
maxCollateralAmount: posState?.assignedCollateralBudget ?? lendingItem.maxCollateralAmount,
|
|
2794
|
+
maxCollateralAmount: (posState?.assignedCollateralBudget ?? lendingItem.maxCollateralAmount),
|
|
2562
2795
|
collateralLimitReferenceAmount: posState?.currentCollateralFundsTotal,
|
|
2563
2796
|
});
|
|
2564
2797
|
if (collateralPlan) {
|
|
@@ -2583,7 +2816,7 @@ class CreditRuntime {
|
|
|
2583
2816
|
};
|
|
2584
2817
|
const configuredCollateralAsset = await this._resolveAsset(lendingItem.collateralAsset);
|
|
2585
2818
|
const configuredCollateralAssetId = configuredCollateralAsset?.id;
|
|
2586
|
-
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : assetId;
|
|
2819
|
+
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : String(assetId);
|
|
2587
2820
|
if (!this.state.positions[posKey])
|
|
2588
2821
|
this.state.positions[posKey] = {};
|
|
2589
2822
|
this.state.positions[posKey].lastMpaAction = lastAction;
|
|
@@ -2594,7 +2827,7 @@ class CreditRuntime {
|
|
|
2594
2827
|
};
|
|
2595
2828
|
if (typeof this.bot?.requestGridReset === 'function') {
|
|
2596
2829
|
try {
|
|
2597
|
-
const resetReason = plan.resetReason || 'cr-adjustment';
|
|
2830
|
+
const resetReason = String(plan.resetReason || 'cr-adjustment');
|
|
2598
2831
|
const resetResult = await this.bot.requestGridReset(resetReason);
|
|
2599
2832
|
this.state.lastGridResetAt = nowIso();
|
|
2600
2833
|
return { plan, executed, resetResult };
|
|
@@ -2617,7 +2850,7 @@ class CreditRuntime {
|
|
|
2617
2850
|
}
|
|
2618
2851
|
const configuredCollateralAsset = await this._resolveAsset(lendingItem.collateralAsset);
|
|
2619
2852
|
const configuredCollateralAssetId = configuredCollateralAsset?.id;
|
|
2620
|
-
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : assetId;
|
|
2853
|
+
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : String(assetId);
|
|
2621
2854
|
// Phase 1: Proactively repay deals nearing expiration before processing reborrows
|
|
2622
2855
|
const expiryThresholdHours = this.bot?.config?.timing?.CREDIT_DEAL_EXPIRY_THRESHOLD_HOURS ?? TIMING.CREDIT_DEAL_EXPIRY_THRESHOLD_HOURS;
|
|
2623
2856
|
const expiryThresholdMs = expiryThresholdHours * 60 * 60 * 1000;
|
|
@@ -2651,15 +2884,23 @@ class CreditRuntime {
|
|
|
2651
2884
|
}
|
|
2652
2885
|
const isCollateralMismatch = deal.collateralMismatch === true;
|
|
2653
2886
|
let existingCollateralAmount = null;
|
|
2887
|
+
let explicitAvailableCollateralInt = null;
|
|
2654
2888
|
if (isCollateralMismatch) {
|
|
2655
2889
|
const accountRef = getAccountRef(this.bot);
|
|
2656
2890
|
const balances = await chainOrders.getOnChainAssetBalances(accountRef, [configuredCollateralAssetId]);
|
|
2657
|
-
const balance = balances
|
|
2891
|
+
const balance = this._pickOnChainBalanceEntry(balances, configuredCollateralAssetId, configuredCollateralAsset);
|
|
2658
2892
|
const available = toFiniteNumber(balance?.total, undefined);
|
|
2659
2893
|
if (!Number.isFinite(available) || available <= 0) {
|
|
2660
2894
|
this.warn(`credit runtime: skipping collateral switch for deal ${deal.id} — no balance of new collateral ${configuredCollateralAssetId}`);
|
|
2661
2895
|
continue;
|
|
2662
2896
|
}
|
|
2897
|
+
const configuredCollateralPrecision = getAssetPrecision(configuredCollateralAsset);
|
|
2898
|
+
if (configuredCollateralPrecision !== null) {
|
|
2899
|
+
explicitAvailableCollateralInt = floatToBlockchainInt(available, configuredCollateralPrecision);
|
|
2900
|
+
if (!Number.isFinite(explicitAvailableCollateralInt) || explicitAvailableCollateralInt <= 0) {
|
|
2901
|
+
explicitAvailableCollateralInt = null;
|
|
2902
|
+
}
|
|
2903
|
+
}
|
|
2663
2904
|
}
|
|
2664
2905
|
if (!isCollateralMismatch) {
|
|
2665
2906
|
const collateralAsset = await this._resolveAsset(deal.collateralAssetId);
|
|
@@ -2668,6 +2909,33 @@ class CreditRuntime {
|
|
|
2668
2909
|
throw new Error(`unable to convert deal ${deal.id} collateral amount for release`);
|
|
2669
2910
|
}
|
|
2670
2911
|
}
|
|
2912
|
+
// Shortfall-aware renewal: the repay leg is funded from the
|
|
2913
|
+
// free debt-asset balance before the atomic reborrow returns
|
|
2914
|
+
// anything, so when the borrowed asset has been deployed into
|
|
2915
|
+
// the grid the full deal cannot be renewed at once. Roll the
|
|
2916
|
+
// largest affordable piece instead and leave the rest for the
|
|
2917
|
+
// next cycle rather than failing the whole renewal.
|
|
2918
|
+
const renewalOffer = await this._getOfferById(deal.offerId);
|
|
2919
|
+
const sizing = await this._resolveRenewalSizing({ deal, debtAsset, offer: renewalOffer, policy: lendingItem });
|
|
2920
|
+
let renewalAmount = repayAmount;
|
|
2921
|
+
let isPartialRenewal = false;
|
|
2922
|
+
if (sizing?.partial === true) {
|
|
2923
|
+
renewalAmount = sizing.amount;
|
|
2924
|
+
isPartialRenewal = renewalAmount < repayAmount;
|
|
2925
|
+
}
|
|
2926
|
+
else if (sizing?.insufficient === true) {
|
|
2927
|
+
// Nothing affordable — fall back to the full renewal so the
|
|
2928
|
+
// on-chain failure still surfaces rather than silently
|
|
2929
|
+
// skipping a deal that is about to expire.
|
|
2930
|
+
this.warn(`credit runtime: cannot size a partial renewal for deal ${deal.id} (free ${sizing.free}, required ${sizing.required}); attempting full renewal`);
|
|
2931
|
+
}
|
|
2932
|
+
let renewalPendingReleaseCollateral = isCollateralMismatch ? null : existingCollateralAmount;
|
|
2933
|
+
if (isPartialRenewal && !isCollateralMismatch && existingCollateralAmount != null) {
|
|
2934
|
+
renewalPendingReleaseCollateral = existingCollateralAmount * (renewalAmount / repayAmount);
|
|
2935
|
+
}
|
|
2936
|
+
if (isPartialRenewal) {
|
|
2937
|
+
this.warn(`credit runtime: insufficient free ${debtAsset?.symbol ?? deal.debtAssetId} for full renewal of deal ${deal.id} (have ${sizing?.free}, need ${sizing?.required}); repaying/reborrowing ${renewalAmount} and rolling the rest`);
|
|
2938
|
+
}
|
|
2671
2939
|
// Snapshot pre-existing pending reborrows for this deal so we
|
|
2672
2940
|
// can prune stale ones after repayCreditDeal without removing
|
|
2673
2941
|
// any new deferred entry that repayCreditDeal itself may queue.
|
|
@@ -2675,14 +2943,15 @@ class CreditRuntime {
|
|
|
2675
2943
|
? this.state.pendingReborrows.filter((r) => r.sourceDealId === String(deal.id))
|
|
2676
2944
|
: [];
|
|
2677
2945
|
const staleKeys = new Set(staleSnapshot.map((r) => `${r.sourceDealId}:${r.offerId}:${r.requestedAt}`));
|
|
2678
|
-
await this.repayCreditDeal(deal,
|
|
2946
|
+
await this.repayCreditDeal(deal, renewalAmount, {
|
|
2679
2947
|
autoReborrow: true,
|
|
2680
|
-
collateralAmount: isCollateralMismatch ? null : {
|
|
2948
|
+
collateralAmount: isCollateralMismatch || isPartialRenewal ? null : {
|
|
2681
2949
|
amount: existingCollateralAmount,
|
|
2682
2950
|
assetId: deal.collateralAssetId,
|
|
2683
2951
|
},
|
|
2684
2952
|
collateralAsset: configuredCollateralAssetId,
|
|
2685
|
-
pendingReleaseCollateralAmount:
|
|
2953
|
+
pendingReleaseCollateralAmount: renewalPendingReleaseCollateral,
|
|
2954
|
+
availableCollateralAmount: explicitAvailableCollateralInt,
|
|
2686
2955
|
specificPolicy: lendingItem,
|
|
2687
2956
|
});
|
|
2688
2957
|
// Prune only the stale entries that existed before the call
|
|
@@ -2788,7 +3057,7 @@ class CreditRuntime {
|
|
|
2788
3057
|
credit: [],
|
|
2789
3058
|
};
|
|
2790
3059
|
const dp = this.debtPolicy;
|
|
2791
|
-
for (const item of dp
|
|
3060
|
+
for (const item of dp?.lending ?? []) {
|
|
2792
3061
|
const resolvedAsset = await this._resolveAsset(item.asset);
|
|
2793
3062
|
const assetId = resolvedAsset?.id ? String(resolvedAsset.id) : null;
|
|
2794
3063
|
if (!assetId) {
|
|
@@ -2823,7 +3092,7 @@ class CreditRuntime {
|
|
|
2823
3092
|
const mpaResults = [];
|
|
2824
3093
|
const creditResults = [];
|
|
2825
3094
|
const dp = this.debtPolicy;
|
|
2826
|
-
for (const item of dp
|
|
3095
|
+
for (const item of dp?.lending ?? []) {
|
|
2827
3096
|
const resolvedAsset = await this._resolveAsset(item.asset);
|
|
2828
3097
|
const assetId = resolvedAsset?.id ? String(resolvedAsset.id) : null;
|
|
2829
3098
|
if (!assetId) {
|