dexbot 1.6.11 → 1.6.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -4
- package/README.md +2 -1
- package/analysis/README.md +2 -0
- package/analysis/tradingview/README.md +1 -1
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
- package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
- package/claw/modules/chain_broadcast.ts +7 -1
- package/claw/modules/claw_launcher.ts +1 -1
- package/claw/modules/launcher_mode_detector.ts +9 -2
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/account_resolver.d.ts +1 -1
- package/dist/analysis/account_resolver.js +2 -1
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -7
- package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
- package/dist/analysis/ama_fitting/fetch_lp_candles.js +4 -4
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +20 -4
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +9 -6
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js +16 -12
- package/dist/analysis/analyze_args.d.ts +31 -0
- package/dist/analysis/analyze_args.js +41 -0
- package/dist/analysis/analyze_dynamic_weight.js +7 -17
- package/dist/analysis/analyze_kalman.js +7 -17
- package/dist/analysis/analyze_regime.js +7 -17
- package/dist/analysis/analyze_regime_windows.js +8 -18
- package/dist/analysis/analyze_risk_profile.js +8 -18
- package/dist/analysis/analyze_trade_heatmap.js +7 -17
- package/dist/analysis/analyze_volatility.js +7 -17
- package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +220 -12
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js +6 -5
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +11 -63
- package/dist/analysis/bot_fitting/shared_utils.d.ts +7 -7
- package/dist/analysis/bot_fitting/shared_utils.js +2 -2
- package/dist/analysis/bot_key_utils.d.ts +18 -10
- package/dist/analysis/bot_key_utils.js +7 -4
- package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
- package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
- package/dist/analysis/chain_pool.d.ts +3 -1
- package/dist/analysis/chart_ui.d.ts +5 -2
- package/dist/analysis/chart_ui.js +6 -3
- package/dist/analysis/chart_utils.d.ts +5 -5
- package/dist/analysis/chart_utils.js +9 -0
- package/dist/analysis/fills_cache.d.ts +1 -1
- package/dist/analysis/fills_source.d.ts +2 -2
- package/dist/analysis/fills_source.js +14 -12
- package/dist/analysis/grid_correction_check.d.ts +1 -1
- package/dist/analysis/grid_correction_check.js +12 -11
- package/dist/analysis/math_utils.d.ts +7 -6
- package/dist/analysis/math_utils.js +5 -8
- package/dist/analysis/pnl_report.js +29 -29
- package/dist/analysis/price_sources.d.ts +8 -8
- package/dist/analysis/price_sources.js +5 -4
- package/dist/analysis/resolve_bot_accounts.js +2 -2
- package/dist/analysis/resolve_source.d.ts +1 -1
- package/dist/analysis/trade_profitability.d.ts +23 -2
- package/dist/analysis/trade_profitability.js +50 -50
- package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
- package/dist/analysis/tradingview/analyze_tradingview.js +6 -5
- package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
- package/dist/analysis/tradingview/grid_reset_config.js +23 -11
- package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
- package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +18 -19
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -1
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +5 -5
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +5 -4
- package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
- package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
- package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
- package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
- package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
- package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
- package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
- package/dist/credential-daemon.js +34 -20
- package/dist/dexbot.js +11 -11
- package/dist/market_adapter/candle_utils.d.ts +22 -18
- package/dist/market_adapter/candle_utils.js +24 -20
- package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
- package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
- package/dist/market_adapter/core/kibana_candles.d.ts +53 -18
- package/dist/market_adapter/core/kibana_candles.js +9 -7
- package/dist/market_adapter/core/kibana_client.d.ts +9 -1
- package/dist/market_adapter/core/kibana_client.js +8 -7
- package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
- package/dist/market_adapter/core/market_adapter_service.d.ts +284 -117
- package/dist/market_adapter/core/market_adapter_service.js +137 -113
- package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
- package/dist/market_adapter/core/strategies/ama.js +2 -4
- package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
- package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
- package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
- package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
- package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
- package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
- package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
- package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
- package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
- package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
- package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
- package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
- package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
- package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
- package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
- package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
- package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +96 -224
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +42 -7
- package/dist/market_adapter/inputs/fetch_lp_data.js +22 -15
- package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
- package/dist/market_adapter/inputs/kibana_feed_source.js +29 -22
- package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
- package/dist/market_adapter/inputs/kibana_source.js +2 -2
- package/dist/market_adapter/inputs/window_cache.d.ts +99 -94
- package/dist/market_adapter/inputs/window_cache.js +8 -8
- package/dist/market_adapter/interval_utils.d.ts +4 -4
- package/dist/market_adapter/log_format.d.ts +6 -6
- package/dist/market_adapter/log_format.js +28 -21
- package/dist/market_adapter/lp_chart_core.d.ts +22 -1
- package/dist/market_adapter/lp_chart_core.js +26 -192
- package/dist/market_adapter/lp_chart_runner.d.ts +7 -7
- package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
- package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
- package/dist/market_adapter/market_adapter.d.ts +94 -32
- package/dist/market_adapter/market_adapter.js +67 -48
- package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
- package/dist/market_adapter/utils/adapter_client.js +2 -2
- package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
- package/dist/market_adapter/utils/chain.d.ts +50 -41
- package/dist/market_adapter/utils/chain.js +40 -46
- package/dist/market_adapter/utils/data_discovery.d.ts +4 -1
- package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
- package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
- package/dist/market_adapter/utils/file_lock.d.ts +28 -14
- package/dist/market_adapter/utils/file_lock.js +36 -32
- package/dist/market_adapter/utils/native_history.d.ts +9 -2
- package/dist/market_adapter/utils/native_history.js +35 -28
- package/dist/modules/account_bots.d.ts +577 -21
- package/dist/modules/account_bots.js +182 -158
- package/dist/modules/account_orders.d.ts +66 -30
- package/dist/modules/account_orders.js +22 -20
- package/dist/modules/authority_resolver.d.ts +12 -2
- package/dist/modules/authority_resolver.js +15 -8
- package/dist/modules/bitshares-native/chain_client.d.ts +38 -3
- package/dist/modules/bitshares-native/chain_client.js +45 -46
- package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
- package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
- package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
- package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
- package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
- package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
- package/dist/modules/bitshares-native/index.d.ts +1 -1
- package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
- package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
- package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
- package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
- package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
- package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
- package/dist/modules/bitshares-native/serial/serializer.js +7 -13
- package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
- package/dist/modules/bitshares-native/serial/types.js +55 -62
- package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
- package/dist/modules/bitshares-native/signing_client.js +19 -14
- package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
- package/dist/modules/bitshares-native/subscriptions.js +12 -12
- package/dist/modules/bitshares-native/transport.d.ts +5 -4
- package/dist/modules/bitshares-native/transport.js +5 -4
- package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
- package/dist/modules/bitshares-native/tx/builder.js +4 -3
- package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
- package/dist/modules/bitshares_client.d.ts +45 -13
- package/dist/modules/bitshares_client.js +28 -19
- package/dist/modules/bot_defaults.d.ts +6 -15
- package/dist/modules/bot_defaults.js +1 -5
- package/dist/modules/bot_settings.d.ts +44 -10
- package/dist/modules/bot_settings.js +11 -8
- package/dist/modules/bots_file_lock.d.ts +6 -6
- package/dist/modules/bots_file_lock.js +16 -12
- package/dist/modules/broadcast_failure.d.ts +2 -2
- package/dist/modules/broadcast_failure.js +5 -4
- package/dist/modules/chain_keys.d.ts +42 -40
- package/dist/modules/chain_keys.js +53 -45
- package/dist/modules/chain_orders.d.ts +93 -59
- package/dist/modules/chain_orders.js +31 -23
- package/dist/modules/constants.d.ts +527 -31
- package/dist/modules/constants.js +15 -47
- package/dist/modules/cr_planner.d.ts +40 -2
- package/dist/modules/credential_policy.d.ts +68 -8
- package/dist/modules/credential_policy.js +37 -31
- package/dist/modules/credential_session_cache.d.ts +2 -2
- package/dist/modules/credit_pricing.d.ts +42 -6
- package/dist/modules/credit_pricing.js +44 -30
- package/dist/modules/credit_runtime.d.ts +276 -118
- package/dist/modules/credit_runtime.js +462 -165
- package/dist/modules/crypto/browser_provider.js +6 -4
- package/dist/modules/crypto/node_provider.js +1 -1
- package/dist/modules/crypto/pure_scrypt.js +35 -4
- package/dist/modules/crypto/pure_secp256k1.js +72 -26
- package/dist/modules/crypto/sync.d.ts +9 -9
- package/dist/modules/crypto/sync.js +16 -9
- package/dist/modules/dexbot_class.d.ts +195 -139
- package/dist/modules/dexbot_class.js +78 -28
- package/dist/modules/dexbot_cow_runtime.d.ts +167 -87
- package/dist/modules/dexbot_cow_runtime.js +248 -206
- package/dist/modules/dexbot_credential_client.d.ts +19 -11
- package/dist/modules/dexbot_fill_runtime.d.ts +63 -48
- package/dist/modules/dexbot_fill_runtime.js +48 -41
- package/dist/modules/dexbot_maintenance_runtime.d.ts +109 -70
- package/dist/modules/dexbot_maintenance_runtime.js +108 -83
- package/dist/modules/dexbot_startup_runtime.d.ts +11 -10
- package/dist/modules/dexbot_startup_runtime.js +43 -43
- package/dist/modules/dexbot_state_recovery.d.ts +13 -12
- package/dist/modules/dexbot_state_recovery.js +18 -13
- package/dist/modules/fund_registry.d.ts +4 -2
- package/dist/modules/fund_registry.js +10 -10
- package/dist/modules/general_settings.d.ts +30 -4
- package/dist/modules/graceful_shutdown.d.ts +3 -3
- package/dist/modules/graceful_shutdown.js +2 -2
- package/dist/modules/grid_price_source.d.ts +1 -1
- package/dist/modules/key_store.d.ts +14 -8
- package/dist/modules/key_store.js +7 -6
- package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
- package/dist/modules/launcher/adapter_requirement.js +5 -5
- package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
- package/dist/modules/launcher/bot_supervisor.js +12 -11
- package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
- package/dist/modules/launcher/credential_bootstrap.js +1 -1
- package/dist/modules/launcher/credential_daemon.d.ts +4 -4
- package/dist/modules/launcher/credential_daemon.js +2 -2
- package/dist/modules/launcher/credential_secret.d.ts +1 -1
- package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
- package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
- package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
- package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
- package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
- package/dist/modules/launcher/status_reporting.d.ts +22 -14
- package/dist/modules/launcher/supervisor_control.d.ts +8 -1
- package/dist/modules/launcher/supervisor_control.js +4 -2
- package/dist/modules/market_adapter_whitelist.d.ts +9 -3
- package/dist/modules/market_adapter_whitelist.js +15 -3
- package/dist/modules/node_manager.d.ts +41 -11
- package/dist/modules/node_manager.js +5 -4
- package/dist/modules/order/accounting.d.ts +53 -24
- package/dist/modules/order/accounting.js +16 -15
- package/dist/modules/order/async_lock.d.ts +5 -2
- package/dist/modules/order/async_lock.js +1 -1
- package/dist/modules/order/export.d.ts +7 -6
- package/dist/modules/order/export.js +1 -7
- package/dist/modules/order/format.d.ts +4 -4
- package/dist/modules/order/genesis_policy.d.ts +21 -18
- package/dist/modules/order/genesis_policy.js +12 -8
- package/dist/modules/order/grid.d.ts +142 -36
- package/dist/modules/order/grid.js +148 -123
- package/dist/modules/order/grid_reconcile.d.ts +21 -20
- package/dist/modules/order/grid_reconcile.js +13 -12
- package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
- package/dist/modules/order/grid_reconcile_internal.js +28 -19
- package/dist/modules/order/index.d.ts +263 -1
- package/dist/modules/order/logger.d.ts +45 -11
- package/dist/modules/order/logger.js +38 -40
- package/dist/modules/order/logger_state.d.ts +4 -4
- package/dist/modules/order/manager.d.ts +225 -180
- package/dist/modules/order/manager.js +80 -83
- package/dist/modules/order/processed_fill_store.d.ts +18 -3
- package/dist/modules/order/processed_fill_store.js +16 -27
- package/dist/modules/order/strategy.d.ts +21 -13
- package/dist/modules/order/strategy.js +5 -6
- package/dist/modules/order/sync_engine.d.ts +91 -33
- package/dist/modules/order/sync_engine.js +84 -53
- package/dist/modules/order/utils/math.d.ts +157 -102
- package/dist/modules/order/utils/math.js +77 -38
- package/dist/modules/order/utils/order.d.ts +310 -110
- package/dist/modules/order/utils/order.js +122 -99
- package/dist/modules/order/utils/slot.d.ts +1 -1
- package/dist/modules/order/utils/system.d.ts +176 -26
- package/dist/modules/order/utils/system.js +86 -69
- package/dist/modules/order/utils/validate.d.ts +89 -41
- package/dist/modules/order/utils/validate.js +24 -22
- package/dist/modules/order/utils/withPoolRef.d.ts +4 -3
- package/dist/modules/order/utils/withPoolRef.js +18 -12
- package/dist/modules/order/working_grid.d.ts +14 -13
- package/dist/modules/paths.d.ts +1 -4
- package/dist/modules/paths.js +1 -27
- package/dist/modules/process_discovery.d.ts +1 -1
- package/dist/modules/process_discovery.js +2 -1
- package/dist/modules/runtime.d.ts +7 -3
- package/dist/modules/runtime.js +4 -3
- package/dist/modules/runtime_settings.d.ts +15 -10
- package/dist/modules/runtime_settings.js +30 -24
- package/dist/modules/settings_merge.d.ts +29 -3
- package/dist/modules/settings_merge.js +56 -78
- package/dist/modules/socket_json_client.d.ts +7 -4
- package/dist/modules/storage/browser_adapter.d.ts +38 -53
- package/dist/modules/storage/browser_adapter.js +7 -30
- package/dist/modules/storage/index.d.ts +1 -1
- package/dist/modules/storage/node_adapter.d.ts +45 -27
- package/dist/modules/storage/node_adapter.js +9 -9
- package/dist/modules/storage/types.d.ts +5 -4
- package/dist/modules/types.d.ts +1071 -2
- package/dist/modules/types.js +4 -1
- package/dist/modules/utils/asset_symbols.d.ts +2 -1
- package/dist/modules/utils/asset_symbols.js +2 -1
- package/dist/modules/utils/errors.d.ts +9 -0
- package/dist/modules/utils/errors.js +23 -1
- package/dist/modules/utils/time_range.d.ts +1 -12
- package/dist/modules/utils/time_range.js +1 -1
- package/dist/modules/validate_profiles.js +53 -43
- package/dist/modules/version_notice.d.ts +14 -3
- package/dist/modules/version_notice.js +6 -4
- package/dist/pm2.d.ts +29 -27
- package/dist/pm2.js +5 -5
- package/dist/scripts/analyze-credit.d.ts +2 -1
- package/dist/scripts/analyze-credit.js +23 -24
- package/dist/scripts/analyze-orders.d.ts +77 -9
- package/dist/scripts/analyze-orders.js +65 -40
- package/dist/scripts/chart_command.d.ts +27 -18
- package/dist/scripts/chart_command.js +13 -11
- package/dist/scripts/check_any.d.ts +18 -0
- package/dist/scripts/check_any.js +126 -0
- package/dist/scripts/diagnose-pool-history.js +12 -7
- package/dist/scripts/print_grid.js +0 -1
- package/dist/scripts/run-tests.js +39 -7
- package/dist/scripts/runner.js +1 -1
- package/dist/scripts/test-credit-renewal.js +30 -21
- package/dist/scripts/update.d.ts +10 -5
- package/dist/scripts/update.js +168 -103
- package/dist/scripts/update_dist_freshness.js +1 -0
- package/dist/scripts/update_layout.d.ts +61 -0
- package/dist/scripts/update_layout.js +180 -0
- package/dist/scripts/validate_bots.js +2 -1
- package/dist/scripts/verify-browser-bundle.js +8 -0
- package/dist/unlock.d.ts +28 -3
- package/dist/unlock.js +63 -35
- package/docs/BITSHARES_ONBOARDING.md +2 -0
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
- package/docs/COW_INVARIANTS.md +13 -6
- package/docs/DEXBOT_COMPARISON.md +8 -8
- package/docs/EVOLUTION.md +10 -9
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
- package/docs/GRID_RECALCULATION.md +4 -2
- package/docs/GRID_RECONCILE.md +14 -3
- package/docs/LIFECYCLE.md +11 -11
- package/docs/MPA_CREDIT_USAGE.md +22 -3
- package/docs/README.md +14 -3
- package/docs/architecture.md +12 -9
- package/docs/developer_guide.md +6 -6
- package/market_adapter/README.md +6 -1
- package/modules/README.md +4 -1
- package/package.json +4 -1
|
@@ -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,7 +934,7 @@ class CreditRuntime {
|
|
|
894
934
|
}
|
|
895
935
|
}
|
|
896
936
|
_getCreditDebtForAsset(asset) {
|
|
897
|
-
const assetId = asset?.id
|
|
937
|
+
const assetId = asset?.id ?? asset;
|
|
898
938
|
const deals = Array.isArray(this.state?.creditDeals) ? this.state.creditDeals : [];
|
|
899
939
|
return deals.reduce((sum, deal) => {
|
|
900
940
|
if (String(deal?.debtAssetId) === String(assetId)) {
|
|
@@ -904,7 +944,7 @@ class CreditRuntime {
|
|
|
904
944
|
}, 0);
|
|
905
945
|
}
|
|
906
946
|
_getCreditCollateralForAsset(asset) {
|
|
907
|
-
const assetId = asset?.id
|
|
947
|
+
const assetId = asset?.id ?? asset;
|
|
908
948
|
const deals = Array.isArray(this.state?.creditDeals) ? this.state.creditDeals : [];
|
|
909
949
|
return deals.reduce((sum, deal) => {
|
|
910
950
|
if (String(deal?.collateralAssetId) === String(assetId)) {
|
|
@@ -920,11 +960,11 @@ class CreditRuntime {
|
|
|
920
960
|
if (!asset)
|
|
921
961
|
return null;
|
|
922
962
|
const [balances, account, deals] = await Promise.all([
|
|
923
|
-
chainOrders.getOnChainAssetBalances(accountId, [assetId]),
|
|
963
|
+
chainOrders.getOnChainAssetBalances(accountId, [String(assetId)]),
|
|
924
964
|
this._getFullAccount(accountId).catch(() => null),
|
|
925
965
|
this._fetchBorrowerDeals().catch(() => []),
|
|
926
966
|
]);
|
|
927
|
-
const balance = balances
|
|
967
|
+
const balance = this._pickOnChainBalanceEntry(balances, assetId, asset);
|
|
928
968
|
const onChainTotal = toFiniteNumber(balance?.total, NaN);
|
|
929
969
|
if (!Number.isFinite(onChainTotal)) {
|
|
930
970
|
return null;
|
|
@@ -947,7 +987,7 @@ class CreditRuntime {
|
|
|
947
987
|
const accountName = getAccountName(this.bot);
|
|
948
988
|
const botName = this.botKey;
|
|
949
989
|
if (accountName && botName) {
|
|
950
|
-
const effective = fundRegistry.getEffectiveCollateralAllocationSync(accountName, botName, assetId, total);
|
|
990
|
+
const effective = fundRegistry.getEffectiveCollateralAllocationSync(accountName, botName, String(assetId), total);
|
|
951
991
|
if (effective !== null)
|
|
952
992
|
return effective;
|
|
953
993
|
}
|
|
@@ -964,7 +1004,7 @@ class CreditRuntime {
|
|
|
964
1004
|
return;
|
|
965
1005
|
const referenceAmount = await this._getCollateralPercentageBase(accountId, collateralAsset.id);
|
|
966
1006
|
if (!Number.isFinite(referenceAmount)) {
|
|
967
|
-
throw new Error(`Unable to resolve collateral percentage base for ${collateralAsset.id}`);
|
|
1007
|
+
throw new Error(`Unable to resolve collateral percentage base for ${String(collateralAsset.id)}`);
|
|
968
1008
|
}
|
|
969
1009
|
limitFloat = resolveConfigValue(maxCollateralAmountValue, referenceAmount);
|
|
970
1010
|
}
|
|
@@ -1023,7 +1063,7 @@ class CreditRuntime {
|
|
|
1023
1063
|
if (!Number.isFinite(collateralAmountFloat) || collateralAmountFloat <= 0) {
|
|
1024
1064
|
return null;
|
|
1025
1065
|
}
|
|
1026
|
-
const valuePerShare = await deriveLiquidityPoolTokenValue(BitShares, collateralAsset.id, debtAsset.id, 'auto', true);
|
|
1066
|
+
const valuePerShare = await deriveLiquidityPoolTokenValue(BitShares, String(collateralAsset.id), String(debtAsset.id), 'auto', true);
|
|
1027
1067
|
if (valuePerShare == null || !Number.isFinite(valuePerShare) || valuePerShare <= 0) {
|
|
1028
1068
|
return null;
|
|
1029
1069
|
}
|
|
@@ -1044,7 +1084,7 @@ class CreditRuntime {
|
|
|
1044
1084
|
if (!accountId)
|
|
1045
1085
|
return [];
|
|
1046
1086
|
const dealObjects = await this._dbCall('get_credit_deals_by_borrower', [accountId]);
|
|
1047
|
-
const normalized = Array.isArray(dealObjects) ? dealObjects.map(parseDealSummary).filter(
|
|
1087
|
+
const normalized = Array.isArray(dealObjects) ? dealObjects.map(parseDealSummary).filter((d) => d !== null) : [];
|
|
1048
1088
|
this._borrowerDealsCache = normalized;
|
|
1049
1089
|
return normalized;
|
|
1050
1090
|
}
|
|
@@ -1055,7 +1095,7 @@ class CreditRuntime {
|
|
|
1055
1095
|
}
|
|
1056
1096
|
const accountId = await this._resolveAccountId(accountRef) || accountRef;
|
|
1057
1097
|
const offers = await this._dbCall('get_credit_offers_by_owner', [accountId]);
|
|
1058
|
-
return Array.isArray(offers) ? offers.map(parseCreditOfferSummary).filter(
|
|
1098
|
+
return Array.isArray(offers) ? offers.map(parseCreditOfferSummary).filter((o) => o !== null) : [];
|
|
1059
1099
|
}
|
|
1060
1100
|
async _buildDebtSnapshot() {
|
|
1061
1101
|
const snapshot = {
|
|
@@ -1082,19 +1122,22 @@ class CreditRuntime {
|
|
|
1082
1122
|
}
|
|
1083
1123
|
snapshot.assets[key][field] += amount;
|
|
1084
1124
|
};
|
|
1085
|
-
for (const
|
|
1125
|
+
for (const entry of snapshot.mpaCallOrders) {
|
|
1126
|
+
const order = entry;
|
|
1086
1127
|
const debtAsset = order?.debtAssetId ? await this._resolveAsset(order.debtAssetId) : null;
|
|
1087
1128
|
const collateralAsset = order?.collateralAssetId ? await this._resolveAsset(order.collateralAssetId) : null;
|
|
1088
1129
|
bump(order?.debtAssetId, 'mpaDebt', blockchainAmountToFloat(order?.debtAmount, debtAsset) || 0);
|
|
1089
1130
|
bump(order?.collateralAssetId, 'mpaCollateral', blockchainAmountToFloat(order?.collateralAmount, collateralAsset) || 0);
|
|
1090
1131
|
}
|
|
1091
|
-
for (const
|
|
1132
|
+
for (const entry of snapshot.creditDeals) {
|
|
1133
|
+
const deal = entry;
|
|
1092
1134
|
const debtAsset = deal?.debtAssetId ? await this._resolveAsset(deal.debtAssetId) : null;
|
|
1093
1135
|
const collateralAsset = deal?.collateralAssetId ? await this._resolveAsset(deal.collateralAssetId) : null;
|
|
1094
1136
|
bump(deal?.debtAssetId, 'creditDebt', blockchainAmountToFloat(deal?.debtAmount, debtAsset) || 0);
|
|
1095
1137
|
bump(deal?.collateralAssetId, 'creditCollateral', blockchainAmountToFloat(deal?.collateralAmount, collateralAsset) || 0);
|
|
1096
1138
|
}
|
|
1097
|
-
for (const
|
|
1139
|
+
for (const entry of snapshot.ownedCreditOffers) {
|
|
1140
|
+
const offer = entry;
|
|
1098
1141
|
const asset = offer?.assetType ? await this._resolveAsset(offer.assetType) : null;
|
|
1099
1142
|
bump(offer?.assetType, 'offeredBalance', blockchainAmountToFloat(offer?.currentBalance, asset) || 0);
|
|
1100
1143
|
}
|
|
@@ -1123,7 +1166,7 @@ class CreditRuntime {
|
|
|
1123
1166
|
this.state.mpaCallOrders = callOrders;
|
|
1124
1167
|
const configuredCollateralAsset = await this._resolveAsset(lendingItem.collateralAsset);
|
|
1125
1168
|
const configuredCollateralAssetId = configuredCollateralAsset?.id ? String(configuredCollateralAsset.id) : null;
|
|
1126
|
-
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : assetId;
|
|
1169
|
+
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : String(assetId);
|
|
1127
1170
|
const candidateOrders = callOrders.filter((entry) => String(entry?.call_price?.quote?.asset_id) === assetId);
|
|
1128
1171
|
const createEmptyState = (reason) => {
|
|
1129
1172
|
const empty = {
|
|
@@ -1167,15 +1210,16 @@ class CreditRuntime {
|
|
|
1167
1210
|
const balancesFn = typeof this._getOnChainAssetBalancesFn === 'function'
|
|
1168
1211
|
? this._getOnChainAssetBalancesFn
|
|
1169
1212
|
: (acct, assets) => chainOrders.getOnChainAssetBalances(acct, assets);
|
|
1170
|
-
const collateralBalances = callOrderCollateralAssetId ? await balancesFn(accountRef, [callOrderCollateralAssetId]) : {};
|
|
1171
|
-
const
|
|
1213
|
+
const collateralBalances = callOrderCollateralAssetId ? await balancesFn(accountRef, [String(callOrderCollateralAssetId)]) : {};
|
|
1214
|
+
const collateralMap = collateralBalances;
|
|
1215
|
+
const collateralBalance = callOrderCollateralAssetId ? (collateralMap?.[String(callOrderCollateralAssetId)] || collateralMap?.[String(collateralAsset?.symbol)] || null) : null;
|
|
1172
1216
|
let currentCollateralFundsTotal = toFiniteNumber(collateralBalance?.total, undefined);
|
|
1173
1217
|
// Apply registry proportional split for shared-account credit bots
|
|
1174
1218
|
if (currentCollateralFundsTotal !== null && callOrderCollateralAssetId) {
|
|
1175
1219
|
const accountName = getAccountName(this.bot);
|
|
1176
1220
|
const botName = this.botKey;
|
|
1177
1221
|
if (accountName && botName) {
|
|
1178
|
-
const effective = fundRegistry.getEffectiveCollateralAllocationSync(accountName, botName, callOrderCollateralAssetId, currentCollateralFundsTotal);
|
|
1222
|
+
const effective = fundRegistry.getEffectiveCollateralAllocationSync(accountName, botName, String(callOrderCollateralAssetId), currentCollateralFundsTotal);
|
|
1179
1223
|
if (effective !== null)
|
|
1180
1224
|
currentCollateralFundsTotal = effective;
|
|
1181
1225
|
}
|
|
@@ -1190,7 +1234,7 @@ class CreditRuntime {
|
|
|
1190
1234
|
? collateralAmount / (debtAmount * feedPrice)
|
|
1191
1235
|
: null;
|
|
1192
1236
|
const posState = {
|
|
1193
|
-
activeCallOrderId: callOrder
|
|
1237
|
+
activeCallOrderId: callOrder?.id || null,
|
|
1194
1238
|
debtAssetId: assetId,
|
|
1195
1239
|
currentCollateralAssetId: callOrderCollateralAssetId,
|
|
1196
1240
|
currentDebtAmount: debtAmount,
|
|
@@ -1219,10 +1263,10 @@ class CreditRuntime {
|
|
|
1219
1263
|
}
|
|
1220
1264
|
const assetId = String(debtAsset.id);
|
|
1221
1265
|
const normalizedDeals = Array.isArray(options.deals)
|
|
1222
|
-
? options.deals.map(parseDealSummary).filter(
|
|
1266
|
+
? options.deals.map(parseDealSummary).filter((d) => d !== null)
|
|
1223
1267
|
: await this._fetchBorrowerDeals();
|
|
1224
1268
|
const ownedCreditOffers = Array.isArray(options.ownedCreditOffers)
|
|
1225
|
-
? options.ownedCreditOffers.map(parseCreditOfferSummary).filter(
|
|
1269
|
+
? options.ownedCreditOffers.map(parseCreditOfferSummary).filter((o) => o !== null)
|
|
1226
1270
|
: await this._fetchOwnedCreditOffers();
|
|
1227
1271
|
const trackedOffers = new Map();
|
|
1228
1272
|
const offerIdsFromDeals = normalizedDeals.map((deal) => deal.offerId).filter(Boolean);
|
|
@@ -1239,7 +1283,7 @@ class CreditRuntime {
|
|
|
1239
1283
|
}
|
|
1240
1284
|
const expectedCollateralAssetObj = await this._resolveAsset(lendingItem.collateralAsset);
|
|
1241
1285
|
const expectedCollateralId = expectedCollateralAssetObj?.id ? String(expectedCollateralAssetObj.id) : null;
|
|
1242
|
-
const posKey = expectedCollateralId ? this._positionKey(assetId, expectedCollateralId) : assetId;
|
|
1286
|
+
const posKey = expectedCollateralId ? this._positionKey(assetId, expectedCollateralId) : String(assetId);
|
|
1243
1287
|
// Cache conversion rate from discovered offers to avoid duplicate fetches in distribution.
|
|
1244
1288
|
// This is a price for the debt+collateral asset pair, not for a specific offer id.
|
|
1245
1289
|
// In practice, offers for the same pair should expose interchangeable acceptable-collateral pricing.
|
|
@@ -1361,7 +1405,7 @@ class CreditRuntime {
|
|
|
1361
1405
|
}
|
|
1362
1406
|
const collateralAsset = await this._resolveAsset(lendingItem.collateralAsset);
|
|
1363
1407
|
const collateralAssetId = collateralAsset?.id;
|
|
1364
|
-
const posKey = collateralAssetId ? this._positionKey(assetId, collateralAssetId) : assetId;
|
|
1408
|
+
const posKey = collateralAssetId ? this._positionKey(assetId, collateralAssetId) : String(assetId);
|
|
1365
1409
|
const posState = this.state.positions[posKey];
|
|
1366
1410
|
if (!posState)
|
|
1367
1411
|
return null;
|
|
@@ -1377,7 +1421,7 @@ class CreditRuntime {
|
|
|
1377
1421
|
targetCollateralRatio: lendingItem.targetCollateralRatio,
|
|
1378
1422
|
maxBorrowAmount: lendingItem.maxBorrowAmount,
|
|
1379
1423
|
maxBorrowAmountPerOperation: lendingItem.maxBorrowAmountPerOperation,
|
|
1380
|
-
maxCollateralAmount: posState.assignedCollateralBudget ?? lendingItem.maxCollateralAmount,
|
|
1424
|
+
maxCollateralAmount: (posState.assignedCollateralBudget ?? lendingItem.maxCollateralAmount),
|
|
1381
1425
|
collateralLimitReferenceAmount: posState.currentCollateralFundsTotal,
|
|
1382
1426
|
minCollateralIncreaseThreshold: lendingItem.minCollateralIncreaseThreshold,
|
|
1383
1427
|
debtOnly: lendingItem.debtOnly,
|
|
@@ -1399,11 +1443,11 @@ class CreditRuntime {
|
|
|
1399
1443
|
if (!policy || !plan)
|
|
1400
1444
|
return null;
|
|
1401
1445
|
if (plan.blocked) {
|
|
1402
|
-
throw new Error(plan.reason || 'MPA plan blocked');
|
|
1446
|
+
throw new Error(String(plan.reason || 'MPA plan blocked'));
|
|
1403
1447
|
}
|
|
1404
1448
|
const collateralAsset = await this._resolveAsset(lendingItem.collateralAsset);
|
|
1405
1449
|
const collateralAssetId = collateralAsset?.id;
|
|
1406
|
-
const posKey = collateralAssetId ? this._positionKey(assetId, collateralAssetId) : assetId;
|
|
1450
|
+
const posKey = collateralAssetId ? this._positionKey(assetId, collateralAssetId) : String(assetId);
|
|
1407
1451
|
const posState = this.state.positions[posKey];
|
|
1408
1452
|
if (!posState)
|
|
1409
1453
|
return null;
|
|
@@ -1422,8 +1466,8 @@ class CreditRuntime {
|
|
|
1422
1466
|
}
|
|
1423
1467
|
const debtDelta = leg === 'collateral' ? 0 : plan.debtDelta;
|
|
1424
1468
|
const collateralDelta = leg === 'debt' ? 0 : plan.collateralDelta;
|
|
1425
|
-
const debtInt = floatToBlockchainInt(debtDelta, debtAsset.precision);
|
|
1426
|
-
const collateralInt = floatToBlockchainInt(collateralDelta, callOrderCollateralAsset.precision);
|
|
1469
|
+
const debtInt = floatToBlockchainInt(debtDelta, Number(debtAsset.precision));
|
|
1470
|
+
const collateralInt = floatToBlockchainInt(collateralDelta, Number(callOrderCollateralAsset.precision));
|
|
1427
1471
|
if (debtInt === 0 && collateralInt === 0) {
|
|
1428
1472
|
return null;
|
|
1429
1473
|
}
|
|
@@ -1437,13 +1481,13 @@ class CreditRuntime {
|
|
|
1437
1481
|
op_data: {
|
|
1438
1482
|
fee: { amount: 0, asset_id: ZERO_ASSET_ID },
|
|
1439
1483
|
funding_account: accountId,
|
|
1440
|
-
delta_collateral: toAmountObject(collateralInt, callOrderCollateralAsset.id),
|
|
1441
|
-
delta_debt: toAmountObject(debtInt, debtAsset.id),
|
|
1484
|
+
delta_collateral: toAmountObject(collateralInt, String(callOrderCollateralAsset.id)),
|
|
1485
|
+
delta_debt: toAmountObject(debtInt, String(debtAsset.id)),
|
|
1442
1486
|
extensions,
|
|
1443
1487
|
}
|
|
1444
1488
|
};
|
|
1445
1489
|
}
|
|
1446
|
-
async buildCreditOfferAcceptOperation({ offer, borrowAmount, collateralAmount, autoRepay = false, specificPolicy = null, pendingRepayAmount = null, pendingReleaseCollateralAmount = null } = {}) {
|
|
1490
|
+
async buildCreditOfferAcceptOperation({ offer, borrowAmount, collateralAmount, autoRepay = false, specificPolicy = null, pendingRepayAmount = null, pendingReleaseCollateralAmount = null, availableCollateralAmount = null } = {}) {
|
|
1447
1491
|
let policy = specificPolicy;
|
|
1448
1492
|
if (!policy) {
|
|
1449
1493
|
const dp = this.debtPolicy;
|
|
@@ -1455,7 +1499,7 @@ class CreditRuntime {
|
|
|
1455
1499
|
continue;
|
|
1456
1500
|
let cached = this._assetCache.get(String(item.asset));
|
|
1457
1501
|
if (!cached && item.asset) {
|
|
1458
|
-
cached = await this._resolveAsset(item.asset);
|
|
1502
|
+
cached = (await this._resolveAsset(item.asset)) ?? undefined;
|
|
1459
1503
|
}
|
|
1460
1504
|
if (cached && String(cached.id) === String(offerDebtAssetId)) {
|
|
1461
1505
|
policy = item;
|
|
@@ -1480,7 +1524,7 @@ class CreditRuntime {
|
|
|
1480
1524
|
}
|
|
1481
1525
|
const validation = this._validateCreditPolicy(policy, offerObj, null);
|
|
1482
1526
|
if (!validation.allow) {
|
|
1483
|
-
throw new Error(validation.reason || 'credit offer rejected by policy');
|
|
1527
|
+
throw new Error(String(validation.reason || 'credit offer rejected by policy'));
|
|
1484
1528
|
}
|
|
1485
1529
|
const accountId = await this._resolveAccountId(getAccountRef(this.bot));
|
|
1486
1530
|
if (!accountId) {
|
|
@@ -1516,6 +1560,8 @@ class CreditRuntime {
|
|
|
1516
1560
|
}
|
|
1517
1561
|
let borrowInt = null;
|
|
1518
1562
|
let requiredCollateralInt = null;
|
|
1563
|
+
let requestedBorrowInt = null;
|
|
1564
|
+
let clampedByCollateral = false;
|
|
1519
1565
|
const requestedBorrowAmount = borrowAmount !== undefined && borrowAmount !== null
|
|
1520
1566
|
? positiveOrNull(borrowAmount)
|
|
1521
1567
|
: null;
|
|
@@ -1523,28 +1569,54 @@ class CreditRuntime {
|
|
|
1523
1569
|
throw new Error('borrowAmount must be positive');
|
|
1524
1570
|
}
|
|
1525
1571
|
if (requestedBorrowAmount !== null) {
|
|
1526
|
-
borrowInt = floatToBlockchainInt(requestedBorrowAmount, debtAsset.precision);
|
|
1572
|
+
borrowInt = floatToBlockchainInt(requestedBorrowAmount, Number(debtAsset.precision));
|
|
1527
1573
|
if (!Number.isFinite(borrowInt) || borrowInt <= 0) {
|
|
1528
1574
|
throw new Error('borrowAmount must be positive');
|
|
1529
1575
|
}
|
|
1576
|
+
requestedBorrowInt = borrowInt;
|
|
1577
|
+
// A reborrow can only lock the collateral the repay just released.
|
|
1578
|
+
// If the requested borrow needs more than that (for example the
|
|
1579
|
+
// market moved against the collateral since the deal was opened),
|
|
1580
|
+
// scale the borrow down to what the budget supports instead of
|
|
1581
|
+
// emitting an op that cannot be collateralized.
|
|
1582
|
+
const hasCollateralBudget = availableCollateralAmount !== null && availableCollateralAmount !== undefined && availableCollateralAmount > 0;
|
|
1583
|
+
if (hasCollateralBudget) {
|
|
1584
|
+
const cappedBorrowInt = sharedCapBorrowToCollateral(borrowInt, availableCollateralAmount, collateralPrice, String(debtAsset.id), String(collateralAsset.id));
|
|
1585
|
+
if (cappedBorrowInt === null || cappedBorrowInt <= 0) {
|
|
1586
|
+
throw new Error('released collateral cannot support any reborrow at offer price');
|
|
1587
|
+
}
|
|
1588
|
+
if (cappedBorrowInt < borrowInt) {
|
|
1589
|
+
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`);
|
|
1590
|
+
borrowInt = cappedBorrowInt;
|
|
1591
|
+
clampedByCollateral = true;
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1530
1594
|
this._enforceMaxBorrowAmount(policy, borrowInt, debtAsset, { pendingRepayAmount });
|
|
1531
1595
|
const minimumCollateralInt = this._calculateRequiredCollateral(borrowInt, collateralPrice, debtAsset, collateralAsset);
|
|
1532
1596
|
const collateralReferenceAmount = isPercentageAmountSpec(collateralSpec)
|
|
1533
|
-
? await this._getCollateralPercentageBase(accountId, collateralAsset.id)
|
|
1597
|
+
? await this._getCollateralPercentageBase(accountId, String(collateralAsset.id))
|
|
1534
1598
|
: null;
|
|
1535
1599
|
requiredCollateralInt = collateralSpec?.amount !== null && collateralSpec?.amount !== undefined
|
|
1536
1600
|
? await this._resolveAmountToBlockchainInt(collateralSpec, collateralAsset, accountId, { balanceField: 'total', referenceAmount: collateralReferenceAmount, referenceLabel: 'total collateral balance' })
|
|
1537
1601
|
: minimumCollateralInt;
|
|
1602
|
+
// An explicit collateral amount (e.g. a percentage spec) may still
|
|
1603
|
+
// exceed the released budget; cap it so the op cannot over-lock. Do
|
|
1604
|
+
// NOT recompute the borrow here — it was already clamped above and
|
|
1605
|
+
// must never grow back past the requested amount.
|
|
1606
|
+
if (hasCollateralBudget && requiredCollateralInt != null && requiredCollateralInt > availableCollateralAmount) {
|
|
1607
|
+
requiredCollateralInt = availableCollateralAmount;
|
|
1608
|
+
}
|
|
1538
1609
|
if (minimumCollateralInt != null && requiredCollateralInt != null && requiredCollateralInt < minimumCollateralInt) {
|
|
1539
1610
|
throw new Error(`collateral amount ${requiredCollateralInt} is below required collateral ${minimumCollateralInt}`);
|
|
1540
1611
|
}
|
|
1541
1612
|
}
|
|
1542
1613
|
else {
|
|
1543
1614
|
const collateralReferenceAmount = isPercentageAmountSpec(collateralSpec)
|
|
1544
|
-
? await this._getCollateralPercentageBase(accountId, collateralAsset.id)
|
|
1615
|
+
? await this._getCollateralPercentageBase(accountId, String(collateralAsset.id))
|
|
1545
1616
|
: null;
|
|
1546
1617
|
requiredCollateralInt = await this._resolveAmountToBlockchainInt(collateralSpec, collateralAsset, accountId, { balanceField: 'total', referenceAmount: collateralReferenceAmount, referenceLabel: 'total collateral balance' });
|
|
1547
1618
|
borrowInt = this._calculateBorrowAmountFromCollateral(requiredCollateralInt, collateralPrice, debtAsset, collateralAsset);
|
|
1619
|
+
requestedBorrowInt = borrowInt;
|
|
1548
1620
|
if (borrowInt != null && Number.isFinite(borrowInt) && borrowInt > 0) {
|
|
1549
1621
|
this._enforceMaxBorrowAmount(policy, borrowInt, debtAsset, { pendingRepayAmount });
|
|
1550
1622
|
}
|
|
@@ -1552,7 +1624,7 @@ class CreditRuntime {
|
|
|
1552
1624
|
// Enforce per-operation borrow limit
|
|
1553
1625
|
const maxPerOp = positiveOrNull(policy?.maxBorrowAmountPerOperation);
|
|
1554
1626
|
if (maxPerOp !== null && borrowInt != null && borrowInt > 0) {
|
|
1555
|
-
const borrowFloat = blockchainToFloat(borrowInt, debtAsset.precision);
|
|
1627
|
+
const borrowFloat = blockchainToFloat(borrowInt, Number(debtAsset.precision));
|
|
1556
1628
|
if (Number.isFinite(borrowFloat) && borrowFloat > maxPerOp) {
|
|
1557
1629
|
throw new Error(`borrowAmount ${borrowFloat} exceeds maxBorrowAmountPerOperation ${maxPerOp}`);
|
|
1558
1630
|
}
|
|
@@ -1592,7 +1664,7 @@ class CreditRuntime {
|
|
|
1592
1664
|
if (maxCollateralRatioValue === null) {
|
|
1593
1665
|
throw new Error('creditOffer maxCollateralRatio is required');
|
|
1594
1666
|
}
|
|
1595
|
-
const borrowAmountFloat = blockchainToFloat(borrowInt, debtAsset.precision);
|
|
1667
|
+
const borrowAmountFloat = blockchainToFloat(borrowInt, Number(debtAsset.precision));
|
|
1596
1668
|
const collateralValueInDebtAsset = await this._calculateCollateralValueInDebtAsset(requiredCollateralInt, collateralAsset, debtAsset, collateralPrice);
|
|
1597
1669
|
const offerCollateralValueInDebtAsset = this._calculateCreditOfferCollateralValueInDebtAsset(requiredCollateralInt, collateralAsset, debtAsset, collateralPrice);
|
|
1598
1670
|
if (collateralValueInDebtAsset == null || offerCollateralValueInDebtAsset == null || borrowAmountFloat <= 0 || collateralValueInDebtAsset <= 0 || offerCollateralValueInDebtAsset <= 0) {
|
|
@@ -1615,8 +1687,8 @@ class CreditRuntime {
|
|
|
1615
1687
|
fee: { amount: 0, asset_id: ZERO_ASSET_ID },
|
|
1616
1688
|
borrower: accountId,
|
|
1617
1689
|
offer_id: offerId,
|
|
1618
|
-
borrow_amount: toAmountObject(borrowInt, debtAsset.id),
|
|
1619
|
-
collateral: toAmountObject(requiredCollateralInt, collateralAsset.id),
|
|
1690
|
+
borrow_amount: toAmountObject(borrowInt, String(debtAsset.id)),
|
|
1691
|
+
collateral: toAmountObject(requiredCollateralInt, String(collateralAsset.id)),
|
|
1620
1692
|
max_fee_rate: offerFeeRate,
|
|
1621
1693
|
min_duration_seconds: minDuration,
|
|
1622
1694
|
extensions,
|
|
@@ -1625,7 +1697,9 @@ class CreditRuntime {
|
|
|
1625
1697
|
this.state.lastBorrowRequest = {
|
|
1626
1698
|
offerId: String(offerId),
|
|
1627
1699
|
borrowAmount: borrowInt,
|
|
1700
|
+
requestedBorrowAmount: requestedBorrowInt,
|
|
1628
1701
|
collateralAmount: requiredCollateralInt,
|
|
1702
|
+
clampedByCollateral,
|
|
1629
1703
|
autoReborrow: !!policy?.autoReborrow,
|
|
1630
1704
|
requestedAt: nowIso()
|
|
1631
1705
|
};
|
|
@@ -1650,7 +1724,7 @@ class CreditRuntime {
|
|
|
1650
1724
|
if (!debtAsset) {
|
|
1651
1725
|
throw new Error('Unable to resolve debt asset metadata for credit repay');
|
|
1652
1726
|
}
|
|
1653
|
-
const repayInt = floatToBlockchainInt(repayAmount, debtAsset.precision);
|
|
1727
|
+
const repayInt = floatToBlockchainInt(repayAmount, Number(debtAsset.precision));
|
|
1654
1728
|
if (!Number.isFinite(repayInt) || repayInt <= 0) {
|
|
1655
1729
|
throw new Error('repayAmount must be positive');
|
|
1656
1730
|
}
|
|
@@ -1664,8 +1738,8 @@ class CreditRuntime {
|
|
|
1664
1738
|
fee: { amount: 0, asset_id: ZERO_ASSET_ID },
|
|
1665
1739
|
account: accountId,
|
|
1666
1740
|
deal_id: dealSummary.id,
|
|
1667
|
-
repay_amount: toAmountObject(repayInt, debtAsset.id),
|
|
1668
|
-
credit_fee: toAmountObject(creditFee, debtAsset.id),
|
|
1741
|
+
repay_amount: toAmountObject(repayInt, String(debtAsset.id)),
|
|
1742
|
+
credit_fee: toAmountObject(creditFee, String(debtAsset.id)),
|
|
1669
1743
|
extensions: [],
|
|
1670
1744
|
}
|
|
1671
1745
|
};
|
|
@@ -1739,7 +1813,7 @@ class CreditRuntime {
|
|
|
1739
1813
|
}
|
|
1740
1814
|
const repayOp = await this.buildCreditDealRepayOperation(dealSummary, repayAmount);
|
|
1741
1815
|
const operations = [repayOp];
|
|
1742
|
-
const reborrowPolicy = options.specificPolicy || await this._findLendingItemForAsset(dealSummary.debtAssetId, 'creditOffer') || {};
|
|
1816
|
+
const reborrowPolicy = (options.specificPolicy || await this._findLendingItemForAsset(dealSummary.debtAssetId, 'creditOffer') || {});
|
|
1743
1817
|
let shouldAutoReborrow = options.autoReborrow !== false && !!reborrowPolicy.autoReborrow;
|
|
1744
1818
|
if (shouldAutoReborrow) {
|
|
1745
1819
|
const disallowedDealIds = this._normalizePolicyList(reborrowPolicy.disallowedDealIds);
|
|
@@ -1749,7 +1823,15 @@ class CreditRuntime {
|
|
|
1749
1823
|
}
|
|
1750
1824
|
let deferredReborrowRequest = null;
|
|
1751
1825
|
let inlineReborrowPlanned = false;
|
|
1826
|
+
let availableReborrowCollateralInt = null;
|
|
1827
|
+
// Snapshot the deals that already exist before this repay broadcasts.
|
|
1828
|
+
// A later pending reborrow can then distinguish a genuine replacement
|
|
1829
|
+
// (a deal that appeared after the repay) from a sibling deal that was
|
|
1830
|
+
// already present on the same offer and must not suppress the reborrow.
|
|
1831
|
+
const preRepayDealIds = this._collectActiveDealIds();
|
|
1752
1832
|
if (shouldAutoReborrow) {
|
|
1833
|
+
// Collateral this repay frees — the ceiling a reborrow may lock.
|
|
1834
|
+
availableReborrowCollateralInt = await this._computeReleasedCollateralInt(dealSummary, repayAmount, options);
|
|
1753
1835
|
const reborrowAmount = options.reborrowAmount !== undefined && options.reborrowAmount !== null
|
|
1754
1836
|
? options.reborrowAmount
|
|
1755
1837
|
: repayAmount;
|
|
@@ -1782,9 +1864,9 @@ class CreditRuntime {
|
|
|
1782
1864
|
}
|
|
1783
1865
|
}
|
|
1784
1866
|
const policyHasAutoRepay = Object.prototype.hasOwnProperty.call(reborrowPolicy, 'autoRepay');
|
|
1785
|
-
const autoRepaySetting = options.autoRepay !== undefined
|
|
1867
|
+
const autoRepaySetting = (options.autoRepay !== undefined
|
|
1786
1868
|
? options.autoRepay
|
|
1787
|
-
: (policyHasAutoRepay ? reborrowPolicy.autoRepay : (dealSummary.autoRepay ?? false));
|
|
1869
|
+
: (policyHasAutoRepay ? reborrowPolicy.autoRepay : (dealSummary.autoRepay ?? false)));
|
|
1788
1870
|
const offer = await this._getOfferById(dealSummary.offerId);
|
|
1789
1871
|
if (offer) {
|
|
1790
1872
|
try {
|
|
@@ -1796,6 +1878,7 @@ class CreditRuntime {
|
|
|
1796
1878
|
specificPolicy: options.specificPolicy,
|
|
1797
1879
|
pendingRepayAmount: repayAmount,
|
|
1798
1880
|
pendingReleaseCollateralAmount: options.pendingReleaseCollateralAmount,
|
|
1881
|
+
availableCollateralAmount: availableReborrowCollateralInt,
|
|
1799
1882
|
});
|
|
1800
1883
|
operations.push(acceptOp);
|
|
1801
1884
|
inlineReborrowPlanned = true;
|
|
@@ -1810,6 +1893,7 @@ class CreditRuntime {
|
|
|
1810
1893
|
autoRepay: autoRepaySetting,
|
|
1811
1894
|
pendingRepayAmount: repayAmount,
|
|
1812
1895
|
pendingReleaseCollateralAmount: options.pendingReleaseCollateralAmount,
|
|
1896
|
+
availableCollateralAmount: availableReborrowCollateralInt,
|
|
1813
1897
|
excludeOfferId: dealSummary.offerId,
|
|
1814
1898
|
});
|
|
1815
1899
|
if (fallback) {
|
|
@@ -1825,6 +1909,8 @@ class CreditRuntime {
|
|
|
1825
1909
|
collateralAmount: reborrowCollateralAmount,
|
|
1826
1910
|
autoRepay: autoRepaySetting,
|
|
1827
1911
|
specificPolicy: reborrowPolicy,
|
|
1912
|
+
preRepayDealIds,
|
|
1913
|
+
availableCollateralAmount: availableReborrowCollateralInt,
|
|
1828
1914
|
pendingRepayAmount: repayAmount,
|
|
1829
1915
|
pendingReleaseCollateralAmount: options.pendingReleaseCollateralAmount,
|
|
1830
1916
|
requestedAt: nowIso(),
|
|
@@ -1843,6 +1929,7 @@ class CreditRuntime {
|
|
|
1843
1929
|
autoRepay: autoRepaySetting,
|
|
1844
1930
|
pendingRepayAmount: repayAmount,
|
|
1845
1931
|
pendingReleaseCollateralAmount: options.pendingReleaseCollateralAmount,
|
|
1932
|
+
availableCollateralAmount: availableReborrowCollateralInt,
|
|
1846
1933
|
excludeOfferId: dealSummary.offerId,
|
|
1847
1934
|
});
|
|
1848
1935
|
if (fallback) {
|
|
@@ -1858,6 +1945,8 @@ class CreditRuntime {
|
|
|
1858
1945
|
collateralAmount: reborrowCollateralAmount,
|
|
1859
1946
|
autoRepay: autoRepaySetting,
|
|
1860
1947
|
specificPolicy: reborrowPolicy,
|
|
1948
|
+
preRepayDealIds,
|
|
1949
|
+
availableCollateralAmount: availableReborrowCollateralInt,
|
|
1861
1950
|
pendingRepayAmount: repayAmount,
|
|
1862
1951
|
pendingReleaseCollateralAmount: options.pendingReleaseCollateralAmount,
|
|
1863
1952
|
requestedAt: nowIso(),
|
|
@@ -1886,6 +1975,8 @@ class CreditRuntime {
|
|
|
1886
1975
|
? reborrowPolicy.autoRepay
|
|
1887
1976
|
: (dealSummary.autoRepay ?? false)),
|
|
1888
1977
|
specificPolicy: reborrowPolicy,
|
|
1978
|
+
preRepayDealIds,
|
|
1979
|
+
availableCollateralAmount: availableReborrowCollateralInt,
|
|
1889
1980
|
pendingRepayAmount: repayAmount,
|
|
1890
1981
|
pendingReleaseCollateralAmount: options.pendingReleaseCollateralAmount,
|
|
1891
1982
|
requestedAt: nowIso(),
|
|
@@ -1900,6 +1991,7 @@ class CreditRuntime {
|
|
|
1900
1991
|
autoRepay: reborrowRequest.autoRepay,
|
|
1901
1992
|
specificPolicy: reborrowRequest.specificPolicy,
|
|
1902
1993
|
pendingReleaseCollateralAmount: reborrowRequest.pendingReleaseCollateralAmount,
|
|
1994
|
+
availableCollateralAmount: reborrowRequest.availableCollateralAmount ?? null,
|
|
1903
1995
|
});
|
|
1904
1996
|
await this.executeOperations([acceptOp], 'credit reborrow');
|
|
1905
1997
|
await this.refreshState();
|
|
@@ -1940,6 +2032,9 @@ class CreditRuntime {
|
|
|
1940
2032
|
collateralAmount: request.collateralAmount ?? null,
|
|
1941
2033
|
autoRepay: request.autoRepay ?? false,
|
|
1942
2034
|
specificPolicy: request.specificPolicy || null,
|
|
2035
|
+
preRepayDealIds: Array.isArray(request.preRepayDealIds) ? request.preRepayDealIds.map((id) => String(id)) : null,
|
|
2036
|
+
availableCollateralAmount: request.availableCollateralAmount ?? null,
|
|
2037
|
+
reborrowAttempts: Number(request.reborrowAttempts) || 0,
|
|
1943
2038
|
pendingRepayAmount: request.pendingRepayAmount ?? null,
|
|
1944
2039
|
pendingReleaseCollateralAmount: request.pendingReleaseCollateralAmount ?? null,
|
|
1945
2040
|
requestedAt: request.requestedAt || nowIso(),
|
|
@@ -1954,6 +2049,158 @@ class CreditRuntime {
|
|
|
1954
2049
|
const num = Number(parts[parts.length - 1]);
|
|
1955
2050
|
return Number.isFinite(num) ? num : 0;
|
|
1956
2051
|
}
|
|
2052
|
+
_collectActiveDealIds() {
|
|
2053
|
+
// state.creditDeals is the flattened mirror of positions[*].creditDeals
|
|
2054
|
+
// rebuilt after every refresh, so it is the single source of truth here.
|
|
2055
|
+
const ids = new Set();
|
|
2056
|
+
const deals = Array.isArray(this.state.creditDeals) ? this.state.creditDeals : [];
|
|
2057
|
+
for (const deal of deals) {
|
|
2058
|
+
const id = deal?.id;
|
|
2059
|
+
if (id)
|
|
2060
|
+
ids.add(String(id));
|
|
2061
|
+
}
|
|
2062
|
+
return Array.from(ids);
|
|
2063
|
+
}
|
|
2064
|
+
/**
|
|
2065
|
+
* Pick a balance entry from a `getOnChainAssetBalances` result by asset id,
|
|
2066
|
+
* falling back to the asset symbol. Centralizes the lookup shape shared by
|
|
2067
|
+
* the percentage/amount resolvers and the credit helpers.
|
|
2068
|
+
*/
|
|
2069
|
+
_pickOnChainBalanceEntry(balances, assetId, asset) {
|
|
2070
|
+
const balanceMap = balances;
|
|
2071
|
+
const symbol = asset?.symbol;
|
|
2072
|
+
return (balanceMap?.[String(assetId)]
|
|
2073
|
+
|| (symbol != null ? balanceMap?.[String(symbol)] : undefined)
|
|
2074
|
+
|| null);
|
|
2075
|
+
}
|
|
2076
|
+
/**
|
|
2077
|
+
* Read the chain-free balance of the debt asset. Returns null when the
|
|
2078
|
+
* balance cannot be determined so callers can fall back to the legacy
|
|
2079
|
+
* (full-deal) renewal path instead of guessing.
|
|
2080
|
+
*/
|
|
2081
|
+
async _getFreeDebtAssetBalance(debtAssetId, debtAsset) {
|
|
2082
|
+
const accountRef = getAccountRef(this.bot);
|
|
2083
|
+
if (!accountRef || !debtAssetId)
|
|
2084
|
+
return null;
|
|
2085
|
+
try {
|
|
2086
|
+
const balances = await chainOrders.getOnChainAssetBalances(accountRef, [String(debtAssetId)]);
|
|
2087
|
+
const entry = this._pickOnChainBalanceEntry(balances, debtAssetId, debtAsset);
|
|
2088
|
+
const free = toFiniteNumber(entry?.free, NaN);
|
|
2089
|
+
return Number.isFinite(free) ? free : null;
|
|
2090
|
+
}
|
|
2091
|
+
catch (err) {
|
|
2092
|
+
this.warn(`credit runtime: unable to read free balance for ${String(debtAssetId)}: ${getErrorMessage(err)}`);
|
|
2093
|
+
return null;
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
/**
|
|
2097
|
+
* Raw collateral freed by a repay, used as the ceiling a reborrow can lock.
|
|
2098
|
+
* Precedence:
|
|
2099
|
+
* 1. explicit raw `options.availableCollateralAmount` (collateral-switch flow),
|
|
2100
|
+
* 2. exact on-chain `floor(repay * collateral / debt)` when the deal's own
|
|
2101
|
+
* collateral asset is used,
|
|
2102
|
+
* 3. explicit `options.pendingReleaseCollateralAmount` (float) as a fallback.
|
|
2103
|
+
* Returns null when it cannot be determined, so the accept builder keeps the
|
|
2104
|
+
* legacy (unclamped) behaviour.
|
|
2105
|
+
*/
|
|
2106
|
+
async _computeReleasedCollateralInt(dealSummary, repayAmount, options) {
|
|
2107
|
+
// 1. Explicit raw budget (collateral-switch flow) wins.
|
|
2108
|
+
const explicitRaw = toFiniteNumber(options?.availableCollateralAmount, null);
|
|
2109
|
+
if (explicitRaw !== null && explicitRaw > 0)
|
|
2110
|
+
return Math.floor(explicitRaw);
|
|
2111
|
+
const effectiveCollateralAssetId = options?.collateralAsset ?? dealSummary?.collateralAssetId ?? null;
|
|
2112
|
+
const dealCollateralAssetId = dealSummary?.collateralAssetId ?? null;
|
|
2113
|
+
const sameCollateralAsset = !dealCollateralAssetId || !effectiveCollateralAssetId
|
|
2114
|
+
|| String(dealCollateralAssetId) === String(effectiveCollateralAssetId);
|
|
2115
|
+
// 2. Exact on-chain release: floor(repay * collateral / debt), matching
|
|
2116
|
+
// credit_deal_repay_evaluator::do_apply. Preferred over the float
|
|
2117
|
+
// fallback so the budget never over-states the freed collateral.
|
|
2118
|
+
if (sameCollateralAsset) {
|
|
2119
|
+
const debtAsset = await this._resolveAsset(dealSummary?.debtAssetId);
|
|
2120
|
+
const debtPrecision = getAssetPrecision(debtAsset);
|
|
2121
|
+
if (debtPrecision !== null) {
|
|
2122
|
+
const repayInt = floatToBlockchainInt(repayAmount, debtPrecision);
|
|
2123
|
+
const debtInt = toFiniteNumber(dealSummary?.debtAmount, 0);
|
|
2124
|
+
const collateralInt = toFiniteNumber(dealSummary?.collateralAmount, 0);
|
|
2125
|
+
if (Number.isFinite(repayInt) && repayInt > 0 && debtInt > 0 && collateralInt > 0) {
|
|
2126
|
+
const released = Math.floor(collateralInt * Math.min(repayInt, debtInt) / debtInt);
|
|
2127
|
+
if (released > 0)
|
|
2128
|
+
return released;
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
// 3. Fallback when raw deal amounts are unavailable: use an explicit
|
|
2132
|
+
// released float, floored at the collateral precision.
|
|
2133
|
+
if (options?.pendingReleaseCollateralAmount !== null && options?.pendingReleaseCollateralAmount !== undefined) {
|
|
2134
|
+
const collateralAsset = effectiveCollateralAssetId ? await this._resolveAsset(effectiveCollateralAssetId) : null;
|
|
2135
|
+
const collateralPrecision = getAssetPrecision(collateralAsset);
|
|
2136
|
+
if (collateralPrecision === null)
|
|
2137
|
+
return null;
|
|
2138
|
+
const explicitFloat = toFiniteNumber(options.pendingReleaseCollateralAmount, null);
|
|
2139
|
+
if (explicitFloat === null || explicitFloat <= 0)
|
|
2140
|
+
return null;
|
|
2141
|
+
const explicit = floorToBlockchainInt(explicitFloat, collateralPrecision);
|
|
2142
|
+
return Number.isFinite(explicit) && explicit > 0 ? explicit : null;
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
return null;
|
|
2146
|
+
}
|
|
2147
|
+
/**
|
|
2148
|
+
* Decide how much of a maturing deal can actually be repaid and reborrowed
|
|
2149
|
+
* with the currently free debt-asset balance. The repay leg is funded from
|
|
2150
|
+
* the borrower's free balance before the atomic reborrow returns anything,
|
|
2151
|
+
* so when the borrowed asset has been deployed into the grid the full deal
|
|
2152
|
+
* cannot be renewed in one shot. In that case we roll the largest affordable
|
|
2153
|
+
* piece (bounded by min_deal_amount and maxBorrowAmountPerOperation) and let
|
|
2154
|
+
* the remaining debt be handled on the next cycle.
|
|
2155
|
+
*
|
|
2156
|
+
* Returns null when sizing is not possible (unknown balance / malformed
|
|
2157
|
+
* deal) so the caller keeps the existing full-renewal behaviour.
|
|
2158
|
+
*/
|
|
2159
|
+
async _resolveRenewalSizing({ deal, debtAsset, offer, policy }) {
|
|
2160
|
+
const fullAmount = blockchainAmountToFloat(deal?.debtAmount, debtAsset);
|
|
2161
|
+
if (fullAmount == null || fullAmount <= 0)
|
|
2162
|
+
return null;
|
|
2163
|
+
const feeRate = Number(deal?.feeRate) || 0;
|
|
2164
|
+
const free = await this._getFreeDebtAssetBalance(deal?.debtAssetId, debtAsset);
|
|
2165
|
+
if (free === null)
|
|
2166
|
+
return null;
|
|
2167
|
+
// Work in raw debt units and reuse the on-chain (ceil) fee helper so the
|
|
2168
|
+
// sizing matches what the repay will actually require.
|
|
2169
|
+
const precisionRaw = Number(debtAsset?.precision);
|
|
2170
|
+
const decimals = Number.isFinite(precisionRaw) && precisionRaw >= 0 ? Math.trunc(precisionRaw) : 0;
|
|
2171
|
+
const fullInt = floorToBlockchainInt(fullAmount, decimals);
|
|
2172
|
+
const freeInt = floorToBlockchainInt(free, decimals);
|
|
2173
|
+
const requiredInt = fullInt + sharedCreditDealFee(fullInt, feeRate, CREDIT_FEE_RATE_DENOM);
|
|
2174
|
+
const required = blockchainToFloat(requiredInt, decimals);
|
|
2175
|
+
const spendableInt = freeInt - CREDIT_REBORROW_FREE_BALANCE_BUFFER_INT;
|
|
2176
|
+
if (spendableInt >= requiredInt) {
|
|
2177
|
+
return { partial: false, amount: fullAmount, free, required };
|
|
2178
|
+
}
|
|
2179
|
+
const minDealInt = toFiniteNumber(offer?.min_deal_amount, null);
|
|
2180
|
+
const minDeal = minDealInt !== null ? blockchainToFloat(minDealInt, decimals) : null;
|
|
2181
|
+
// Start from an upper estimate and step down until piece + ceil(fee)
|
|
2182
|
+
// fits the spendable balance; the loop runs at most a couple of iterations.
|
|
2183
|
+
let pieceInt = spendableInt > 0 ? Math.ceil(spendableInt / (1 + feeRate / CREDIT_FEE_RATE_DENOM)) : 0;
|
|
2184
|
+
while (pieceInt > 0 && pieceInt + sharedCreditDealFee(pieceInt, feeRate, CREDIT_FEE_RATE_DENOM) > spendableInt) {
|
|
2185
|
+
pieceInt -= 1;
|
|
2186
|
+
}
|
|
2187
|
+
const maxPerOp = positiveOrNull(policy?.maxBorrowAmountPerOperation);
|
|
2188
|
+
if (maxPerOp !== null && maxPerOp > 0) {
|
|
2189
|
+
const maxPerOpInt = floorToBlockchainInt(maxPerOp, decimals);
|
|
2190
|
+
if (maxPerOpInt < pieceInt)
|
|
2191
|
+
pieceInt = maxPerOpInt;
|
|
2192
|
+
}
|
|
2193
|
+
const affordable = blockchainToFloat(pieceInt, decimals);
|
|
2194
|
+
if (!Number.isFinite(affordable)
|
|
2195
|
+
|| affordable <= 0
|
|
2196
|
+
|| (minDeal !== null && minDeal > 0 && affordable < minDeal)) {
|
|
2197
|
+
return { partial: false, insufficient: true, amount: 0, free, required, minDeal };
|
|
2198
|
+
}
|
|
2199
|
+
if (affordable >= fullAmount) {
|
|
2200
|
+
return { partial: false, amount: fullAmount, free, required };
|
|
2201
|
+
}
|
|
2202
|
+
return { partial: true, amount: affordable, free, required, minDeal };
|
|
2203
|
+
}
|
|
1957
2204
|
async _getOfferById(offerId) {
|
|
1958
2205
|
if (!offerId)
|
|
1959
2206
|
return null;
|
|
@@ -1967,7 +2214,7 @@ class CreditRuntime {
|
|
|
1967
2214
|
// cause deal-split guards to pass against a value that no longer
|
|
1968
2215
|
// holds on-chain.
|
|
1969
2216
|
const OFFER_CACHE_TTL_MS = require('./constants').TIMING.OFFER_CACHE_TTL_MS;
|
|
1970
|
-
const cachedAt = cached._cachedAt || 0;
|
|
2217
|
+
const cachedAt = Number(cached._cachedAt) || 0;
|
|
1971
2218
|
if (Date.now() - cachedAt < OFFER_CACHE_TTL_MS) {
|
|
1972
2219
|
return cached;
|
|
1973
2220
|
}
|
|
@@ -2026,7 +2273,7 @@ class CreditRuntime {
|
|
|
2026
2273
|
collateralAssetId: collateralAsset?.id ? String(collateralAsset.id) : null,
|
|
2027
2274
|
};
|
|
2028
2275
|
}
|
|
2029
|
-
async _selectFallbackCreditOffer({ debtAssetId, collateralAssetId, policy, borrowAmount, collateralAmount, autoRepay, pendingRepayAmount = null, pendingReleaseCollateralAmount, excludeOfferId = null } = {}) {
|
|
2276
|
+
async _selectFallbackCreditOffer({ debtAssetId, collateralAssetId, policy, borrowAmount, collateralAmount, autoRepay, pendingRepayAmount = null, pendingReleaseCollateralAmount, availableCollateralAmount = null, excludeOfferId = null } = {}) {
|
|
2030
2277
|
const offers = await this._fetchCreditOffersByAsset(debtAssetId);
|
|
2031
2278
|
const candidates = [];
|
|
2032
2279
|
for (const offer of offers) {
|
|
@@ -2049,29 +2296,23 @@ class CreditRuntime {
|
|
|
2049
2296
|
offer,
|
|
2050
2297
|
borrowAmount,
|
|
2051
2298
|
collateralAmount,
|
|
2052
|
-
autoRepay,
|
|
2299
|
+
autoRepay: autoRepay,
|
|
2053
2300
|
specificPolicy: policy,
|
|
2054
2301
|
pendingRepayAmount,
|
|
2055
2302
|
pendingReleaseCollateralAmount,
|
|
2303
|
+
availableCollateralAmount,
|
|
2056
2304
|
});
|
|
2057
2305
|
candidates.push({
|
|
2058
2306
|
offer,
|
|
2059
2307
|
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),
|
|
2308
|
+
...offerRankingFields(this._calculateDailyFeeRate(offer), offer),
|
|
2064
2309
|
});
|
|
2065
2310
|
}
|
|
2066
2311
|
catch (_) {
|
|
2067
2312
|
// Candidate does not satisfy amount, ratio, balance, or duration policy.
|
|
2068
2313
|
}
|
|
2069
2314
|
}
|
|
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))));
|
|
2315
|
+
candidates.sort(compareCreditOfferCandidates);
|
|
2075
2316
|
return candidates[0] || null;
|
|
2076
2317
|
}
|
|
2077
2318
|
async _selectCreditOfferForIncrease({ debtAssetId, collateralAssetId, policy, collateralAmount, minCollateralIncrease = 0, remainingBorrowCapacity = null, autoRepay } = {}) {
|
|
@@ -2129,7 +2370,7 @@ class CreditRuntime {
|
|
|
2129
2370
|
if (accountId && debtAsset && collateralAsset && effectiveBorrowCapacity !== null) {
|
|
2130
2371
|
const collateralSpec = normalizeAmountSpec(collateralAmount);
|
|
2131
2372
|
const collateralReferenceAmount = isPercentageAmountSpec(collateralSpec)
|
|
2132
|
-
? await this._getCollateralPercentageBase(accountId, collateralAsset.id)
|
|
2373
|
+
? await this._getCollateralPercentageBase(accountId, String(collateralAsset.id))
|
|
2133
2374
|
: null;
|
|
2134
2375
|
const requestedCollateralInt = await this._resolveAmountToBlockchainInt(collateralSpec, collateralAsset, accountId, {
|
|
2135
2376
|
balanceField: 'total',
|
|
@@ -2137,7 +2378,7 @@ class CreditRuntime {
|
|
|
2137
2378
|
referenceLabel: 'total collateral balance',
|
|
2138
2379
|
});
|
|
2139
2380
|
const desiredBorrowInt = this._calculateBorrowAmountFromCollateral(requestedCollateralInt, collateralPrice, debtAsset, collateralAsset);
|
|
2140
|
-
const desiredBorrowAmount = blockchainToFloat(desiredBorrowInt, debtAsset.precision);
|
|
2381
|
+
const desiredBorrowAmount = blockchainToFloat(desiredBorrowInt, Number(debtAsset.precision));
|
|
2141
2382
|
if (Number.isFinite(desiredBorrowAmount) && desiredBorrowAmount > effectiveBorrowCapacity) {
|
|
2142
2383
|
acceptArgs = {
|
|
2143
2384
|
offer,
|
|
@@ -2163,7 +2404,7 @@ class CreditRuntime {
|
|
|
2163
2404
|
offer,
|
|
2164
2405
|
borrowAmount: effectiveBorrowCapacity,
|
|
2165
2406
|
collateralAmount: { assetId: collateralAssetId },
|
|
2166
|
-
autoRepay,
|
|
2407
|
+
autoRepay: autoRepay,
|
|
2167
2408
|
specificPolicy: policy,
|
|
2168
2409
|
});
|
|
2169
2410
|
}
|
|
@@ -2182,21 +2423,14 @@ class CreditRuntime {
|
|
|
2182
2423
|
borrowAmount: opBorrowAmount,
|
|
2183
2424
|
collateralAmount: opCollateralAmount,
|
|
2184
2425
|
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),
|
|
2426
|
+
...offerRankingFields(this._calculateDailyFeeRate(offer), offer),
|
|
2189
2427
|
});
|
|
2190
2428
|
}
|
|
2191
2429
|
catch (_) {
|
|
2192
2430
|
// Candidate does not satisfy amount, ratio, balance, or duration policy.
|
|
2193
2431
|
}
|
|
2194
2432
|
}
|
|
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))));
|
|
2433
|
+
candidates.sort(compareCreditOfferCandidates);
|
|
2200
2434
|
return candidates[0] || null;
|
|
2201
2435
|
}
|
|
2202
2436
|
async _buildCreditIncreasePlan(lendingItem, assetId, posState) {
|
|
@@ -2312,9 +2546,9 @@ class CreditRuntime {
|
|
|
2312
2546
|
const dealOffer = await this._getOfferById(parseDealSummary(currentDeal)?.offerId);
|
|
2313
2547
|
const minDealAmount = toFiniteNumber(dealOffer?.min_deal_amount, null);
|
|
2314
2548
|
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}`);
|
|
2549
|
+
const pieceAmount = roundToDecimals(dealDebt / numPieces, Number(debtAsset.precision));
|
|
2550
|
+
if (minDealAmount !== null && pieceAmount < blockchainToFloat(minDealAmount, Number(debtAsset.precision))) {
|
|
2551
|
+
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
2552
|
continue;
|
|
2319
2553
|
}
|
|
2320
2554
|
const dealPieces = Math.min(numPieces - 1, MAX_PIECES_PER_CYCLE - totalPiecesThisCycle);
|
|
@@ -2338,7 +2572,7 @@ class CreditRuntime {
|
|
|
2338
2572
|
});
|
|
2339
2573
|
}
|
|
2340
2574
|
// Re-fetch deal from current state (may have been refreshed by repayCreditDeal)
|
|
2341
|
-
const pos = this.state.positions?.[posKey];
|
|
2575
|
+
const pos = this.state.positions?.[String(posKey)];
|
|
2342
2576
|
const refreshed = Array.isArray(pos?.creditDeals)
|
|
2343
2577
|
? pos.creditDeals.find((d) => String(d.id) === dealId)
|
|
2344
2578
|
: null;
|
|
@@ -2384,8 +2618,8 @@ class CreditRuntime {
|
|
|
2384
2618
|
return null;
|
|
2385
2619
|
const accountId = await this._resolveAccountId(accountRef) || accountRef;
|
|
2386
2620
|
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
|
|
2621
|
+
const normalized = Array.isArray(dealObjects) ? dealObjects.map(parseDealSummary).filter((d) => d !== null) : [];
|
|
2622
|
+
return (normalized.find((entry) => String(entry?.id) === String(dealId)) || null);
|
|
2389
2623
|
}
|
|
2390
2624
|
async processPendingReborrows() {
|
|
2391
2625
|
if (!Array.isArray(this.state.pendingReborrows) || this.state.pendingReborrows.length === 0) {
|
|
@@ -2395,18 +2629,34 @@ class CreditRuntime {
|
|
|
2395
2629
|
return { skipped: true, reason: 'reborrow processing already in flight' };
|
|
2396
2630
|
}
|
|
2397
2631
|
this._reborrowsInFlight = true;
|
|
2632
|
+
const configuredMaxAttempts = Number(this.config?.timing?.CREDIT_REBORROW_MAX_ATTEMPTS);
|
|
2633
|
+
const maxReborrowAttempts = Number.isFinite(configuredMaxAttempts) && configuredMaxAttempts > 0
|
|
2634
|
+
? Math.trunc(configuredMaxAttempts)
|
|
2635
|
+
: TIMING.CREDIT_REBORROW_MAX_ATTEMPTS;
|
|
2398
2636
|
try {
|
|
2399
2637
|
const onChainDeals = await this._fetchBorrowerDeals();
|
|
2400
2638
|
const activeDealIds = new Set(onChainDeals.map((deal) => String(deal?.id)).filter(Boolean));
|
|
2401
2639
|
const nextQueue = [];
|
|
2402
2640
|
let processed = 0;
|
|
2641
|
+
// Bounded retry: build/broadcast failures increment the attempt count
|
|
2642
|
+
// and are dropped once the limit is reached. Transient deferrals
|
|
2643
|
+
// (offer missing/disabled, source deal still active) are not counted.
|
|
2644
|
+
const recordFailedAttempt = (request, label, err) => {
|
|
2645
|
+
const attempts = (Number(request.reborrowAttempts) || 0) + 1;
|
|
2646
|
+
if (attempts >= maxReborrowAttempts) {
|
|
2647
|
+
this.warn(`credit runtime: dropping ${label} for offer ${request.offerId} after ${attempts} failed attempt(s) — last error: ${getErrorMessage(err)}`);
|
|
2648
|
+
return;
|
|
2649
|
+
}
|
|
2650
|
+
this.warn(`credit runtime: ${label} for offer ${request.offerId} failed (attempt ${attempts}/${maxReborrowAttempts}): ${getErrorMessage(err)}`);
|
|
2651
|
+
nextQueue.push({ ...request, reborrowAttempts: attempts, reason: getErrorMessage(err) });
|
|
2652
|
+
};
|
|
2403
2653
|
for (const request of this.state.pendingReborrows) {
|
|
2404
2654
|
if (!request?.offerId || (request.borrowAmount == null && request.collateralAmount == null)) {
|
|
2405
2655
|
this.warn(`credit runtime: dropping invalid pending reborrow request${request?.sourceDealId ? ` for deal ${request.sourceDealId}` : ''} — missing offerId or borrow/collateral amounts`);
|
|
2406
2656
|
continue;
|
|
2407
2657
|
}
|
|
2408
2658
|
const offer = await this._getOfferById(request.offerId);
|
|
2409
|
-
const requestPolicy = request.specificPolicy || (offer ? await this._resolveLendingPolicyForOffer(offer) : null);
|
|
2659
|
+
const requestPolicy = (request.specificPolicy || (offer ? await this._resolveLendingPolicyForOffer(offer) : null));
|
|
2410
2660
|
if (!requestPolicy || !requestPolicy.autoReborrow) {
|
|
2411
2661
|
this.warn(`credit runtime: dropping pending reborrow for offer ${request.offerId}; autoReborrow disabled or policy missing`);
|
|
2412
2662
|
continue;
|
|
@@ -2429,8 +2679,19 @@ class CreditRuntime {
|
|
|
2429
2679
|
if (request.sourceDealId && request.offerId && requestPolicy?.renewOnly === true) {
|
|
2430
2680
|
const sourceNum = this._extractDealNumericId(request.sourceDealId);
|
|
2431
2681
|
if (sourceNum > 0) {
|
|
2432
|
-
const
|
|
2433
|
-
|
|
2682
|
+
const preRepaySnapshot = Array.isArray(request.preRepayDealIds)
|
|
2683
|
+
? new Set(request.preRepayDealIds.map((id) => String(id)))
|
|
2684
|
+
: null;
|
|
2685
|
+
const hasNewerReplacement = onChainDeals.some((d) => {
|
|
2686
|
+
if (String(d?.offerId) !== String(request.offerId))
|
|
2687
|
+
return false;
|
|
2688
|
+
if (this._extractDealNumericId(d.id) <= sourceNum)
|
|
2689
|
+
return false;
|
|
2690
|
+
// With a pre-repay snapshot, only deals that appeared
|
|
2691
|
+
// after the repay count as replacements. Sibling deals
|
|
2692
|
+
// already present on the same offer are not.
|
|
2693
|
+
return preRepaySnapshot ? !preRepaySnapshot.has(String(d.id)) : true;
|
|
2694
|
+
});
|
|
2434
2695
|
if (hasNewerReplacement) {
|
|
2435
2696
|
this.warn(`credit runtime: dropping stale pending reborrow for deal ${request.sourceDealId} — replacement deal already exists for offer ${request.offerId}`);
|
|
2436
2697
|
processed++;
|
|
@@ -2461,8 +2722,9 @@ class CreditRuntime {
|
|
|
2461
2722
|
policy: requestPolicy,
|
|
2462
2723
|
borrowAmount: request.borrowAmount,
|
|
2463
2724
|
collateralAmount: effectiveCollateralAmount,
|
|
2464
|
-
autoRepay: request.autoRepay ?? false,
|
|
2725
|
+
autoRepay: (request.autoRepay ?? false),
|
|
2465
2726
|
pendingReleaseCollateralAmount: request.pendingReleaseCollateralAmount,
|
|
2727
|
+
availableCollateralAmount: request.availableCollateralAmount ?? null,
|
|
2466
2728
|
excludeOfferId: request.offerId,
|
|
2467
2729
|
})
|
|
2468
2730
|
: null;
|
|
@@ -2473,8 +2735,7 @@ class CreditRuntime {
|
|
|
2473
2735
|
processed++;
|
|
2474
2736
|
}
|
|
2475
2737
|
catch (err) {
|
|
2476
|
-
|
|
2477
|
-
nextQueue.push({ ...request, reason: getErrorMessage(err) });
|
|
2738
|
+
recordFailedAttempt(request, 'fallback reborrow', err);
|
|
2478
2739
|
}
|
|
2479
2740
|
}
|
|
2480
2741
|
else {
|
|
@@ -2488,16 +2749,16 @@ class CreditRuntime {
|
|
|
2488
2749
|
offer,
|
|
2489
2750
|
borrowAmount: request.borrowAmount ?? null,
|
|
2490
2751
|
collateralAmount: effectiveCollateralAmount,
|
|
2491
|
-
autoRepay: request.autoRepay ?? false,
|
|
2492
|
-
specificPolicy: request.specificPolicy || requestPolicy,
|
|
2752
|
+
autoRepay: (request.autoRepay ?? false),
|
|
2753
|
+
specificPolicy: (request.specificPolicy || requestPolicy),
|
|
2493
2754
|
pendingReleaseCollateralAmount: request.pendingReleaseCollateralAmount,
|
|
2755
|
+
availableCollateralAmount: request.availableCollateralAmount ?? null,
|
|
2494
2756
|
});
|
|
2495
2757
|
await this.executeOperations([acceptOp], 'credit reborrow');
|
|
2496
2758
|
processed++;
|
|
2497
2759
|
}
|
|
2498
2760
|
catch (err) {
|
|
2499
|
-
|
|
2500
|
-
nextQueue.push({ ...request, reason: getErrorMessage(err) });
|
|
2761
|
+
recordFailedAttempt(request, 'pending reborrow', err);
|
|
2501
2762
|
}
|
|
2502
2763
|
}
|
|
2503
2764
|
this.state.pendingReborrows = nextQueue;
|
|
@@ -2551,14 +2812,14 @@ class CreditRuntime {
|
|
|
2551
2812
|
// Try collateral-only repair; if unavailable, surface the original broadcast failure.
|
|
2552
2813
|
const configuredCollateralAsset = await this._resolveAsset(lendingItem.collateralAsset);
|
|
2553
2814
|
const configuredCollateralAssetId = configuredCollateralAsset?.id;
|
|
2554
|
-
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : assetId;
|
|
2815
|
+
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : String(assetId);
|
|
2555
2816
|
const posState = this.state.positions[posKey];
|
|
2556
2817
|
const collateralPlan = buildCollateralFallbackPlan({
|
|
2557
2818
|
currentCollateralAmount: posState?.currentCollateralAmount,
|
|
2558
2819
|
currentDebtAmount: posState?.currentDebtAmount,
|
|
2559
2820
|
feedPrice: posState?.feedPrice,
|
|
2560
2821
|
targetCollateralRatio: plan.targetCollateralRatio,
|
|
2561
|
-
maxCollateralAmount: posState?.assignedCollateralBudget ?? lendingItem.maxCollateralAmount,
|
|
2822
|
+
maxCollateralAmount: (posState?.assignedCollateralBudget ?? lendingItem.maxCollateralAmount),
|
|
2562
2823
|
collateralLimitReferenceAmount: posState?.currentCollateralFundsTotal,
|
|
2563
2824
|
});
|
|
2564
2825
|
if (collateralPlan) {
|
|
@@ -2583,7 +2844,7 @@ class CreditRuntime {
|
|
|
2583
2844
|
};
|
|
2584
2845
|
const configuredCollateralAsset = await this._resolveAsset(lendingItem.collateralAsset);
|
|
2585
2846
|
const configuredCollateralAssetId = configuredCollateralAsset?.id;
|
|
2586
|
-
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : assetId;
|
|
2847
|
+
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : String(assetId);
|
|
2587
2848
|
if (!this.state.positions[posKey])
|
|
2588
2849
|
this.state.positions[posKey] = {};
|
|
2589
2850
|
this.state.positions[posKey].lastMpaAction = lastAction;
|
|
@@ -2594,7 +2855,7 @@ class CreditRuntime {
|
|
|
2594
2855
|
};
|
|
2595
2856
|
if (typeof this.bot?.requestGridReset === 'function') {
|
|
2596
2857
|
try {
|
|
2597
|
-
const resetReason = plan.resetReason || 'cr-adjustment';
|
|
2858
|
+
const resetReason = String(plan.resetReason || 'cr-adjustment');
|
|
2598
2859
|
const resetResult = await this.bot.requestGridReset(resetReason);
|
|
2599
2860
|
this.state.lastGridResetAt = nowIso();
|
|
2600
2861
|
return { plan, executed, resetResult };
|
|
@@ -2617,7 +2878,7 @@ class CreditRuntime {
|
|
|
2617
2878
|
}
|
|
2618
2879
|
const configuredCollateralAsset = await this._resolveAsset(lendingItem.collateralAsset);
|
|
2619
2880
|
const configuredCollateralAssetId = configuredCollateralAsset?.id;
|
|
2620
|
-
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : assetId;
|
|
2881
|
+
const posKey = configuredCollateralAssetId ? this._positionKey(assetId, configuredCollateralAssetId) : String(assetId);
|
|
2621
2882
|
// Phase 1: Proactively repay deals nearing expiration before processing reborrows
|
|
2622
2883
|
const expiryThresholdHours = this.bot?.config?.timing?.CREDIT_DEAL_EXPIRY_THRESHOLD_HOURS ?? TIMING.CREDIT_DEAL_EXPIRY_THRESHOLD_HOURS;
|
|
2623
2884
|
const expiryThresholdMs = expiryThresholdHours * 60 * 60 * 1000;
|
|
@@ -2651,15 +2912,23 @@ class CreditRuntime {
|
|
|
2651
2912
|
}
|
|
2652
2913
|
const isCollateralMismatch = deal.collateralMismatch === true;
|
|
2653
2914
|
let existingCollateralAmount = null;
|
|
2915
|
+
let explicitAvailableCollateralInt = null;
|
|
2654
2916
|
if (isCollateralMismatch) {
|
|
2655
2917
|
const accountRef = getAccountRef(this.bot);
|
|
2656
2918
|
const balances = await chainOrders.getOnChainAssetBalances(accountRef, [configuredCollateralAssetId]);
|
|
2657
|
-
const balance = balances
|
|
2919
|
+
const balance = this._pickOnChainBalanceEntry(balances, configuredCollateralAssetId, configuredCollateralAsset);
|
|
2658
2920
|
const available = toFiniteNumber(balance?.total, undefined);
|
|
2659
2921
|
if (!Number.isFinite(available) || available <= 0) {
|
|
2660
2922
|
this.warn(`credit runtime: skipping collateral switch for deal ${deal.id} — no balance of new collateral ${configuredCollateralAssetId}`);
|
|
2661
2923
|
continue;
|
|
2662
2924
|
}
|
|
2925
|
+
const configuredCollateralPrecision = getAssetPrecision(configuredCollateralAsset);
|
|
2926
|
+
if (configuredCollateralPrecision !== null) {
|
|
2927
|
+
explicitAvailableCollateralInt = floatToBlockchainInt(available, configuredCollateralPrecision);
|
|
2928
|
+
if (!Number.isFinite(explicitAvailableCollateralInt) || explicitAvailableCollateralInt <= 0) {
|
|
2929
|
+
explicitAvailableCollateralInt = null;
|
|
2930
|
+
}
|
|
2931
|
+
}
|
|
2663
2932
|
}
|
|
2664
2933
|
if (!isCollateralMismatch) {
|
|
2665
2934
|
const collateralAsset = await this._resolveAsset(deal.collateralAssetId);
|
|
@@ -2668,6 +2937,33 @@ class CreditRuntime {
|
|
|
2668
2937
|
throw new Error(`unable to convert deal ${deal.id} collateral amount for release`);
|
|
2669
2938
|
}
|
|
2670
2939
|
}
|
|
2940
|
+
// Shortfall-aware renewal: the repay leg is funded from the
|
|
2941
|
+
// free debt-asset balance before the atomic reborrow returns
|
|
2942
|
+
// anything, so when the borrowed asset has been deployed into
|
|
2943
|
+
// the grid the full deal cannot be renewed at once. Roll the
|
|
2944
|
+
// largest affordable piece instead and leave the rest for the
|
|
2945
|
+
// next cycle rather than failing the whole renewal.
|
|
2946
|
+
const renewalOffer = await this._getOfferById(deal.offerId);
|
|
2947
|
+
const sizing = await this._resolveRenewalSizing({ deal, debtAsset, offer: renewalOffer, policy: lendingItem });
|
|
2948
|
+
let renewalAmount = repayAmount;
|
|
2949
|
+
let isPartialRenewal = false;
|
|
2950
|
+
if (sizing?.partial === true) {
|
|
2951
|
+
renewalAmount = sizing.amount;
|
|
2952
|
+
isPartialRenewal = renewalAmount < repayAmount;
|
|
2953
|
+
}
|
|
2954
|
+
else if (sizing?.insufficient === true) {
|
|
2955
|
+
// Nothing affordable — fall back to the full renewal so the
|
|
2956
|
+
// on-chain failure still surfaces rather than silently
|
|
2957
|
+
// skipping a deal that is about to expire.
|
|
2958
|
+
this.warn(`credit runtime: cannot size a partial renewal for deal ${deal.id} (free ${sizing.free}, required ${sizing.required}); attempting full renewal`);
|
|
2959
|
+
}
|
|
2960
|
+
let renewalPendingReleaseCollateral = isCollateralMismatch ? null : existingCollateralAmount;
|
|
2961
|
+
if (isPartialRenewal && !isCollateralMismatch && existingCollateralAmount != null) {
|
|
2962
|
+
renewalPendingReleaseCollateral = existingCollateralAmount * (renewalAmount / repayAmount);
|
|
2963
|
+
}
|
|
2964
|
+
if (isPartialRenewal) {
|
|
2965
|
+
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`);
|
|
2966
|
+
}
|
|
2671
2967
|
// Snapshot pre-existing pending reborrows for this deal so we
|
|
2672
2968
|
// can prune stale ones after repayCreditDeal without removing
|
|
2673
2969
|
// any new deferred entry that repayCreditDeal itself may queue.
|
|
@@ -2675,14 +2971,15 @@ class CreditRuntime {
|
|
|
2675
2971
|
? this.state.pendingReborrows.filter((r) => r.sourceDealId === String(deal.id))
|
|
2676
2972
|
: [];
|
|
2677
2973
|
const staleKeys = new Set(staleSnapshot.map((r) => `${r.sourceDealId}:${r.offerId}:${r.requestedAt}`));
|
|
2678
|
-
await this.repayCreditDeal(deal,
|
|
2974
|
+
await this.repayCreditDeal(deal, renewalAmount, {
|
|
2679
2975
|
autoReborrow: true,
|
|
2680
|
-
collateralAmount: isCollateralMismatch ? null : {
|
|
2976
|
+
collateralAmount: isCollateralMismatch || isPartialRenewal ? null : {
|
|
2681
2977
|
amount: existingCollateralAmount,
|
|
2682
2978
|
assetId: deal.collateralAssetId,
|
|
2683
2979
|
},
|
|
2684
2980
|
collateralAsset: configuredCollateralAssetId,
|
|
2685
|
-
pendingReleaseCollateralAmount:
|
|
2981
|
+
pendingReleaseCollateralAmount: renewalPendingReleaseCollateral,
|
|
2982
|
+
availableCollateralAmount: explicitAvailableCollateralInt,
|
|
2686
2983
|
specificPolicy: lendingItem,
|
|
2687
2984
|
});
|
|
2688
2985
|
// Prune only the stale entries that existed before the call
|
|
@@ -2788,7 +3085,7 @@ class CreditRuntime {
|
|
|
2788
3085
|
credit: [],
|
|
2789
3086
|
};
|
|
2790
3087
|
const dp = this.debtPolicy;
|
|
2791
|
-
for (const item of dp
|
|
3088
|
+
for (const item of dp?.lending ?? []) {
|
|
2792
3089
|
const resolvedAsset = await this._resolveAsset(item.asset);
|
|
2793
3090
|
const assetId = resolvedAsset?.id ? String(resolvedAsset.id) : null;
|
|
2794
3091
|
if (!assetId) {
|
|
@@ -2823,7 +3120,7 @@ class CreditRuntime {
|
|
|
2823
3120
|
const mpaResults = [];
|
|
2824
3121
|
const creditResults = [];
|
|
2825
3122
|
const dp = this.debtPolicy;
|
|
2826
|
-
for (const item of dp
|
|
3123
|
+
for (const item of dp?.lending ?? []) {
|
|
2827
3124
|
const resolvedAsset = await this._resolveAsset(item.asset);
|
|
2828
3125
|
const assetId = resolvedAsset?.id ? String(resolvedAsset.id) : null;
|
|
2829
3126
|
if (!assetId) {
|