dexbot 1.6.11 → 1.6.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (398) hide show
  1. package/CHANGELOG.md +67 -4
  2. package/README.md +2 -1
  3. package/analysis/README.md +11 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/analysis/tradingview/README.md +1 -1
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
  7. package/claw/README.md +1 -0
  8. package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
  9. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  10. package/claw/modules/chain_broadcast.ts +7 -1
  11. package/claw/modules/claw_bridge.ts +0 -3
  12. package/claw/modules/claw_launcher.ts +1 -1
  13. package/claw/modules/claw_skill_md.ts +1 -0
  14. package/claw/modules/launcher_mode_detector.ts +9 -2
  15. package/claw/package.json +3 -3
  16. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  17. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/account_resolver.d.ts +1 -1
  20. package/dist/analysis/account_resolver.js +2 -1
  21. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  22. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +3 -21
  23. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  24. package/dist/analysis/ama_fitting/fetch_lp_candles.js +55 -45
  25. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -8
  26. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +45 -24
  27. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +34 -78
  28. package/dist/analysis/analyze_args.d.ts +43 -0
  29. package/dist/analysis/analyze_args.js +61 -0
  30. package/dist/analysis/analyze_dynamic_weight.js +7 -17
  31. package/dist/analysis/analyze_kalman.js +7 -17
  32. package/dist/analysis/analyze_regime.js +7 -17
  33. package/dist/analysis/analyze_regime_windows.js +8 -18
  34. package/dist/analysis/analyze_risk_profile.js +8 -18
  35. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  36. package/dist/analysis/analyze_volatility.js +7 -17
  37. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +221 -28
  38. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +23 -103
  39. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  40. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +32 -150
  41. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  42. package/dist/analysis/bot_fitting/shared_utils.d.ts +77 -9
  43. package/dist/analysis/bot_fitting/shared_utils.js +125 -9
  44. package/dist/analysis/bot_key_utils.d.ts +18 -10
  45. package/dist/analysis/bot_key_utils.js +7 -4
  46. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  47. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  48. package/dist/analysis/chain_pool.d.ts +3 -1
  49. package/dist/analysis/chart_ui.d.ts +35 -3
  50. package/dist/analysis/chart_ui.js +43 -4
  51. package/dist/analysis/chart_utils.d.ts +5 -5
  52. package/dist/analysis/chart_utils.js +9 -0
  53. package/dist/analysis/fills_cache.d.ts +4 -24
  54. package/dist/analysis/fills_cache.js +3 -84
  55. package/dist/analysis/fills_source.d.ts +33 -3
  56. package/dist/analysis/fills_source.js +83 -13
  57. package/dist/analysis/grid_correction_check.d.ts +2 -24
  58. package/dist/analysis/grid_correction_check.js +27 -69
  59. package/dist/analysis/math_utils.d.ts +91 -6
  60. package/dist/analysis/math_utils.js +119 -7
  61. package/dist/analysis/pnl_report.js +29 -29
  62. package/dist/analysis/price_sources.d.ts +30 -9
  63. package/dist/analysis/price_sources.js +28 -4
  64. package/dist/analysis/resolve_bot_accounts.js +2 -2
  65. package/dist/analysis/resolve_source.d.ts +1 -1
  66. package/dist/analysis/resolve_source.js +31 -10
  67. package/dist/analysis/trade_profitability.d.ts +29 -2
  68. package/dist/analysis/trade_profitability.js +73 -147
  69. package/dist/analysis/tradingview/analyze_tradingview.d.ts +3 -8
  70. package/dist/analysis/tradingview/analyze_tradingview.js +7 -6
  71. package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
  72. package/dist/analysis/tradingview/grid_reset_config.js +23 -11
  73. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
  74. package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
  75. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  76. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -34
  77. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  78. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +26 -84
  79. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  80. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +16 -41
  81. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
  82. package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
  83. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  84. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  85. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  86. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  87. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  88. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  89. package/dist/analysis/worker_pool.d.ts +38 -0
  90. package/dist/analysis/worker_pool.js +67 -0
  91. package/dist/credential-daemon.js +34 -20
  92. package/dist/dexbot.js +78 -59
  93. package/dist/market_adapter/ama_signal_runner.js +21 -54
  94. package/dist/market_adapter/candle_utils.d.ts +29 -19
  95. package/dist/market_adapter/candle_utils.js +35 -21
  96. package/dist/market_adapter/cli_args.d.ts +22 -0
  97. package/dist/market_adapter/cli_args.js +30 -0
  98. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  99. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  100. package/dist/market_adapter/core/config_normalizers.js +11 -6
  101. package/dist/market_adapter/core/kibana_candles.d.ts +56 -19
  102. package/dist/market_adapter/core/kibana_candles.js +12 -9
  103. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  104. package/dist/market_adapter/core/kibana_client.js +8 -7
  105. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  106. package/dist/market_adapter/core/market_adapter_service.d.ts +320 -153
  107. package/dist/market_adapter/core/market_adapter_service.js +228 -269
  108. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  109. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  110. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  111. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  112. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  113. package/dist/market_adapter/core/strategies/ama.js +2 -4
  114. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  115. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  116. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  117. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  118. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  119. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  120. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
  121. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
  122. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  123. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  124. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  125. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  126. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  127. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  128. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  129. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  130. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  131. package/dist/market_adapter/inputs/fetch_book_data.js +3 -2
  132. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +160 -332
  133. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +50 -8
  134. package/dist/market_adapter/inputs/fetch_lp_data.js +47 -22
  135. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  136. package/dist/market_adapter/inputs/kibana_feed_source.js +26 -41
  137. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  138. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  139. package/dist/market_adapter/inputs/window_cache.d.ts +93 -156
  140. package/dist/market_adapter/inputs/window_cache.js +59 -184
  141. package/dist/market_adapter/interval_utils.d.ts +15 -5
  142. package/dist/market_adapter/interval_utils.js +16 -1
  143. package/dist/market_adapter/log_format.d.ts +6 -6
  144. package/dist/market_adapter/log_format.js +28 -21
  145. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  146. package/dist/market_adapter/lp_chart_core.js +26 -192
  147. package/dist/market_adapter/lp_chart_runner.d.ts +10 -7
  148. package/dist/market_adapter/lp_chart_runner.js +37 -19
  149. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  150. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  151. package/dist/market_adapter/market_adapter.d.ts +94 -32
  152. package/dist/market_adapter/market_adapter.js +94 -120
  153. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  154. package/dist/market_adapter/utils/adapter_client.js +2 -2
  155. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  156. package/dist/market_adapter/utils/chain.d.ts +50 -41
  157. package/dist/market_adapter/utils/chain.js +40 -46
  158. package/dist/market_adapter/utils/data_discovery.d.ts +49 -2
  159. package/dist/market_adapter/utils/data_discovery.js +220 -27
  160. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  161. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  162. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  163. package/dist/market_adapter/utils/file_lock.js +36 -32
  164. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  165. package/dist/market_adapter/utils/month_shards.js +237 -0
  166. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  167. package/dist/market_adapter/utils/native_history.js +35 -28
  168. package/dist/modules/account_bots.d.ts +578 -21
  169. package/dist/modules/account_bots.js +272 -267
  170. package/dist/modules/account_orders.d.ts +79 -30
  171. package/dist/modules/account_orders.js +60 -64
  172. package/dist/modules/authority_resolver.d.ts +12 -2
  173. package/dist/modules/authority_resolver.js +15 -8
  174. package/dist/modules/bitshares-native/chain_client.d.ts +39 -4
  175. package/dist/modules/bitshares-native/chain_client.js +59 -59
  176. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  177. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  178. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  179. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  180. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  181. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  182. package/dist/modules/bitshares-native/index.d.ts +1 -1
  183. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  184. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  185. package/dist/modules/bitshares-native/resolvers.js +22 -25
  186. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  187. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  188. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  189. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  190. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  191. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  192. package/dist/modules/bitshares-native/serial/types.js +73 -108
  193. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  194. package/dist/modules/bitshares-native/signing_client.js +19 -14
  195. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  196. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  197. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  198. package/dist/modules/bitshares-native/transport.js +5 -4
  199. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  200. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  201. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  202. package/dist/modules/bitshares_client.d.ts +45 -13
  203. package/dist/modules/bitshares_client.js +28 -19
  204. package/dist/modules/bot_defaults.d.ts +8 -16
  205. package/dist/modules/bot_defaults.js +1 -5
  206. package/dist/modules/bot_settings.d.ts +44 -10
  207. package/dist/modules/bot_settings.js +11 -8
  208. package/dist/modules/bots_file_lock.d.ts +6 -6
  209. package/dist/modules/bots_file_lock.js +16 -12
  210. package/dist/modules/broadcast_failure.d.ts +4 -3
  211. package/dist/modules/broadcast_failure.js +5 -4
  212. package/dist/modules/chain_keys.d.ts +42 -40
  213. package/dist/modules/chain_keys.js +53 -45
  214. package/dist/modules/chain_orders.d.ts +94 -60
  215. package/dist/modules/chain_orders.js +81 -118
  216. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  217. package/dist/modules/constants.d.ts +534 -32
  218. package/dist/modules/constants.js +35 -48
  219. package/dist/modules/cr_planner.d.ts +41 -3
  220. package/dist/modules/cr_planner.js +1 -5
  221. package/dist/modules/credential_policy.d.ts +68 -8
  222. package/dist/modules/credential_policy.js +37 -31
  223. package/dist/modules/credential_session_cache.d.ts +2 -2
  224. package/dist/modules/credit_pricing.d.ts +43 -6
  225. package/dist/modules/credit_pricing.js +70 -60
  226. package/dist/modules/credit_runtime.d.ts +283 -118
  227. package/dist/modules/credit_runtime.js +500 -231
  228. package/dist/modules/crypto/browser_provider.js +6 -4
  229. package/dist/modules/crypto/node_provider.js +1 -1
  230. package/dist/modules/crypto/pure_scrypt.js +35 -4
  231. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  232. package/dist/modules/crypto/sync.d.ts +9 -9
  233. package/dist/modules/crypto/sync.js +16 -9
  234. package/dist/modules/daemon_node_health.d.ts +4 -3
  235. package/dist/modules/dexbot_class.d.ts +213 -146
  236. package/dist/modules/dexbot_class.js +183 -86
  237. package/dist/modules/dexbot_cow_runtime.d.ts +160 -87
  238. package/dist/modules/dexbot_cow_runtime.js +302 -234
  239. package/dist/modules/dexbot_credential_client.d.ts +19 -18
  240. package/dist/modules/dexbot_credential_client.js +1 -2
  241. package/dist/modules/dexbot_fill_runtime.d.ts +63 -49
  242. package/dist/modules/dexbot_fill_runtime.js +53 -47
  243. package/dist/modules/dexbot_maintenance_runtime.d.ts +127 -71
  244. package/dist/modules/dexbot_maintenance_runtime.js +187 -147
  245. package/dist/modules/dexbot_startup_runtime.d.ts +11 -11
  246. package/dist/modules/dexbot_startup_runtime.js +56 -57
  247. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  248. package/dist/modules/dexbot_state_recovery.js +18 -13
  249. package/dist/modules/fund_registry.d.ts +4 -2
  250. package/dist/modules/fund_registry.js +10 -10
  251. package/dist/modules/general_settings.d.ts +30 -4
  252. package/dist/modules/graceful_shutdown.d.ts +3 -3
  253. package/dist/modules/graceful_shutdown.js +19 -13
  254. package/dist/modules/grid_price_source.d.ts +1 -1
  255. package/dist/modules/key_store.d.ts +14 -8
  256. package/dist/modules/key_store.js +7 -7
  257. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  258. package/dist/modules/launcher/adapter_requirement.js +5 -5
  259. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  260. package/dist/modules/launcher/bot_supervisor.js +12 -11
  261. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  262. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  263. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  264. package/dist/modules/launcher/credential_daemon.js +2 -2
  265. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  266. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  267. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  268. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  269. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  270. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  271. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  272. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  273. package/dist/modules/launcher/supervisor_control.js +4 -2
  274. package/dist/modules/lazy_shim.d.ts +11 -0
  275. package/dist/modules/lazy_shim.js +16 -0
  276. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  277. package/dist/modules/market_adapter_whitelist.js +15 -3
  278. package/dist/modules/node_connect_policy.d.ts +3 -2
  279. package/dist/modules/node_failure_ledger.d.ts +6 -5
  280. package/dist/modules/node_manager.d.ts +41 -11
  281. package/dist/modules/node_manager.js +5 -4
  282. package/dist/modules/order/accounting.d.ts +53 -24
  283. package/dist/modules/order/accounting.js +16 -15
  284. package/dist/modules/order/async_lock.d.ts +5 -2
  285. package/dist/modules/order/async_lock.js +1 -1
  286. package/dist/modules/order/export.d.ts +7 -6
  287. package/dist/modules/order/export.js +1 -7
  288. package/dist/modules/order/format.d.ts +16 -7
  289. package/dist/modules/order/format.js +15 -3
  290. package/dist/modules/order/genesis_policy.d.ts +24 -21
  291. package/dist/modules/order/genesis_policy.js +17 -10
  292. package/dist/modules/order/grid.d.ts +144 -36
  293. package/dist/modules/order/grid.js +226 -145
  294. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  295. package/dist/modules/order/grid_reconcile.js +13 -12
  296. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  297. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  298. package/dist/modules/order/index.d.ts +264 -1
  299. package/dist/modules/order/logger.d.ts +46 -19
  300. package/dist/modules/order/logger.js +38 -49
  301. package/dist/modules/order/logger_state.d.ts +4 -4
  302. package/dist/modules/order/manager.d.ts +232 -191
  303. package/dist/modules/order/manager.js +110 -130
  304. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  305. package/dist/modules/order/processed_fill_store.js +16 -27
  306. package/dist/modules/order/strategy.d.ts +21 -13
  307. package/dist/modules/order/strategy.js +5 -6
  308. package/dist/modules/order/sync_engine.d.ts +91 -33
  309. package/dist/modules/order/sync_engine.js +84 -53
  310. package/dist/modules/order/utils/math.d.ts +157 -102
  311. package/dist/modules/order/utils/math.js +77 -38
  312. package/dist/modules/order/utils/order.d.ts +310 -110
  313. package/dist/modules/order/utils/order.js +153 -126
  314. package/dist/modules/order/utils/slot.d.ts +1 -1
  315. package/dist/modules/order/utils/system.d.ts +156 -26
  316. package/dist/modules/order/utils/system.js +103 -71
  317. package/dist/modules/order/utils/validate.d.ts +89 -41
  318. package/dist/modules/order/utils/validate.js +26 -24
  319. package/dist/modules/order/utils/withPoolRef.d.ts +6 -4
  320. package/dist/modules/order/utils/withPoolRef.js +18 -12
  321. package/dist/modules/order/working_grid.d.ts +14 -13
  322. package/dist/modules/paths.d.ts +1 -4
  323. package/dist/modules/paths.js +33 -61
  324. package/dist/modules/process_discovery.d.ts +1 -1
  325. package/dist/modules/process_discovery.js +2 -1
  326. package/dist/modules/runtime.d.ts +7 -3
  327. package/dist/modules/runtime.js +4 -3
  328. package/dist/modules/runtime_settings.d.ts +14 -11
  329. package/dist/modules/runtime_settings.js +30 -24
  330. package/dist/modules/settings_merge.d.ts +29 -3
  331. package/dist/modules/settings_merge.js +56 -78
  332. package/dist/modules/socket_json_client.d.ts +9 -5
  333. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  334. package/dist/modules/storage/browser_adapter.js +7 -30
  335. package/dist/modules/storage/index.d.ts +1 -1
  336. package/dist/modules/storage/node_adapter.d.ts +45 -27
  337. package/dist/modules/storage/node_adapter.js +9 -9
  338. package/dist/modules/storage/types.d.ts +5 -4
  339. package/dist/modules/types.d.ts +1090 -6
  340. package/dist/modules/types.js +4 -1
  341. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  342. package/dist/modules/utils/asset_symbols.js +2 -1
  343. package/dist/modules/utils/errors.d.ts +9 -0
  344. package/dist/modules/utils/errors.js +24 -4
  345. package/dist/modules/utils/time_range.d.ts +1 -12
  346. package/dist/modules/utils/time_range.js +1 -1
  347. package/dist/modules/validate_profiles.js +53 -43
  348. package/dist/modules/version_notice.d.ts +23 -11
  349. package/dist/modules/version_notice.js +6 -4
  350. package/dist/pm2.d.ts +28 -27
  351. package/dist/pm2.js +61 -40
  352. package/dist/scripts/analyze-credit.d.ts +2 -1
  353. package/dist/scripts/analyze-credit.js +23 -24
  354. package/dist/scripts/analyze-git.js +2 -15
  355. package/dist/scripts/analyze-orders.d.ts +77 -9
  356. package/dist/scripts/analyze-orders.js +65 -40
  357. package/dist/scripts/chart_command.d.ts +27 -18
  358. package/dist/scripts/chart_command.js +15 -13
  359. package/dist/scripts/check_any.d.ts +22 -0
  360. package/dist/scripts/check_any.js +158 -0
  361. package/dist/scripts/diagnose-pool-history.js +13 -13
  362. package/dist/scripts/print_grid.js +0 -1
  363. package/dist/scripts/run-tests.js +39 -8
  364. package/dist/scripts/runner.js +1 -1
  365. package/dist/scripts/sync-version.js +0 -10
  366. package/dist/scripts/test-credit-renewal.js +30 -21
  367. package/dist/scripts/update.d.ts +10 -5
  368. package/dist/scripts/update.js +168 -103
  369. package/dist/scripts/update_dist_freshness.js +1 -0
  370. package/dist/scripts/update_layout.d.ts +61 -0
  371. package/dist/scripts/update_layout.js +180 -0
  372. package/dist/scripts/validate_bots.js +2 -1
  373. package/dist/scripts/verify-browser-bundle.js +8 -0
  374. package/dist/unlock.d.ts +28 -3
  375. package/dist/unlock.js +63 -35
  376. package/docs/BITSHARES_ONBOARDING.md +10 -12
  377. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -2
  378. package/docs/COW_INVARIANTS.md +13 -6
  379. package/docs/DEXBOT_COMPARISON.md +8 -8
  380. package/docs/EVOLUTION.md +10 -8
  381. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  382. package/docs/GRID_RECALCULATION.md +4 -2
  383. package/docs/GRID_RECONCILE.md +14 -3
  384. package/docs/LIFECYCLE.md +11 -11
  385. package/docs/MPA_CREDIT_USAGE.md +22 -3
  386. package/docs/README.md +14 -3
  387. package/docs/WORKFLOW.md +1 -0
  388. package/docs/architecture.md +31 -19
  389. package/docs/developer_guide.md +6 -6
  390. package/market_adapter/README.md +12 -5
  391. package/modules/README.md +4 -1
  392. package/package.json +9 -9
  393. package/scripts/README.md +43 -38
  394. package/tests/README.md +25 -10
  395. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  396. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  397. package/scripts/git-viewer.sh +0 -489
  398. package/scripts/postinstall.js +0 -16
@@ -49,7 +49,7 @@
49
49
  * Includes GRID_COMPARISON sub-object for grid divergence metrics
50
50
  *
51
51
  * 6. INCREMENT_BOUNDS - Price increment percentage validation
52
- * MIN_PERCENT, MAX_PERCENT, MIN_FACTOR, MAX_FACTOR
52
+ * MIN_PERCENT, MAX_PERCENT
53
53
  *
54
54
  * FEE CONFIGURATION:
55
55
  * 7. FEE_PARAMETERS - Fee calculation and reservation parameters
@@ -158,6 +158,19 @@ const COW_ACTIONS = Object.freeze({
158
158
  CANCEL: 'cancel',
159
159
  UPDATE: 'update'
160
160
  });
161
+ // Canonical plan/action ORIGIN labels. A plan stamps `origin` so the execution
162
+ // guard can scope a bypass to one producer (never to the whole batch by
163
+ // accident). Kept here so the planner that writes the tag and the guard that
164
+ // reads it can never drift on the spelling.
165
+ // - SPREAD_CORRECTION: gap-repair creates (may close the spread on the
166
+ // market side); LAST-FILL-GUARD bypasses these CREATEs per-action.
167
+ // - GAP_EVACUATION: in-band rotation UPDATEs proven violation-reducing at
168
+ // plan-build (B-stamp) or re-proven live; LAST-FILL-GUARD bypasses only
169
+ // stamped/validated ones.
170
+ const COW_ORIGINS = Object.freeze({
171
+ SPREAD_CORRECTION: 'spread-correction',
172
+ GAP_EVACUATION: 'gap-evacuation'
173
+ });
161
174
  // Defaults applied when instantiating an OrderManager with minimal configuration.
162
175
  // These values are used when a parameter is not explicitly provided in the bot config.
163
176
  let DEFAULT_CONFIG = {
@@ -256,6 +269,11 @@ let TIMING = {
256
269
  RETRY_BACKOFF_CAP_MS: 30000, // 30 seconds - Max exponential backoff delay for connection retries
257
270
  DAEMON_PING_TIMEOUT_MS: 5000, // 5 seconds - Private key daemon ping/healthcheck timeout
258
271
  CREDENTIAL_DAEMON_WATCHDOG_MS: 60000, // 60 seconds - Credential daemon watchdog polling interval
272
+ // Consecutive failed watchdog probes before the daemon is declared down and
273
+ // grid persistence is suspended. 2 tolerates a single transient timeout
274
+ // (daemon busy signing a large batch) without pausing writes; a genuinely
275
+ // dead daemon still trips on the very next probe (~60s later).
276
+ CREDENTIAL_DAEMON_WATCHDOG_FAILURE_THRESHOLD: 2,
259
277
  // Main loop and polling defaults
260
278
  RUN_LOOP_DEFAULT_MS: 300000, // 5 minutes - default open-orders sync cycle delay (env override: OPEN_ORDERS_SYNC_LOOP_MS)
261
279
  OPEN_ORDERS_SYNC_LOOP_ENABLED: false, // Preferred flag: continuous open-order watchdog sync loop (default false — react to fills only)
@@ -364,6 +382,7 @@ let TIMING = {
364
382
  CREDIT_DEAL_CHECK_INTERVAL_MIN: 60, // How often to check credit deal expiry (minutes)
365
383
  CREDIT_DEAL_EXPIRY_THRESHOLD_HOURS: 12, // Proactively renew deals expiring within this window
366
384
  CREDIT_DEAL_SPLIT_MAX_PIECES: 48, // Max pieces per _splitOversizedCreditDeals cycle (~4.8min at 6s/piece)
385
+ CREDIT_REBORROW_MAX_ATTEMPTS: 6, // Drop a deferred reborrow after this many failed build/broadcast attempts
367
386
  // LOCK_REFRESH_MIN_MS: Minimum interval for refreshing order lock leases during long operations.
368
387
  // Prevents lock expiration during extended reconciliations or batch operations.
369
388
  // Default: 250ms (4 refreshes per second minimum during long operations).
@@ -703,11 +722,7 @@ let INCREMENT_BOUNDS = {
703
722
  // Minimum increment percentage allowed (0.01%)
704
723
  MIN_PERCENT: 0.01,
705
724
  // Maximum increment percentage allowed (10%)
706
- MAX_PERCENT: 10,
707
- // Minimum increment as decimal factor (0.01% = 0.0001)
708
- MIN_FACTOR: 0.0001,
709
- // Maximum increment as decimal factor (10% = 0.10)
710
- MAX_FACTOR: 0.10
725
+ MAX_PERCENT: 10
711
726
  };
712
727
  // Fee-related parameters for order operations
713
728
  let FEE_PARAMETERS = {
@@ -883,6 +898,13 @@ let FILL_PROCESSING = {
883
898
  // 0 drains no price updates this cycle. Cancel-class entries are never
884
899
  // budgeted by either knob.
885
900
  CORRECTION_MAX_UPDATES_PER_CYCLE: null,
901
+ // CORRECTION_INTER_OP_DELAY_MS: spacing between successive correction
902
+ // broadcasts (one update/cancel RPC per iteration). Default null inherits
903
+ // TIMING.SYNC_DELAY_MS (500ms) — the production pacing that keeps a burst
904
+ // of corrections from looking like a flood to the node. Exposed as a
905
+ // config knob so tests can drive the drain at 0ms without wall-clock
906
+ // sleeps; 0 is honored verbatim.
907
+ CORRECTION_INTER_OP_DELAY_MS: null,
886
908
  // CORRECTION_QUEUE_WARN_THRESHOLD: emit a rate-limited warn when the
887
909
  // persisted correction queue reaches this size, so a growing backlog is
888
910
  // surfaced instead of silently starving placements.
@@ -1111,7 +1133,7 @@ let MARKET_ADAPTER = {
1111
1133
  // Lower values make the Kalman channel reach maximum influence more easily.
1112
1134
  // Higher values require a stronger move before the Kalman branch reaches full effect.
1113
1135
  // nob: kalS% (Kalman Max Slope %)
1114
- DYNAMIC_WEIGHT_KALMAN_MAX_SLOPE_PCT: 1.11,
1136
+ DYNAMIC_WEIGHT_KALMAN_MAX_SLOPE_PCT: 1.2,
1115
1137
  // DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT: Ignore small AMA moves around flat price action.
1116
1138
  // Higher values create a larger neutral zone and reduce small trend reactions.
1117
1139
  // Lower values make the AMA channel react to smaller moves.
@@ -1148,8 +1170,9 @@ let MARKET_ADAPTER = {
1148
1170
  // confirming bars, filtering short-lived excursions. Enabled by default
1149
1171
  // (was legacy fire-on-first-crossing): measured over the real 1h pools it
1150
1172
  // cuts resets ~35% and whipsaw ~52%→~17%, leaving lag and range-tilt
1151
- // unchanged. Per bot/market override via `amaSlope.persistBars` /
1152
- // `amaSlope.persistEnabled`. See docs/AMA_SLOPE_WINDOW.md.
1173
+ // unchanged. Per bot/market override via `amaSlope.persistBars` (>= 1 gate
1174
+ // length, 0 disables, 1 = legacy) or `amaSlope.persistEnabled: false`
1175
+ // (disables even while the global flag is on). See docs/AMA_SLOPE_WINDOW.md.
1153
1176
  AMA_SLOPE_PERSIST_ENABLED: true,
1154
1177
  // AMA_SLOPE_PERSIST_BARS: consecutive confirming bars required before the
1155
1178
  // slope-delta grid reset (trigger B) fires once enabled. 1 = legacy behavior
@@ -1605,7 +1628,6 @@ let COW_PERFORMANCE = {
1605
1628
  // Structure:
1606
1629
  // NATIVE_CLIENT.CHAIN - Graphene chain parameters
1607
1630
  // NATIVE_CLIENT.OPERATIONS - Operation type IDs
1608
- // NATIVE_CLIENT.OBJECT_TYPES - Object space/type IDs
1609
1631
  // NATIVE_CLIENT.TRANSACTION - Transaction builder limits
1610
1632
  // NATIVE_CLIENT.TRANSPORT - WebSocket transport tuning
1611
1633
  // NATIVE_CLIENT.SUBSCRIPTIONS - Fill-detection subscription settings
@@ -1613,7 +1635,7 @@ let COW_PERFORMANCE = {
1613
1635
  // NATIVE_CLIENT.ECC - Cryptographic constants (reference only)
1614
1636
  //
1615
1637
  // Source files:
1616
- // modules/bitshares-native/serial/chain_constants.ts (CHAIN, OPERATIONS, OBJECT_TYPES)
1638
+ // modules/bitshares-native/serial/chain_constants.ts (CHAIN, OPERATIONS)
1617
1639
  // modules/bitshares-native/tx/builder.ts (TRANSACTION)
1618
1640
  // modules/bitshares-native/transport.ts (TRANSPORT)
1619
1641
  // modules/bitshares-native/subscriptions.ts (SUBSCRIPTIONS)
@@ -1664,36 +1686,6 @@ let NATIVE_CLIENT = {
1664
1686
  LIQUIDITY_POOL_EXCHANGE: 63,
1665
1687
  },
1666
1688
  // -------------------------------------------------------------------------
1667
- // OBJECT_TYPES — Graphene object space/type IDs
1668
- // -------------------------------------------------------------------------
1669
- // Space 1 (protocol), used for blockchain entity identification.
1670
- // Object IDs follow the format "space.type.instance" (e.g. "1.2.12345" = account).
1671
- OBJECT_TYPES: {
1672
- NULL: 0,
1673
- BASE: 1,
1674
- ACCOUNT: 2,
1675
- ASSET: 3,
1676
- FORCE_SETTLEMENT: 4,
1677
- COMMITTEE_MEMBER: 5,
1678
- WITNESS: 6,
1679
- LIMIT_ORDER: 7,
1680
- CALL_ORDER: 8,
1681
- CUSTOM: 9,
1682
- PROPOSAL: 10,
1683
- OPERATION_HISTORY: 11,
1684
- WITHDRAW_PERMISSION: 12,
1685
- VESTING_BALANCE: 13,
1686
- WORKER: 14,
1687
- BALANCE: 15,
1688
- HTLC: 16,
1689
- CUSTOM_AUTHORITY: 17,
1690
- TICKET: 18,
1691
- LIQUIDITY_POOL: 19,
1692
- SAMET_FUND: 20,
1693
- CREDIT_OFFER: 21,
1694
- CREDIT_DEAL: 22,
1695
- },
1696
- // -------------------------------------------------------------------------
1697
1689
  // TRANSACTION — Transaction builder limits (tx/builder.js)
1698
1690
  // -------------------------------------------------------------------------
1699
1691
  TRANSACTION: {
@@ -1761,11 +1753,6 @@ let NATIVE_CLIENT = {
1761
1753
  // node failure. 1000 = normal closure, 1001 = going away (server
1762
1754
  // shutdown/deploy). Any other code, or wasClean === false, is abnormal.
1763
1755
  BENIGN_CLOSE_CODES: [1000, 1001],
1764
- // NOTE: These constants are informational but not imported by transport.ts
1765
- // Reconnection backoff parameters (ms).
1766
- // Reconnect delay = min(base × 2^attempt + random(0..1000), max).
1767
- RECONNECT_BASE_MS: 1000,
1768
- RECONNECT_MAX_MS: 30000,
1769
1756
  },
1770
1757
  // -------------------------------------------------------------------------
1771
1758
  // SUBSCRIPTIONS — Fill-detection subscription settings (subscriptions.js)
@@ -2002,6 +1989,7 @@ Object.freeze(ORDER_TYPES);
2002
1989
  Object.freeze(ORDER_STATES);
2003
1990
  Object.freeze(REBALANCE_STATES);
2004
1991
  Object.freeze(COW_ACTIONS);
1992
+ Object.freeze(COW_ORIGINS);
2005
1993
  Object.freeze(TIMING);
2006
1994
  Object.freeze(GRID_LIMITS);
2007
1995
  Object.freeze(GRID_LIMITS.GRID_COMPARISON);
@@ -2021,7 +2009,6 @@ Object.freeze(COW_PERFORMANCE);
2021
2009
  Object.freeze(LOGGING_CONFIG);
2022
2010
  Object.freeze(NATIVE_CLIENT.CHAIN);
2023
2011
  Object.freeze(NATIVE_CLIENT.OPERATIONS);
2024
- Object.freeze(NATIVE_CLIENT.OBJECT_TYPES);
2025
2012
  Object.freeze(NATIVE_CLIENT.TRANSACTION);
2026
2013
  Object.freeze(NATIVE_CLIENT.TRANSPORT);
2027
2014
  Object.freeze(NATIVE_CLIENT.SUBSCRIPTIONS);
@@ -2037,5 +2024,5 @@ Object.freeze(MARKET_ADAPTER.AMAS.AMA4);
2037
2024
  Object.freeze(MARKET_ADAPTER.AMAS);
2038
2025
  Object.freeze(MARKET_ADAPTER);
2039
2026
  Object.freeze(CREDENTIAL_PROMPTS);
2040
- export { ORDER_TYPES, ORDER_STATES, REBALANCE_STATES, COW_ACTIONS, DEFAULT_CONFIG, TIMING, RANGE_QUALITY, GRID_LIMITS, LOG_LEVEL, LOGGING_CONFIG, INCREMENT_BOUNDS, FEE_PARAMETERS, CR_ZONES, DEFAULT_TARGET_CR, API_LIMITS, FILL_PROCESSING, MAINTENANCE, NODE_MANAGEMENT, PIPELINE_TIMING, UPDATER, LAUNCHER, COW_PERFORMANCE, NATIVE_CLIENT, MARKET_ADAPTER, BUILD_DIR, BTS_PRECISION, DAEMON_ERRORS, DAEMON_CODES, CREDENTIAL_PROMPTS, buildDefaultGeneralSettings };
2027
+ export { ORDER_TYPES, ORDER_STATES, REBALANCE_STATES, COW_ACTIONS, COW_ORIGINS, DEFAULT_CONFIG, TIMING, RANGE_QUALITY, GRID_LIMITS, LOG_LEVEL, LOGGING_CONFIG, INCREMENT_BOUNDS, FEE_PARAMETERS, CR_ZONES, DEFAULT_TARGET_CR, API_LIMITS, FILL_PROCESSING, MAINTENANCE, NODE_MANAGEMENT, PIPELINE_TIMING, UPDATER, LAUNCHER, COW_PERFORMANCE, NATIVE_CLIENT, MARKET_ADAPTER, BUILD_DIR, BTS_PRECISION, DAEMON_ERRORS, DAEMON_CODES, CREDENTIAL_PROMPTS, buildDefaultGeneralSettings };
2041
2028
  //# sourceMappingURL=constants.js.map
@@ -1,3 +1,4 @@
1
+ import { positiveOrNull } from './order/format.js';
1
2
  interface CrPolicy {
2
3
  minCollateralRatio?: number;
3
4
  maxCollateralRatio?: number;
@@ -25,10 +26,47 @@ interface CollateralFallbackPlanOptions {
25
26
  maxCollateralAmount?: number | string;
26
27
  collateralLimitReferenceAmount?: number;
27
28
  }
28
- declare function positiveOrNull(value: unknown): number | null;
29
29
  declare function resolveMinCollateralIncreaseThreshold(value: unknown, referenceAmount?: unknown): number | null;
30
30
  declare function resolveTargetCollateralRatio(policy?: CrPolicy): number | null;
31
- declare function buildDebtFirstCrPlan({ currentCollateralAmount, currentDebtAmount, feedPrice, minCollateralRatio, maxCollateralRatio, targetCollateralRatio, maxBorrowAmount, maxBorrowAmountPerOperation, maxCollateralAmount, collateralLimitReferenceAmount, minCollateralIncreaseThreshold, debtOnly, }?: DebtFirstCrPlanOptions): any;
32
- declare function buildCollateralFallbackPlan({ currentCollateralAmount, currentDebtAmount, feedPrice, targetCollateralRatio, maxCollateralAmount, collateralLimitReferenceAmount, }?: CollateralFallbackPlanOptions): any;
31
+ declare function buildDebtFirstCrPlan({ currentCollateralAmount, currentDebtAmount, feedPrice, minCollateralRatio, maxCollateralRatio, targetCollateralRatio, maxBorrowAmount, maxBorrowAmountPerOperation, maxCollateralAmount, collateralLimitReferenceAmount, minCollateralIncreaseThreshold, debtOnly, }?: DebtFirstCrPlanOptions): {
32
+ blocked: boolean;
33
+ reason: string;
34
+ action?: undefined;
35
+ fallbackAction?: undefined;
36
+ targetCollateralRatio?: undefined;
37
+ currentCollateralRatio?: undefined;
38
+ currentDebtAmount?: undefined;
39
+ currentCollateralAmount?: undefined;
40
+ feedPrice?: undefined;
41
+ debtDelta?: undefined;
42
+ collateralDelta?: undefined;
43
+ needsGridReset?: undefined;
44
+ resetReason?: undefined;
45
+ } | {
46
+ action: string;
47
+ fallbackAction: string | null;
48
+ targetCollateralRatio: number;
49
+ currentCollateralRatio: number;
50
+ currentDebtAmount: number | undefined;
51
+ currentCollateralAmount: number | undefined;
52
+ feedPrice: number | undefined;
53
+ debtDelta: number;
54
+ collateralDelta: number;
55
+ needsGridReset: boolean;
56
+ resetReason: string;
57
+ blocked?: undefined;
58
+ reason?: undefined;
59
+ } | null;
60
+ declare function buildCollateralFallbackPlan({ currentCollateralAmount, currentDebtAmount, feedPrice, targetCollateralRatio, maxCollateralAmount, collateralLimitReferenceAmount, }?: CollateralFallbackPlanOptions): {
61
+ action: string;
62
+ targetCollateralRatio: number;
63
+ currentCollateralRatio: number | null;
64
+ currentDebtAmount: number | undefined;
65
+ currentCollateralAmount: number | undefined;
66
+ feedPrice: number | undefined;
67
+ collateralDelta: number;
68
+ needsGridReset: boolean;
69
+ resetReason: string;
70
+ } | null;
33
71
  export { buildCollateralFallbackPlan, buildDebtFirstCrPlan, positiveOrNull, resolveMinCollateralIncreaseThreshold, resolveTargetCollateralRatio };
34
72
  //# sourceMappingURL=cr_planner.d.ts.map
@@ -1,10 +1,6 @@
1
1
  'use strict';
2
- import { toFiniteNumber } from './order/format.js';
2
+ import { positiveOrNull } from './order/format.js';
3
3
  import { resolveConfigValue, isPercentageString, roundToDecimals } from './order/utils/math.js';
4
- function positiveOrNull(value) {
5
- const num = toFiniteNumber(value, undefined);
6
- return Number.isFinite(num) && num > 0 ? num : null;
7
- }
8
4
  function resolveCollateralLimit(value, referenceAmount) {
9
5
  const resolved = resolveConfigValue(value, referenceAmount);
10
6
  if (!Number.isFinite(resolved))
@@ -7,17 +7,77 @@
7
7
  * Default-deny on errors: validation failures, executable timeouts, etc.
8
8
  */
9
9
  declare const POLICY_DENIED_PREFIX = "POLICY_DENIED: ";
10
+ interface AmountRef {
11
+ asset_id?: string;
12
+ amount?: number;
13
+ }
14
+ interface OpData {
15
+ to?: unknown;
16
+ amount?: AmountRef;
17
+ amount_to_sell?: AmountRef;
18
+ min_to_receive?: AmountRef;
19
+ delta_amount_to_sell?: AmountRef;
20
+ delta_collateral?: AmountRef;
21
+ delta_debt?: AmountRef;
22
+ new_price?: {
23
+ base?: AmountRef;
24
+ quote?: AmountRef;
25
+ };
26
+ fill_or_kill?: unknown;
27
+ extensions?: {
28
+ target_collateral_ratio?: unknown;
29
+ };
30
+ offer_id?: unknown;
31
+ collateral?: AmountRef;
32
+ borrow_amount?: AmountRef;
33
+ repay_amount?: AmountRef;
34
+ credit_fee?: AmountRef;
35
+ max_fee_rate?: unknown;
36
+ min_duration_seconds?: unknown;
37
+ auto_repay?: unknown;
38
+ pool?: unknown;
39
+ [key: string]: unknown;
40
+ }
41
+ interface PolicyOperation {
42
+ op_name?: string;
43
+ op_data?: OpData;
44
+ [key: string]: unknown;
45
+ }
10
46
  interface PolicyContext {
11
47
  accountName: string;
12
48
  requestType: string;
13
49
  sessionId: string | null;
14
50
  timestamp: string;
15
- operations: any[];
51
+ operations: PolicyOperation[];
52
+ }
53
+ interface PolicyLayer {
54
+ sessionTtlMs?: number;
55
+ maxOpsPerBatch?: number;
56
+ allowedAssetIds?: string[] | null;
57
+ executable?: string | null;
58
+ botHmacSecret?: string;
59
+ allowedOps?: Record<string, Record<string, unknown>> | null;
60
+ [key: string]: unknown;
16
61
  }
17
62
  interface PolicyConfig {
18
63
  sessionTtlMs?: number;
19
- default?: Record<string, any>;
20
- accounts?: Record<string, Record<string, any>>;
64
+ default?: PolicyLayer;
65
+ accounts?: Record<string, PolicyLayer>;
66
+ }
67
+ interface MergedPolicy {
68
+ allowedOps: Record<string, Record<string, unknown>>;
69
+ maxOpsPerBatch?: number;
70
+ allowedAssetIds?: string[] | null;
71
+ executable?: string | null;
72
+ [key: string]: unknown;
73
+ }
74
+ interface PolicyRequest {
75
+ accountName: string;
76
+ type: string;
77
+ sessionId?: string | null;
78
+ operations?: PolicyOperation[];
79
+ hmac?: unknown;
80
+ [key: string]: unknown;
21
81
  }
22
82
  declare const BUILTIN_DEFAULT_POLICY: Readonly<{
23
83
  allowedOps: Readonly<{
@@ -88,20 +148,20 @@ declare function loadRequiredPolicyConfig(filePath: string): PolicyConfig;
88
148
  /**
89
149
  * Validate raw policy config. Returns { valid: boolean, errors: string[] }.
90
150
  */
91
- declare function validatePolicyConfig(raw: any): {
151
+ declare function validatePolicyConfig(raw: unknown): {
92
152
  valid: boolean;
93
153
  errors: string[];
94
154
  };
95
- declare function resolveAccountPolicy(config: any, accountName: string): any;
155
+ declare function resolveAccountPolicy(config: PolicyConfig | null, accountName: string): MergedPolicy;
96
156
  /**
97
157
  * Build the PolicyContext passed to evaluatePolicy and to executable hooks.
98
158
  */
99
- declare function buildPolicyContext(request: any): PolicyContext;
159
+ declare function buildPolicyContext(request: PolicyRequest): PolicyContext;
100
160
  /**
101
161
  * Evaluate a policy against a context. AND semantics: short-circuit on first denial.
102
162
  * Returns Promise<{ allow: boolean, reason: string|null, policyId: string|null }>
103
163
  */
104
- declare function evaluatePolicy(policy: any, context: PolicyContext): Promise<{
164
+ declare function evaluatePolicy(policy: MergedPolicy, context: PolicyContext): Promise<{
105
165
  allow: boolean;
106
166
  reason: string | null;
107
167
  policyId: string | null;
@@ -136,7 +196,7 @@ declare function loadBotHmacSecret(accountName: string, policyConfigPath: string
136
196
  * @param {object|null} policyConfig - Loaded daemon-policies.json content
137
197
  * @returns {{ valid: boolean, reason: string|null }}
138
198
  */
139
- declare function verifySourceHmac(request: any, policyConfig: any): {
199
+ declare function verifySourceHmac(request: PolicyRequest, policyConfig: PolicyConfig | null): {
140
200
  valid: boolean;
141
201
  reason: string | null;
142
202
  };
@@ -86,7 +86,7 @@ async function resolveAssetRefToId(assetRef) {
86
86
  return result;
87
87
  }
88
88
  }
89
- catch (_) {
89
+ catch {
90
90
  // fall through — native client may not be connected yet
91
91
  }
92
92
  // Don't cache null from external resolver; the native client may not
@@ -101,7 +101,7 @@ async function resolveAssetRefToId(assetRef) {
101
101
  resolvedId = asset?.id ? String(asset.id) : null;
102
102
  }
103
103
  }
104
- catch (_) {
104
+ catch {
105
105
  resolvedId = null;
106
106
  }
107
107
  if (resolvedId)
@@ -222,7 +222,7 @@ function ensurePolicyConfig(filePath) {
222
222
  function loadPolicyConfig(filePath, options = {}) {
223
223
  const forceReload = options.forceReload || false;
224
224
  if (!forceReload && policyCache.has(filePath)) {
225
- return policyCache.get(filePath);
225
+ return policyCache.get(filePath) ?? null;
226
226
  }
227
227
  const detailed = readPolicyConfigDetailed(filePath);
228
228
  if (detailed.status !== 'ok') {
@@ -399,31 +399,32 @@ function validatePolicyConfig(raw) {
399
399
  errors.push('root must be an object');
400
400
  return { valid: false, errors };
401
401
  }
402
+ const cfg = raw;
402
403
  // sessionTtlMs: optional positive integer
403
- if (raw.sessionTtlMs !== undefined) {
404
- if (typeof raw.sessionTtlMs !== 'number' || raw.sessionTtlMs <= 0) {
404
+ if (cfg.sessionTtlMs !== undefined) {
405
+ if (typeof cfg.sessionTtlMs !== 'number' || cfg.sessionTtlMs <= 0) {
405
406
  errors.push('sessionTtlMs must be a positive integer');
406
407
  }
407
408
  }
408
409
  // default: optional policy object
409
- if (raw.default !== undefined) {
410
- if (typeof raw.default !== 'object' || raw.default === null) {
410
+ if (cfg.default !== undefined) {
411
+ if (typeof cfg.default !== 'object' || cfg.default === null) {
411
412
  errors.push('default must be an object');
412
413
  }
413
414
  else {
414
- const { valid: validDefault, errors: defaultErrors } = validatePolicyObject(raw.default);
415
+ const { valid: validDefault, errors: defaultErrors } = validatePolicyObject(cfg.default);
415
416
  if (!validDefault) {
416
417
  errors.push(`default: ${defaultErrors.join('; ')}`);
417
418
  }
418
419
  }
419
420
  }
420
421
  // accounts: optional object of policies
421
- if (raw.accounts !== undefined) {
422
- if (typeof raw.accounts !== 'object' || Array.isArray(raw.accounts)) {
422
+ if (cfg.accounts !== undefined) {
423
+ if (typeof cfg.accounts !== 'object' || Array.isArray(cfg.accounts)) {
423
424
  errors.push('accounts must be an object');
424
425
  }
425
426
  else {
426
- for (const [accountName, policy] of Object.entries(raw.accounts)) {
427
+ for (const [accountName, policy] of Object.entries(cfg.accounts)) {
427
428
  if (typeof policy !== 'object' || policy === null) {
428
429
  errors.push(`accounts.${accountName} must be an object`);
429
430
  }
@@ -441,8 +442,9 @@ function validatePolicyConfig(raw) {
441
442
  /**
442
443
  * Validate a single policy object (used by both default and per-account policies).
443
444
  */
444
- function validatePolicyObject(policy) {
445
+ function validatePolicyObject(policyInput) {
445
446
  const errors = [];
447
+ const policy = (policyInput && typeof policyInput === 'object' ? policyInput : {});
446
448
  // maxOpsPerBatch: must be positive integer
447
449
  if (policy.maxOpsPerBatch !== undefined) {
448
450
  if (typeof policy.maxOpsPerBatch !== 'number' || policy.maxOpsPerBatch <= 0) {
@@ -584,10 +586,11 @@ function deriveDebtPolicyConstraints(accountName) {
584
586
  function mergePolicyLayer(base, layer) {
585
587
  if (!layer || typeof layer !== 'object')
586
588
  return base;
587
- const merged = { ...base, ...layer };
588
- if (layer.allowedOps && typeof layer.allowedOps === 'object') {
589
- const allowedOps = { ...(base.allowedOps || {}) };
590
- for (const [opName, constraints] of Object.entries(layer.allowedOps)) {
589
+ const l = layer;
590
+ const merged = { ...base, ...l, allowedOps: { ...base.allowedOps } };
591
+ if (l.allowedOps && typeof l.allowedOps === 'object') {
592
+ const allowedOps = { ...base.allowedOps };
593
+ for (const [opName, constraints] of Object.entries(l.allowedOps)) {
591
594
  if (opName === '__proto__' || opName === 'constructor' || opName === 'prototype')
592
595
  continue;
593
596
  allowedOps[opName] = { ...(allowedOps[opName] || {}), ...((constraints && typeof constraints === 'object') ? constraints : {}) };
@@ -650,11 +653,13 @@ function denyNotInList(opName, word, id, listName, list, requirePresent) {
650
653
  return null;
651
654
  }
652
655
  function denyBoundExceeded(opName, label, compareValue, shownValue, boundLabel, bound, opts = {}) {
653
- if (bound == null)
656
+ if (bound == null || compareValue == null)
654
657
  return null;
655
- if (compareValue == null || !Number.isFinite(compareValue))
658
+ const cmp = Number(compareValue);
659
+ const bnd = Number(bound);
660
+ if (!Number.isFinite(cmp) || !Number.isFinite(bnd))
656
661
  return null;
657
- const over = opts.lower ? compareValue < bound : compareValue > bound;
662
+ const over = opts.lower ? cmp < bnd : cmp > bnd;
658
663
  if (!over)
659
664
  return null;
660
665
  const verb = opts.verb ?? (opts.lower ? 'below' : 'exceeds');
@@ -663,7 +668,7 @@ function denyBoundExceeded(opName, label, compareValue, shownValue, boundLabel,
663
668
  async function denyAssetRefMismatch(opName, word, assetId, refs, refLabel, opts = {}) {
664
669
  if (!opts.active)
665
670
  return null;
666
- const resolved = await resolveConfiguredAssetRefs(refs, refLabel);
671
+ const resolved = await resolveConfiguredAssetRefs(Array.isArray(refs) ? refs.map((r) => String(r)) : [], refLabel);
667
672
  if (!resolved.ok)
668
673
  return asDeny(`${opName}: ${resolved.reason}`);
669
674
  if (assetId && resolved.values && !resolved.values.includes(String(assetId))) {
@@ -722,7 +727,7 @@ async function evaluateOpConstraints(opName, opData, constraints) {
722
727
  if (receiveDenied)
723
728
  return receiveDenied;
724
729
  // maxDeltaSellAmount (abs value)
725
- const maxDeltaSellDenied = denyBoundExceeded('limit_order_update', '|delta|', Math.abs(d.delta_amount_to_sell && d.delta_amount_to_sell.amount), Math.abs(d.delta_amount_to_sell && d.delta_amount_to_sell.amount), 'maxDeltaSellAmount', constraints.maxDeltaSellAmount);
730
+ const maxDeltaSellDenied = denyBoundExceeded('limit_order_update', '|delta|', Math.abs(Number(d.delta_amount_to_sell && d.delta_amount_to_sell.amount)), Math.abs(Number(d.delta_amount_to_sell && d.delta_amount_to_sell.amount)), 'maxDeltaSellAmount', constraints.maxDeltaSellAmount);
726
731
  if (maxDeltaSellDenied)
727
732
  return maxDeltaSellDenied;
728
733
  }
@@ -741,14 +746,14 @@ async function evaluateOpConstraints(opName, opData, constraints) {
741
746
  if (allowedCollateralDenied)
742
747
  return allowedCollateralDenied;
743
748
  // maxDeltaCollateral
744
- const maxDeltaCollateralDenied = denyBoundExceeded('call_order_update', '|delta_collateral|', Math.abs(d.delta_collateral && d.delta_collateral.amount), Math.abs(d.delta_collateral && d.delta_collateral.amount), 'maxDeltaCollateral', constraints.maxDeltaCollateral);
749
+ const maxDeltaCollateralDenied = denyBoundExceeded('call_order_update', '|delta_collateral|', Math.abs(Number(d.delta_collateral && d.delta_collateral.amount)), Math.abs(Number(d.delta_collateral && d.delta_collateral.amount)), 'maxDeltaCollateral', constraints.maxDeltaCollateral);
745
750
  if (maxDeltaCollateralDenied)
746
751
  return maxDeltaCollateralDenied;
747
752
  // maxDeltaDebt
748
- const maxDeltaDebtDenied = denyBoundExceeded('call_order_update', '|delta_debt|', Math.abs(d.delta_debt && d.delta_debt.amount), Math.abs(d.delta_debt && d.delta_debt.amount), 'maxDeltaDebt', constraints.maxDeltaDebt);
753
+ const maxDeltaDebtDenied = denyBoundExceeded('call_order_update', '|delta_debt|', Math.abs(Number(d.delta_debt && d.delta_debt.amount)), Math.abs(Number(d.delta_debt && d.delta_debt.amount)), 'maxDeltaDebt', constraints.maxDeltaDebt);
749
754
  if (maxDeltaDebtDenied)
750
755
  return maxDeltaDebtDenied;
751
- const targetCollateralRatio = d.extensions && d.extensions.target_collateral_ratio != null ? normalizeGrapheneCollateralRatio(d.extensions.target_collateral_ratio) : NaN;
756
+ const targetCollateralRatio = d.extensions && d.extensions.target_collateral_ratio != null ? normalizeGrapheneCollateralRatio(Number(d.extensions.target_collateral_ratio)) : NaN;
752
757
  const minRatioDenied = denyBoundExceeded('call_order_update', 'target_collateral_ratio', targetCollateralRatio, targetCollateralRatio, 'minCollateralRatio', constraints.minCollateralRatio, { lower: true });
753
758
  if (minRatioDenied)
754
759
  return minRatioDenied;
@@ -834,8 +839,8 @@ async function evaluatePolicy(policy, context) {
834
839
  };
835
840
  }
836
841
  // Get per-op constraints and evaluate
837
- const constraints = policy.allowedOps[opName];
838
- const result = await evaluateOpConstraints(opName, op.op_data, constraints);
842
+ const constraints = policy.allowedOps[String(opName)];
843
+ const result = await evaluateOpConstraints(String(opName), op.op_data, constraints);
839
844
  if (!result.allow) {
840
845
  return result;
841
846
  }
@@ -1013,7 +1018,7 @@ function evaluateExecutable(exePath, context) {
1013
1018
  }
1014
1019
  resolve({
1015
1020
  allow: result.allow,
1016
- reason: result.allow ? null : (result.reason || 'denied by executable'),
1021
+ reason: result.allow ? null : (typeof result.reason === 'string' ? result.reason : 'denied by executable'),
1017
1022
  });
1018
1023
  }
1019
1024
  catch (error) {
@@ -1118,17 +1123,18 @@ function loadBotHmacSecret(accountName, policyConfigPath, options = {}) {
1118
1123
  }
1119
1124
  }
1120
1125
  catch (e) {
1121
- if (e && e.code === 'ENOENT') {
1126
+ const err = e;
1127
+ if (err && err.code === 'ENOENT') {
1122
1128
  info(`[policy] Ready file not present; daemon not running, SIGHUP skipped`);
1123
1129
  }
1124
1130
  else if (e instanceof SyntaxError) {
1125
1131
  warn(`[policy] Ready file is malformed JSON (${getErrorMessage(e)}); SIGHUP skipped, fs.watch will pick up the change`);
1126
1132
  }
1127
- else if (e && (e.code === 'ESRCH' || e.code === 'EPERM')) {
1128
- warn(`[policy] SIGHUP to daemon failed (${e.code}: ${getErrorMessage(e)}); fs.watch will pick up the change`);
1133
+ else if (err && (err.code === 'ESRCH' || err.code === 'EPERM')) {
1134
+ warn(`[policy] SIGHUP to daemon failed (${err.code}: ${getErrorMessage(e)}); fs.watch will pick up the change`);
1129
1135
  }
1130
1136
  else {
1131
- warn(`[policy] Unexpected error signalling daemon (${e && getErrorMessage(e)}); fs.watch will pick up the change`);
1137
+ warn(`[policy] Unexpected error signalling daemon (${getErrorMessage(e)}); fs.watch will pick up the change`);
1132
1138
  }
1133
1139
  }
1134
1140
  secret = newSecret;
@@ -11,7 +11,7 @@ interface BuildSessionCacheOptions {
11
11
  }
12
12
  interface LoadDaemonKeyOptions {
13
13
  chainKeys?: typeof chainKeys;
14
- chainClient?: any;
14
+ chainClient?: unknown;
15
15
  }
16
16
  interface SessionState {
17
17
  vaultSecret?: string;
@@ -27,6 +27,6 @@ declare function buildSessionAccountCache(accountsData: AccountsData, masterSecr
27
27
  vaultKeyHex: string;
28
28
  };
29
29
  };
30
- declare function loadDaemonPrivateKey(accountName: string, sessionState: SessionState, options?: LoadDaemonKeyOptions): Promise<any>;
30
+ declare function loadDaemonPrivateKey(accountName: string, sessionState: SessionState, options?: LoadDaemonKeyOptions): Promise<string>;
31
31
  export { buildSessionAccountCache, loadDaemonPrivateKey };
32
32
  //# sourceMappingURL=credential_session_cache.d.ts.map
@@ -1,9 +1,35 @@
1
+ /**
2
+ * modules/credit_pricing.ts — Canonical credit-pricing math (single source of truth).
3
+ *
4
+ * Pure functions only: no I/O, browser-safe; imports only the dependency-free
5
+ * order/format number helpers. Both the live
6
+ * credit runtime (modules/credit_runtime.ts) and the offline analyzer
7
+ * (scripts/analyze-credit.ts) delegate to these helpers so offer-price
8
+ * orientation, conversion rates, and collateral-ratio math cannot drift
9
+ * apart between surfaces.
10
+ *
11
+ * Conventions (mirror the chain's credit_offer_object price layout):
12
+ * - A 'core' price has base == debt asset / quote == collateral asset and
13
+ * the conversion rate (debt per 1 collateral) is base / quote.
14
+ * - A 'legacy-reversed' price has base == collateral / quote == debt and
15
+ * the rate is quote / base. Unknown layouts default to 'core'.
16
+ * - Credit CR = collateralValueInDebt / debtAmount, where
17
+ * collateralValueInDebt = collateralAmount * conversionRate.
18
+ */
19
+ interface PriceLeg {
20
+ amount?: unknown;
21
+ asset_id?: unknown;
22
+ }
23
+ interface OfferPrice {
24
+ base?: PriceLeg;
25
+ quote?: PriceLeg;
26
+ }
1
27
  /**
2
28
  * Tolerantly normalize an offer's acceptable_collateral map, which arrives
3
29
  * in different shapes depending on the API path (Map, [[id, price]] pairs,
4
30
  * [{key, value}] entries, or a plain {assetId: price} object).
5
31
  */
6
- declare function normalizeCollateralMap(raw: unknown): Map<string, any>;
32
+ declare function normalizeCollateralMap(raw: unknown): Map<string, OfferPrice>;
7
33
  declare function creditPriceOrientation(baseAssetId: string, quoteAssetId: string, debtAssetId: string, collateralAssetId: string): 'core' | 'legacy-reversed';
8
34
  /**
9
35
  * Extract the conversion rate (debt asset per 1 collateral unit) for a
@@ -20,17 +46,25 @@ declare function extractOfferConversionRate(offerCollateral: unknown, collateral
20
46
  * Value collateral (raw int) in debt-asset units via an offer price.
21
47
  * Pure offer-math leg of the runtime's pool-aware valuation.
22
48
  */
23
- declare function collateralValueFromOfferPrice(collateralAmountInt: unknown, collateralPrecision: unknown, collateralPriceOrMap: any, debtAssetId: string, collateralAssetId: string, precisionOf: (assetId: string) => number | null): number | null;
49
+ declare function collateralValueFromOfferPrice(collateralAmountInt: unknown, collateralPrecision: unknown, collateralPriceOrMap: unknown, debtAssetId: string, collateralAssetId: string, precisionOf: (assetId: string) => number | null): number | null;
24
50
  /**
25
51
  * Minimum raw collateral required to borrow a raw debt amount at a price.
26
52
  * Integer ceil so the borrow is never under-collateralized by rounding.
27
53
  */
28
- declare function requiredCollateralForBorrow(borrowAmountInt: unknown, collateralPrice: any, debtAssetId?: string | null, collateralAssetId?: string | null): number | null;
54
+ declare function requiredCollateralForBorrow(borrowAmountInt: unknown, collateralPrice: OfferPrice | null | undefined, debtAssetId?: string | null, collateralAssetId?: string | null): number | null;
29
55
  /**
30
56
  * Raw debt yielded by raw collateral at a price. Integer floor so the
31
57
  * borrow never exceeds what the collateral covers.
32
58
  */
33
- declare function borrowAmountForCollateral(collateralAmountInt: unknown, collateralPrice: any, debtAssetId?: string | null, collateralAssetId?: string | null): number | null;
59
+ declare function borrowAmountForCollateral(collateralAmountInt: unknown, collateralPrice: OfferPrice | null | undefined, debtAssetId?: string | null, collateralAssetId?: string | null): number | null;
60
+ /**
61
+ * Raw debt yielded by a raw collateral budget, never exceeding the requested
62
+ * raw debt. Returns `requestedBorrowInt` when no budget is supplied or the
63
+ * budget already covers it; `null` when a supplied budget cannot support any
64
+ * borrow at the offer price (caller should back off rather than emit a doomed
65
+ * accept op).
66
+ */
67
+ declare function capBorrowToCollateral(requestedBorrowInt: unknown, availableCollateralInt: unknown, collateralPrice: OfferPrice | null | undefined, debtAssetId?: string | null, collateralAssetId?: string | null): number | null;
34
68
  /**
35
69
  * Per-deal CR from floats plus a conversion rate:
36
70
  * (collateralFloat * rate) / debtFloat.
@@ -51,11 +85,14 @@ declare function averageCollateralRatio(entries: Array<{
51
85
  * Returns 0 for missing/non-positive inputs (matches runtime gating, where
52
86
  * a zero daily rate never exceeds maxFeeRatePerDay).
53
87
  */
54
- declare function dailyOfferFeeRate(offer: any, feeDenom: unknown): number;
88
+ declare function dailyOfferFeeRate(offer: {
89
+ fee_rate?: unknown;
90
+ max_duration_seconds?: unknown;
91
+ } | null | undefined, feeDenom: unknown): number;
55
92
  /**
56
93
  * Credit-deal repay fee in raw debt units, rounded up (Graphene ceil):
57
94
  * (repay * feeRate + denom - 1) / denom. Zero when nothing is owed.
58
95
  */
59
96
  declare function creditDealFee(repayAmountInt: unknown, feeRate: unknown, feeDenom: unknown): number;
60
- export { normalizeCollateralMap, creditPriceOrientation, extractOfferConversionRate, collateralValueFromOfferPrice, requiredCollateralForBorrow, borrowAmountForCollateral, creditDealCollateralRatio, averageCollateralRatio, dailyOfferFeeRate, creditDealFee, };
97
+ export { normalizeCollateralMap, creditPriceOrientation, extractOfferConversionRate, collateralValueFromOfferPrice, requiredCollateralForBorrow, borrowAmountForCollateral, capBorrowToCollateral, creditDealCollateralRatio, averageCollateralRatio, dailyOfferFeeRate, creditDealFee, };
61
98
  //# sourceMappingURL=credit_pricing.d.ts.map