dexbot 1.6.10 → 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.
Files changed (365) hide show
  1. package/CHANGELOG.md +50 -3
  2. package/README.md +3 -1
  3. package/analysis/README.md +51 -11
  4. package/analysis/bot_fitting/README.md +12 -0
  5. package/analysis/tradingview/README.md +3 -3
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +11 -37
  7. package/analysis/trend_detection/README.md +31 -0
  8. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  9. package/claw/modules/chain_broadcast.ts +7 -1
  10. package/claw/modules/claw_launcher.ts +1 -1
  11. package/claw/modules/launcher_mode_detector.ts +9 -2
  12. package/claw/package.json +1 -1
  13. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  14. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  15. package/dist/analysis/account_resolver.d.ts +1 -1
  16. package/dist/analysis/account_resolver.js +15 -2
  17. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  18. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -7
  19. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  20. package/dist/analysis/ama_fitting/fetch_lp_candles.js +4 -4
  21. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +20 -4
  22. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +9 -6
  23. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +16 -12
  24. package/dist/analysis/analyze_args.d.ts +31 -0
  25. package/dist/analysis/analyze_args.js +41 -0
  26. package/dist/analysis/analyze_dynamic_weight.js +7 -20
  27. package/dist/analysis/analyze_kalman.js +7 -17
  28. package/dist/analysis/analyze_regime.js +7 -17
  29. package/dist/analysis/analyze_regime_windows.js +8 -18
  30. package/dist/analysis/analyze_risk_profile.js +8 -18
  31. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  32. package/dist/analysis/analyze_volatility.js +7 -17
  33. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +220 -12
  34. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +55 -10
  35. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  36. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +72 -66
  37. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.d.ts +21 -0
  38. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +315 -0
  39. package/dist/analysis/bot_fitting/shared_utils.d.ts +7 -7
  40. package/dist/analysis/bot_fitting/shared_utils.js +2 -2
  41. package/dist/analysis/bot_key_utils.d.ts +18 -10
  42. package/dist/analysis/bot_key_utils.js +10 -17
  43. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  44. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  45. package/dist/analysis/chain_pool.d.ts +3 -1
  46. package/dist/analysis/chart_ui.d.ts +5 -2
  47. package/dist/analysis/chart_ui.js +6 -3
  48. package/dist/analysis/chart_utils.d.ts +5 -5
  49. package/dist/analysis/chart_utils.js +9 -0
  50. package/dist/analysis/fills_cache.d.ts +64 -0
  51. package/dist/analysis/fills_cache.js +254 -0
  52. package/dist/analysis/fills_source.d.ts +2 -2
  53. package/dist/analysis/fills_source.js +19 -14
  54. package/dist/analysis/grid_correction_check.d.ts +1 -1
  55. package/dist/analysis/grid_correction_check.js +12 -11
  56. package/dist/analysis/math_utils.d.ts +7 -6
  57. package/dist/analysis/math_utils.js +5 -8
  58. package/dist/analysis/pnl_report.d.ts +39 -0
  59. package/dist/analysis/pnl_report.js +325 -0
  60. package/dist/analysis/price_sources.d.ts +8 -8
  61. package/dist/analysis/price_sources.js +5 -4
  62. package/dist/analysis/resolve_bot_accounts.js +2 -2
  63. package/dist/analysis/resolve_source.d.ts +1 -2
  64. package/dist/analysis/trade_profitability.d.ts +32 -2
  65. package/dist/analysis/trade_profitability.js +232 -106
  66. package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
  67. package/dist/analysis/tradingview/analyze_tradingview.js +9 -10
  68. package/dist/analysis/tradingview/grid_reset_config.d.ts +42 -31
  69. package/dist/analysis/tradingview/grid_reset_config.js +35 -6
  70. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -8
  71. package/dist/analysis/tradingview/grid_reset_sim.js +42 -5
  72. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  73. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -20
  74. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +102 -0
  75. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +725 -0
  76. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  77. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +27 -112
  78. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +40 -0
  79. package/dist/analysis/trend_detection/huber_scale_variants.js +176 -0
  80. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  81. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  82. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  83. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  84. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  85. package/dist/credential-daemon.js +34 -20
  86. package/dist/dexbot.js +17 -14
  87. package/dist/market_adapter/candle_utils.d.ts +22 -18
  88. package/dist/market_adapter/candle_utils.js +24 -20
  89. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  90. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  91. package/dist/market_adapter/core/kibana_candles.d.ts +53 -18
  92. package/dist/market_adapter/core/kibana_candles.js +9 -7
  93. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  94. package/dist/market_adapter/core/kibana_client.js +8 -7
  95. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  96. package/dist/market_adapter/core/market_adapter_service.d.ts +297 -115
  97. package/dist/market_adapter/core/market_adapter_service.js +184 -101
  98. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  99. package/dist/market_adapter/core/strategies/ama.js +7 -32
  100. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  101. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  102. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  103. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  104. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  105. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  106. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +36 -8
  107. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +9 -9
  108. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  109. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  110. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  111. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  112. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  113. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  114. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  115. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  116. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  117. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  118. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +97 -226
  119. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +42 -7
  120. package/dist/market_adapter/inputs/fetch_lp_data.js +22 -15
  121. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  122. package/dist/market_adapter/inputs/kibana_feed_source.js +29 -22
  123. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  124. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  125. package/dist/market_adapter/inputs/window_cache.d.ts +99 -94
  126. package/dist/market_adapter/inputs/window_cache.js +8 -8
  127. package/dist/market_adapter/interval_utils.d.ts +4 -4
  128. package/dist/market_adapter/log_format.d.ts +6 -6
  129. package/dist/market_adapter/log_format.js +28 -22
  130. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  131. package/dist/market_adapter/lp_chart_core.js +26 -192
  132. package/dist/market_adapter/lp_chart_runner.d.ts +7 -7
  133. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  134. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  135. package/dist/market_adapter/market_adapter.d.ts +94 -33
  136. package/dist/market_adapter/market_adapter.js +69 -75
  137. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  138. package/dist/market_adapter/utils/adapter_client.js +2 -2
  139. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  140. package/dist/market_adapter/utils/chain.d.ts +50 -41
  141. package/dist/market_adapter/utils/chain.js +40 -46
  142. package/dist/market_adapter/utils/data_discovery.d.ts +4 -1
  143. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  144. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  145. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  146. package/dist/market_adapter/utils/file_lock.js +36 -32
  147. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  148. package/dist/market_adapter/utils/native_history.js +35 -28
  149. package/dist/modules/account_bots.d.ts +577 -21
  150. package/dist/modules/account_bots.js +182 -158
  151. package/dist/modules/account_orders.d.ts +66 -30
  152. package/dist/modules/account_orders.js +22 -20
  153. package/dist/modules/authority_resolver.d.ts +12 -2
  154. package/dist/modules/authority_resolver.js +15 -8
  155. package/dist/modules/bitshares-native/chain_client.d.ts +38 -3
  156. package/dist/modules/bitshares-native/chain_client.js +45 -46
  157. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  158. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  159. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  160. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  161. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  162. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  163. package/dist/modules/bitshares-native/index.d.ts +1 -1
  164. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  165. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  166. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  167. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  168. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  169. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  170. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  171. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  172. package/dist/modules/bitshares-native/serial/types.js +55 -62
  173. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  174. package/dist/modules/bitshares-native/signing_client.js +19 -14
  175. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  176. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  177. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  178. package/dist/modules/bitshares-native/transport.js +5 -4
  179. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  180. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  181. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  182. package/dist/modules/bitshares_client.d.ts +45 -13
  183. package/dist/modules/bitshares_client.js +28 -19
  184. package/dist/modules/bot_defaults.d.ts +6 -15
  185. package/dist/modules/bot_defaults.js +1 -5
  186. package/dist/modules/bot_settings.d.ts +44 -10
  187. package/dist/modules/bot_settings.js +11 -8
  188. package/dist/modules/bots_file_lock.d.ts +6 -6
  189. package/dist/modules/bots_file_lock.js +16 -12
  190. package/dist/modules/broadcast_failure.d.ts +2 -2
  191. package/dist/modules/broadcast_failure.js +5 -4
  192. package/dist/modules/chain_keys.d.ts +42 -40
  193. package/dist/modules/chain_keys.js +53 -45
  194. package/dist/modules/chain_orders.d.ts +93 -59
  195. package/dist/modules/chain_orders.js +31 -23
  196. package/dist/modules/constants.d.ts +530 -32
  197. package/dist/modules/constants.js +52 -60
  198. package/dist/modules/cr_planner.d.ts +40 -2
  199. package/dist/modules/credential_policy.d.ts +68 -8
  200. package/dist/modules/credential_policy.js +37 -31
  201. package/dist/modules/credential_session_cache.d.ts +2 -2
  202. package/dist/modules/credit_pricing.d.ts +42 -6
  203. package/dist/modules/credit_pricing.js +44 -30
  204. package/dist/modules/credit_runtime.d.ts +276 -118
  205. package/dist/modules/credit_runtime.js +462 -165
  206. package/dist/modules/crypto/browser_provider.js +6 -4
  207. package/dist/modules/crypto/node_provider.js +1 -1
  208. package/dist/modules/crypto/pure_scrypt.js +35 -4
  209. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  210. package/dist/modules/crypto/sync.d.ts +9 -9
  211. package/dist/modules/crypto/sync.js +16 -9
  212. package/dist/modules/dexbot_class.d.ts +195 -139
  213. package/dist/modules/dexbot_class.js +78 -28
  214. package/dist/modules/dexbot_cow_runtime.d.ts +167 -87
  215. package/dist/modules/dexbot_cow_runtime.js +248 -206
  216. package/dist/modules/dexbot_credential_client.d.ts +19 -11
  217. package/dist/modules/dexbot_fill_runtime.d.ts +63 -48
  218. package/dist/modules/dexbot_fill_runtime.js +48 -41
  219. package/dist/modules/dexbot_maintenance_runtime.d.ts +109 -70
  220. package/dist/modules/dexbot_maintenance_runtime.js +117 -80
  221. package/dist/modules/dexbot_startup_runtime.d.ts +11 -10
  222. package/dist/modules/dexbot_startup_runtime.js +43 -43
  223. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  224. package/dist/modules/dexbot_state_recovery.js +18 -13
  225. package/dist/modules/fund_registry.d.ts +4 -2
  226. package/dist/modules/fund_registry.js +10 -10
  227. package/dist/modules/general_settings.d.ts +30 -4
  228. package/dist/modules/graceful_shutdown.d.ts +3 -3
  229. package/dist/modules/graceful_shutdown.js +2 -2
  230. package/dist/modules/grid_price_source.d.ts +1 -1
  231. package/dist/modules/key_store.d.ts +14 -8
  232. package/dist/modules/key_store.js +7 -6
  233. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  234. package/dist/modules/launcher/adapter_requirement.js +5 -5
  235. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  236. package/dist/modules/launcher/bot_supervisor.js +12 -11
  237. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  238. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  239. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  240. package/dist/modules/launcher/credential_daemon.js +2 -2
  241. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  242. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  243. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  244. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  245. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  246. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  247. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  248. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  249. package/dist/modules/launcher/supervisor_control.js +4 -2
  250. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  251. package/dist/modules/market_adapter_whitelist.js +15 -3
  252. package/dist/modules/node_manager.d.ts +41 -11
  253. package/dist/modules/node_manager.js +5 -4
  254. package/dist/modules/order/accounting.d.ts +53 -24
  255. package/dist/modules/order/accounting.js +40 -14
  256. package/dist/modules/order/async_lock.d.ts +5 -2
  257. package/dist/modules/order/async_lock.js +1 -1
  258. package/dist/modules/order/export.d.ts +7 -6
  259. package/dist/modules/order/export.js +1 -7
  260. package/dist/modules/order/format.d.ts +39 -19
  261. package/dist/modules/order/format.js +62 -16
  262. package/dist/modules/order/genesis_policy.d.ts +21 -18
  263. package/dist/modules/order/genesis_policy.js +12 -8
  264. package/dist/modules/order/grid.d.ts +142 -36
  265. package/dist/modules/order/grid.js +148 -123
  266. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  267. package/dist/modules/order/grid_reconcile.js +13 -12
  268. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  269. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  270. package/dist/modules/order/index.d.ts +263 -1
  271. package/dist/modules/order/logger.d.ts +45 -11
  272. package/dist/modules/order/logger.js +38 -40
  273. package/dist/modules/order/logger_state.d.ts +4 -4
  274. package/dist/modules/order/manager.d.ts +226 -180
  275. package/dist/modules/order/manager.js +101 -83
  276. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  277. package/dist/modules/order/processed_fill_store.js +16 -27
  278. package/dist/modules/order/strategy.d.ts +21 -13
  279. package/dist/modules/order/strategy.js +5 -6
  280. package/dist/modules/order/sync_engine.d.ts +91 -33
  281. package/dist/modules/order/sync_engine.js +99 -54
  282. package/dist/modules/order/utils/math.d.ts +157 -102
  283. package/dist/modules/order/utils/math.js +77 -38
  284. package/dist/modules/order/utils/order.d.ts +326 -106
  285. package/dist/modules/order/utils/order.js +200 -99
  286. package/dist/modules/order/utils/slot.d.ts +1 -1
  287. package/dist/modules/order/utils/system.d.ts +176 -26
  288. package/dist/modules/order/utils/system.js +86 -69
  289. package/dist/modules/order/utils/validate.d.ts +89 -41
  290. package/dist/modules/order/utils/validate.js +24 -22
  291. package/dist/modules/order/utils/withPoolRef.d.ts +4 -3
  292. package/dist/modules/order/utils/withPoolRef.js +18 -12
  293. package/dist/modules/order/working_grid.d.ts +14 -13
  294. package/dist/modules/paths.d.ts +3 -4
  295. package/dist/modules/paths.js +3 -27
  296. package/dist/modules/process_discovery.d.ts +1 -1
  297. package/dist/modules/process_discovery.js +2 -1
  298. package/dist/modules/runtime.d.ts +7 -3
  299. package/dist/modules/runtime.js +4 -3
  300. package/dist/modules/runtime_settings.d.ts +15 -10
  301. package/dist/modules/runtime_settings.js +30 -24
  302. package/dist/modules/settings_merge.d.ts +29 -3
  303. package/dist/modules/settings_merge.js +56 -78
  304. package/dist/modules/socket_json_client.d.ts +7 -4
  305. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  306. package/dist/modules/storage/browser_adapter.js +7 -30
  307. package/dist/modules/storage/index.d.ts +1 -1
  308. package/dist/modules/storage/node_adapter.d.ts +45 -27
  309. package/dist/modules/storage/node_adapter.js +9 -9
  310. package/dist/modules/storage/types.d.ts +5 -4
  311. package/dist/modules/types.d.ts +1071 -2
  312. package/dist/modules/types.js +4 -1
  313. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  314. package/dist/modules/utils/asset_symbols.js +2 -1
  315. package/dist/modules/utils/errors.d.ts +9 -0
  316. package/dist/modules/utils/errors.js +23 -1
  317. package/dist/modules/utils/time_range.d.ts +4 -0
  318. package/dist/modules/utils/time_range.js +18 -0
  319. package/dist/modules/validate_profiles.js +53 -43
  320. package/dist/modules/version_notice.d.ts +14 -3
  321. package/dist/modules/version_notice.js +6 -4
  322. package/dist/pm2.d.ts +29 -27
  323. package/dist/pm2.js +5 -5
  324. package/dist/scripts/analyze-credit.d.ts +2 -1
  325. package/dist/scripts/analyze-credit.js +23 -24
  326. package/dist/scripts/analyze-orders.d.ts +77 -9
  327. package/dist/scripts/analyze-orders.js +66 -84
  328. package/dist/scripts/chart_command.d.ts +27 -18
  329. package/dist/scripts/chart_command.js +16 -15
  330. package/dist/scripts/check_any.d.ts +18 -0
  331. package/dist/scripts/check_any.js +126 -0
  332. package/dist/scripts/diagnose-pool-history.js +12 -7
  333. package/dist/scripts/pnl.d.ts +3 -0
  334. package/dist/scripts/pnl.js +40 -0
  335. package/dist/scripts/print_grid.js +0 -1
  336. package/dist/scripts/run-tests.js +39 -7
  337. package/dist/scripts/runner.js +1 -1
  338. package/dist/scripts/test-credit-renewal.js +30 -21
  339. package/dist/scripts/update.d.ts +10 -5
  340. package/dist/scripts/update.js +168 -103
  341. package/dist/scripts/update_dist_freshness.js +1 -0
  342. package/dist/scripts/update_layout.d.ts +61 -0
  343. package/dist/scripts/update_layout.js +180 -0
  344. package/dist/scripts/validate_bots.js +2 -1
  345. package/dist/scripts/verify-browser-bundle.js +8 -0
  346. package/dist/unlock.d.ts +28 -3
  347. package/dist/unlock.js +72 -10
  348. package/docs/BITSHARES_ONBOARDING.md +2 -0
  349. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  350. package/docs/COW_INVARIANTS.md +13 -6
  351. package/docs/DEXBOT_COMPARISON.md +8 -8
  352. package/docs/EVOLUTION.md +12 -10
  353. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  354. package/docs/GRID_RECALCULATION.md +15 -16
  355. package/docs/GRID_RECONCILE.md +14 -3
  356. package/docs/LIFECYCLE.md +11 -11
  357. package/docs/MPA_CREDIT_USAGE.md +22 -3
  358. package/docs/README.md +15 -4
  359. package/docs/WORKFLOW.md +1 -0
  360. package/docs/architecture.md +12 -9
  361. package/docs/developer_guide.md +6 -6
  362. package/market_adapter/README.md +9 -26
  363. package/modules/README.md +4 -1
  364. package/package.json +4 -1
  365. package/scripts/README.md +14 -0
@@ -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
@@ -242,6 +242,14 @@ let TIMING = {
242
242
  // genuinely empty. A contradicted re-read (non-empty) aborts acceptance
243
243
  // and feeds the fresh snapshot to the resync instead.
244
244
  SYNC_EMPTY_READ_CONFIRM_DELAY_MS: 2000,
245
+ // Surplus-cancel grace for freshly placed orders. Spread correction and
246
+ // surplus sweeps run on different count snapshots within one cycle, so a
247
+ // fill landing between them makes the second controller cancel what the
248
+ // first just placed (observed: 4 placed, 3 cancelled seconds later).
249
+ // Orders younger than this are skipped by surplus cancellation and
250
+ // re-evaluated next cycle. Time-bounded by design: genuine misplacements
251
+ // are only delayed, never protected forever.
252
+ SURPLUS_CANCEL_GRACE_MS: 15 * 60 * 1000,
245
253
  // Connection and initialization timeouts
246
254
  CONNECTION_TIMEOUT_MS: 30000, // 30 seconds - BitShares client connection establishment timeout
247
255
  DAEMON_STARTUP_TIMEOUT_MS: 60000, // 60 seconds - Private key daemon startup timeout
@@ -356,6 +364,7 @@ let TIMING = {
356
364
  CREDIT_DEAL_CHECK_INTERVAL_MIN: 60, // How often to check credit deal expiry (minutes)
357
365
  CREDIT_DEAL_EXPIRY_THRESHOLD_HOURS: 12, // Proactively renew deals expiring within this window
358
366
  CREDIT_DEAL_SPLIT_MAX_PIECES: 48, // Max pieces per _splitOversizedCreditDeals cycle (~4.8min at 6s/piece)
367
+ CREDIT_REBORROW_MAX_ATTEMPTS: 6, // Drop a deferred reborrow after this many failed build/broadcast attempts
359
368
  // LOCK_REFRESH_MIN_MS: Minimum interval for refreshing order lock leases during long operations.
360
369
  // Prevents lock expiration during extended reconciliations or batch operations.
361
370
  // Default: 250ms (4 refreshes per second minimum during long operations).
@@ -695,11 +704,7 @@ let INCREMENT_BOUNDS = {
695
704
  // Minimum increment percentage allowed (0.01%)
696
705
  MIN_PERCENT: 0.01,
697
706
  // Maximum increment percentage allowed (10%)
698
- MAX_PERCENT: 10,
699
- // Minimum increment as decimal factor (0.01% = 0.0001)
700
- MIN_FACTOR: 0.0001,
701
- // Maximum increment as decimal factor (10% = 0.10)
702
- MAX_FACTOR: 0.10
707
+ MAX_PERCENT: 10
703
708
  };
704
709
  // Fee-related parameters for order operations
705
710
  let FEE_PARAMETERS = {
@@ -875,6 +880,13 @@ let FILL_PROCESSING = {
875
880
  // 0 drains no price updates this cycle. Cancel-class entries are never
876
881
  // budgeted by either knob.
877
882
  CORRECTION_MAX_UPDATES_PER_CYCLE: null,
883
+ // CORRECTION_INTER_OP_DELAY_MS: spacing between successive correction
884
+ // broadcasts (one update/cancel RPC per iteration). Default null inherits
885
+ // TIMING.SYNC_DELAY_MS (500ms) — the production pacing that keeps a burst
886
+ // of corrections from looking like a flood to the node. Exposed as a
887
+ // config knob so tests can drive the drain at 0ms without wall-clock
888
+ // sleeps; 0 is honored verbatim.
889
+ CORRECTION_INTER_OP_DELAY_MS: null,
878
890
  // CORRECTION_QUEUE_WARN_THRESHOLD: emit a rate-limited warn when the
879
891
  // persisted correction queue reaches this size, so a growing backlog is
880
892
  // surfaced instead of silently starving placements.
@@ -1083,12 +1095,15 @@ let MARKET_ADAPTER = {
1083
1095
  // DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS: Lookback window for measuring AMA trend.
1084
1096
  // Lower values react faster to recent price changes.
1085
1097
  // Higher values smooth the signal and require a more sustained move.
1086
- // 20 (was 9): measured on the real 1h pools, the slope's bar-to-bar wobble
1087
- // drops ~34% and slope-driven grid resets ~19%, while the band tilt is
1088
- // unchanged; the cost is freshness — the window centre sits ~10 bars back
1089
- // instead of ~4.5, so reversals are acted on later.
1098
+ // 16 (was 20): the shorter window's slope is ~8% noisier (bar-to-bar wobble
1099
+ // and zero-crossings), which by itself would add slope resets; the
1100
+ // persistence gate (K=3) absorbs that, so resets/day stay matched — 962 vs
1101
+ // 960 on the sample, 0.95/day either way. It buys a cleaner signal where it
1102
+ // matters: AMA group delay 10→8 bars, reversal lag 22→20, and range-tilt
1103
+ // wrong-way 13.7%→12.6%. Measured on the real 1h pools; see
1104
+ // docs/AMA_SLOPE_WINDOW.md.
1090
1105
  // nob: lb (Lookback Bars)
1091
- DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS: 20,
1106
+ DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS: 16,
1092
1107
  // DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT: Average per-bar trend size that counts as "full strength" for AMA.
1093
1108
  // Lower values make the AMA channel reach maximum influence more easily.
1094
1109
  // Higher values require a stronger price move before AMA reaches full effect.
@@ -1100,7 +1115,7 @@ let MARKET_ADAPTER = {
1100
1115
  // Lower values make the Kalman channel reach maximum influence more easily.
1101
1116
  // Higher values require a stronger move before the Kalman branch reaches full effect.
1102
1117
  // nob: kalS% (Kalman Max Slope %)
1103
- DYNAMIC_WEIGHT_KALMAN_MAX_SLOPE_PCT: 1.11,
1118
+ DYNAMIC_WEIGHT_KALMAN_MAX_SLOPE_PCT: 1.2,
1104
1119
  // DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT: Ignore small AMA moves around flat price action.
1105
1120
  // Higher values create a larger neutral zone and reduce small trend reactions.
1106
1121
  // Lower values make the AMA channel react to smaller moves.
@@ -1113,8 +1128,16 @@ let MARKET_ADAPTER = {
1113
1128
  // Node callers via the module import, generated HTML via an injected
1114
1129
  // `const AMA_SLOPE_HUBER = {...}` literal. Change a value here and every
1115
1130
  // slope computation follows; do not re-declare them per caller.
1116
- // C Huber tuning constant (1.345 ~= 95% Gaussian efficiency)
1117
- // ITERATIONS IRLS passes (converges in a few at the 20-bar window)
1131
+ // C Huber tuning constant. Nominal 1.345 ~= 95% Gaussian
1132
+ // efficiency, but the plug-in 1.4826*MAD scale is biased low
1133
+ // (residual degrees of freedom), so the EFFECTIVE C is
1134
+ // ~1.25 at the 16-bar window — more robust, less efficient
1135
+ // than nominal. The detune grows ~1/(bars-1) at short
1136
+ // windows and vanishes at long ones; deliberately NOT
1137
+ // compensated (the bias points the robust way, and a
1138
+ // sqrt(n/(n-2)) correction is decision-neutral). See
1139
+ // analysis/trend_detection/huber_scale_variants.ts.
1140
+ // ITERATIONS IRLS passes (converges in a few at the ~16-bar window)
1118
1141
  // SCALE_FLOOR Floor for the 1.4826*MAD robust scale, in log units
1119
1142
  // ZERO_EPSILON Slopes below this (%/bar) snap to exactly 0
1120
1143
  // nob: n/a (algorithm-internal)
@@ -1124,6 +1147,20 @@ let MARKET_ADAPTER = {
1124
1147
  SCALE_FLOOR: 1e-6,
1125
1148
  ZERO_EPSILON: 1e-9,
1126
1149
  },
1150
+ // AMA_SLOPE_PERSIST_ENABLED: slope-delta persistence gate (trigger B).
1151
+ // When true, the slope reset requires AMA_SLOPE_PERSIST_BARS consecutive
1152
+ // confirming bars, filtering short-lived excursions. Enabled by default
1153
+ // (was legacy fire-on-first-crossing): measured over the real 1h pools it
1154
+ // cuts resets ~35% and whipsaw ~52%→~17%, leaving lag and range-tilt
1155
+ // unchanged. Per bot/market override via `amaSlope.persistBars` (>= 1 gate
1156
+ // length, 0 disables, 1 = legacy) or `amaSlope.persistEnabled: false`
1157
+ // (disables even while the global flag is on). See docs/AMA_SLOPE_WINDOW.md.
1158
+ AMA_SLOPE_PERSIST_ENABLED: true,
1159
+ // AMA_SLOPE_PERSIST_BARS: consecutive confirming bars required before the
1160
+ // slope-delta grid reset (trigger B) fires once enabled. 1 = legacy behavior
1161
+ // (no persistence). Filters short-lived slope excursions without adding trend
1162
+ // latency.
1163
+ AMA_SLOPE_PERSIST_BARS: 3,
1127
1164
  // DYNAMIC_WEIGHT_ALPHA: Blend between AMA trend and Kalman trend.
1128
1165
  // 0 = pure Kalman, 1 = pure AMA.
1129
1166
  // Higher values trust AMA more, lower values trust Kalman more.
@@ -1331,14 +1368,6 @@ let MARKET_ADAPTER = {
1331
1368
  // AMA_CONVERGENCE_EPSILON: Target fraction of initialization bias remaining
1332
1369
  // after convergence. 0.01 = 99 % of the initial bias has decayed.
1333
1370
  AMA_CONVERGENCE_EPSILON: 0.01,
1334
- // AMA_ER_SMOOTH_FAST_PERIOD: Fast-period equivalent for smoothing the raw
1335
- // Efficiency Ratio via EMA before it enters the SC formula. Raw ER can spike
1336
- // at regime boundaries (trending ↔ ranging), causing jerky AMA transitions
1337
- // and false grid re-centering triggers.
1338
- // 0 = disabled (raw ER used directly, backward compatible).
1339
- // Enabled alpha = 2 / (AMA_ER_SMOOTH_FAST_PERIOD + 1).
1340
- // Overridable per bot via bots.json inline `ama.erSmoothPeriod` field.
1341
- AMA_ER_SMOOTH_FAST_PERIOD: 0,
1342
1371
  };
1343
1372
  // Logging Level Configuration
1344
1373
  // Options:
@@ -1581,7 +1610,6 @@ let COW_PERFORMANCE = {
1581
1610
  // Structure:
1582
1611
  // NATIVE_CLIENT.CHAIN - Graphene chain parameters
1583
1612
  // NATIVE_CLIENT.OPERATIONS - Operation type IDs
1584
- // NATIVE_CLIENT.OBJECT_TYPES - Object space/type IDs
1585
1613
  // NATIVE_CLIENT.TRANSACTION - Transaction builder limits
1586
1614
  // NATIVE_CLIENT.TRANSPORT - WebSocket transport tuning
1587
1615
  // NATIVE_CLIENT.SUBSCRIPTIONS - Fill-detection subscription settings
@@ -1589,7 +1617,7 @@ let COW_PERFORMANCE = {
1589
1617
  // NATIVE_CLIENT.ECC - Cryptographic constants (reference only)
1590
1618
  //
1591
1619
  // Source files:
1592
- // modules/bitshares-native/serial/chain_constants.ts (CHAIN, OPERATIONS, OBJECT_TYPES)
1620
+ // modules/bitshares-native/serial/chain_constants.ts (CHAIN, OPERATIONS)
1593
1621
  // modules/bitshares-native/tx/builder.ts (TRANSACTION)
1594
1622
  // modules/bitshares-native/transport.ts (TRANSPORT)
1595
1623
  // modules/bitshares-native/subscriptions.ts (SUBSCRIPTIONS)
@@ -1640,36 +1668,6 @@ let NATIVE_CLIENT = {
1640
1668
  LIQUIDITY_POOL_EXCHANGE: 63,
1641
1669
  },
1642
1670
  // -------------------------------------------------------------------------
1643
- // OBJECT_TYPES — Graphene object space/type IDs
1644
- // -------------------------------------------------------------------------
1645
- // Space 1 (protocol), used for blockchain entity identification.
1646
- // Object IDs follow the format "space.type.instance" (e.g. "1.2.12345" = account).
1647
- OBJECT_TYPES: {
1648
- NULL: 0,
1649
- BASE: 1,
1650
- ACCOUNT: 2,
1651
- ASSET: 3,
1652
- FORCE_SETTLEMENT: 4,
1653
- COMMITTEE_MEMBER: 5,
1654
- WITNESS: 6,
1655
- LIMIT_ORDER: 7,
1656
- CALL_ORDER: 8,
1657
- CUSTOM: 9,
1658
- PROPOSAL: 10,
1659
- OPERATION_HISTORY: 11,
1660
- WITHDRAW_PERMISSION: 12,
1661
- VESTING_BALANCE: 13,
1662
- WORKER: 14,
1663
- BALANCE: 15,
1664
- HTLC: 16,
1665
- CUSTOM_AUTHORITY: 17,
1666
- TICKET: 18,
1667
- LIQUIDITY_POOL: 19,
1668
- SAMET_FUND: 20,
1669
- CREDIT_OFFER: 21,
1670
- CREDIT_DEAL: 22,
1671
- },
1672
- // -------------------------------------------------------------------------
1673
1671
  // TRANSACTION — Transaction builder limits (tx/builder.js)
1674
1672
  // -------------------------------------------------------------------------
1675
1673
  TRANSACTION: {
@@ -1737,11 +1735,6 @@ let NATIVE_CLIENT = {
1737
1735
  // node failure. 1000 = normal closure, 1001 = going away (server
1738
1736
  // shutdown/deploy). Any other code, or wasClean === false, is abnormal.
1739
1737
  BENIGN_CLOSE_CODES: [1000, 1001],
1740
- // NOTE: These constants are informational but not imported by transport.ts
1741
- // Reconnection backoff parameters (ms).
1742
- // Reconnect delay = min(base × 2^attempt + random(0..1000), max).
1743
- RECONNECT_BASE_MS: 1000,
1744
- RECONNECT_MAX_MS: 30000,
1745
1738
  },
1746
1739
  // -------------------------------------------------------------------------
1747
1740
  // SUBSCRIPTIONS — Fill-detection subscription settings (subscriptions.js)
@@ -1997,7 +1990,6 @@ Object.freeze(COW_PERFORMANCE);
1997
1990
  Object.freeze(LOGGING_CONFIG);
1998
1991
  Object.freeze(NATIVE_CLIENT.CHAIN);
1999
1992
  Object.freeze(NATIVE_CLIENT.OPERATIONS);
2000
- Object.freeze(NATIVE_CLIENT.OBJECT_TYPES);
2001
1993
  Object.freeze(NATIVE_CLIENT.TRANSACTION);
2002
1994
  Object.freeze(NATIVE_CLIENT.TRANSPORT);
2003
1995
  Object.freeze(NATIVE_CLIENT.SUBSCRIPTIONS);
@@ -28,7 +28,45 @@ interface CollateralFallbackPlanOptions {
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
@@ -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