dexbot 1.6.12 → 1.6.14

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 (213) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/README.md +2 -2
  3. package/analysis/README.md +9 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/claw/README.md +1 -0
  6. package/claw/docs/AI_BOT_LIBRARY_API.md +3 -1
  7. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  8. package/claw/modules/claw_bridge.ts +0 -3
  9. package/claw/modules/claw_catalog.ts +8 -4
  10. package/claw/modules/claw_skill_md.ts +1 -0
  11. package/claw/modules/dexbot_profiles.ts +59 -15
  12. package/claw/modules/types.ts +2 -1
  13. package/claw/package.json +3 -3
  14. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  15. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  16. package/claw/skills/margin-trading/SKILL.md +1 -1
  17. package/claw/skills/margin-trading/references/position-management.md +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  20. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  21. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  22. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  23. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  24. package/dist/analysis/analyze_args.d.ts +12 -0
  25. package/dist/analysis/analyze_args.js +20 -0
  26. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  27. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  28. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  29. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  30. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  31. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  32. package/dist/analysis/chart_ui.d.ts +30 -1
  33. package/dist/analysis/chart_ui.js +37 -1
  34. package/dist/analysis/fills_cache.d.ts +3 -23
  35. package/dist/analysis/fills_cache.js +3 -84
  36. package/dist/analysis/fills_source.d.ts +31 -1
  37. package/dist/analysis/fills_source.js +69 -1
  38. package/dist/analysis/grid_correction_check.d.ts +1 -23
  39. package/dist/analysis/grid_correction_check.js +15 -58
  40. package/dist/analysis/math_utils.d.ts +85 -1
  41. package/dist/analysis/math_utils.js +116 -1
  42. package/dist/analysis/price_sources.d.ts +22 -1
  43. package/dist/analysis/price_sources.js +23 -0
  44. package/dist/analysis/resolve_source.js +31 -10
  45. package/dist/analysis/trade_profitability.d.ts +6 -0
  46. package/dist/analysis/trade_profitability.js +23 -97
  47. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  48. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  49. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +27 -40
  50. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  51. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  52. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  53. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  54. package/dist/analysis/worker_pool.d.ts +38 -0
  55. package/dist/analysis/worker_pool.js +67 -0
  56. package/dist/dexbot.js +67 -48
  57. package/dist/market_adapter/ama_signal_runner.js +21 -54
  58. package/dist/market_adapter/candle_utils.d.ts +7 -1
  59. package/dist/market_adapter/candle_utils.js +11 -1
  60. package/dist/market_adapter/cli_args.d.ts +22 -0
  61. package/dist/market_adapter/cli_args.js +30 -0
  62. package/dist/market_adapter/core/config_normalizers.js +11 -6
  63. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  64. package/dist/market_adapter/core/kibana_candles.js +3 -2
  65. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  66. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  67. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  68. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  69. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  70. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  71. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  72. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  73. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  74. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  75. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  76. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  77. package/dist/market_adapter/inputs/window_cache.js +52 -177
  78. package/dist/market_adapter/interval_utils.d.ts +11 -1
  79. package/dist/market_adapter/interval_utils.js +16 -1
  80. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  81. package/dist/market_adapter/lp_chart_runner.js +37 -19
  82. package/dist/market_adapter/market_adapter.js +27 -72
  83. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  84. package/dist/market_adapter/utils/data_discovery.js +220 -27
  85. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  86. package/dist/market_adapter/utils/month_shards.js +237 -0
  87. package/dist/modules/account_bots.d.ts +8 -6
  88. package/dist/modules/account_bots.js +112 -131
  89. package/dist/modules/account_orders.d.ts +49 -4
  90. package/dist/modules/account_orders.js +114 -49
  91. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  92. package/dist/modules/bitshares-native/chain_client.js +14 -13
  93. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  94. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  95. package/dist/modules/bitshares-native/resolvers.js +22 -25
  96. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  97. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  98. package/dist/modules/bitshares-native/serial/types.js +22 -50
  99. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  100. package/dist/modules/bot_defaults.d.ts +18 -3
  101. package/dist/modules/bot_defaults.js +34 -8
  102. package/dist/modules/bot_settings.d.ts +5 -1
  103. package/dist/modules/bot_settings.js +55 -21
  104. package/dist/modules/broadcast_failure.d.ts +2 -1
  105. package/dist/modules/chain_orders.d.ts +1 -1
  106. package/dist/modules/chain_orders.js +51 -96
  107. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  108. package/dist/modules/config.js +6 -1
  109. package/dist/modules/constants.d.ts +14 -6
  110. package/dist/modules/constants.js +32 -6
  111. package/dist/modules/cr_planner.d.ts +1 -1
  112. package/dist/modules/cr_planner.js +1 -5
  113. package/dist/modules/credit_pricing.d.ts +2 -1
  114. package/dist/modules/credit_pricing.js +36 -40
  115. package/dist/modules/credit_runtime.d.ts +7 -0
  116. package/dist/modules/credit_runtime.js +45 -73
  117. package/dist/modules/daemon_node_health.d.ts +4 -3
  118. package/dist/modules/dexbot_class.d.ts +33 -17
  119. package/dist/modules/dexbot_class.js +113 -61
  120. package/dist/modules/dexbot_cow_runtime.d.ts +62 -181
  121. package/dist/modules/dexbot_cow_runtime.js +380 -69
  122. package/dist/modules/dexbot_credential_client.d.ts +1 -23
  123. package/dist/modules/dexbot_credential_client.js +2 -3
  124. package/dist/modules/dexbot_fill_runtime.d.ts +2 -3
  125. package/dist/modules/dexbot_fill_runtime.js +17 -7
  126. package/dist/modules/dexbot_maintenance_runtime.d.ts +36 -81
  127. package/dist/modules/dexbot_maintenance_runtime.js +137 -133
  128. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  129. package/dist/modules/dexbot_startup_runtime.js +25 -14
  130. package/dist/modules/dexbot_state_recovery.js +16 -0
  131. package/dist/modules/general_settings.d.ts +1 -1
  132. package/dist/modules/graceful_shutdown.js +17 -11
  133. package/dist/modules/key_store.d.ts +0 -5
  134. package/dist/modules/key_store.js +1 -2
  135. package/dist/modules/lazy_shim.d.ts +11 -0
  136. package/dist/modules/lazy_shim.js +16 -0
  137. package/dist/modules/node_connect_policy.d.ts +3 -2
  138. package/dist/modules/node_failure_ledger.d.ts +6 -5
  139. package/dist/modules/order/accounting.js +11 -11
  140. package/dist/modules/order/export.js +2 -2
  141. package/dist/modules/order/format.d.ts +26 -3
  142. package/dist/modules/order/format.js +33 -3
  143. package/dist/modules/order/genesis_policy.d.ts +4 -4
  144. package/dist/modules/order/genesis_policy.js +6 -3
  145. package/dist/modules/order/grid.d.ts +26 -12
  146. package/dist/modules/order/grid.js +468 -80
  147. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  148. package/dist/modules/order/grid_reconcile.js +5 -5
  149. package/dist/modules/order/grid_reconcile_internal.js +48 -40
  150. package/dist/modules/order/index.d.ts +35 -8
  151. package/dist/modules/order/logger.d.ts +1 -8
  152. package/dist/modules/order/logger.js +2 -11
  153. package/dist/modules/order/manager.d.ts +18 -15
  154. package/dist/modules/order/manager.js +91 -74
  155. package/dist/modules/order/strategy.d.ts +2 -2
  156. package/dist/modules/order/strategy.js +51 -21
  157. package/dist/modules/order/sync_engine.js +4 -0
  158. package/dist/modules/order/utils/math.d.ts +3 -3
  159. package/dist/modules/order/utils/math.js +38 -27
  160. package/dist/modules/order/utils/order.d.ts +58 -58
  161. package/dist/modules/order/utils/order.js +158 -137
  162. package/dist/modules/order/utils/system.d.ts +202 -35
  163. package/dist/modules/order/utils/system.js +409 -31
  164. package/dist/modules/order/utils/validate.js +28 -6
  165. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  166. package/dist/modules/paths.js +32 -34
  167. package/dist/modules/runtime_settings.d.ts +3 -5
  168. package/dist/modules/runtime_settings.js +3 -3
  169. package/dist/modules/settings_merge.d.ts +2 -2
  170. package/dist/modules/socket_json_client.d.ts +2 -1
  171. package/dist/modules/types.d.ts +89 -30
  172. package/dist/modules/utils/errors.js +1 -3
  173. package/dist/modules/version_notice.d.ts +11 -10
  174. package/dist/pm2.d.ts +0 -1
  175. package/dist/pm2.js +56 -35
  176. package/dist/scripts/analyze-git.js +2 -15
  177. package/dist/scripts/analyze-orders.d.ts +1 -1
  178. package/dist/scripts/analyze-orders.js +4 -4
  179. package/dist/scripts/chart_command.js +2 -2
  180. package/dist/scripts/check_any.d.ts +4 -0
  181. package/dist/scripts/check_any.js +53 -21
  182. package/dist/scripts/diagnose-pool-history.js +1 -6
  183. package/dist/scripts/divergence-calc.js +6 -6
  184. package/dist/scripts/run-tests.js +0 -1
  185. package/dist/scripts/sync-version.js +0 -10
  186. package/dist/scripts/validate_bots.d.ts +1 -1
  187. package/dist/scripts/validate_bots.js +3 -3
  188. package/dist/unlock.js +7 -2
  189. package/docs/BITSHARES_ONBOARDING.md +8 -12
  190. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -3
  191. package/docs/COW_INVARIANTS.md +6 -6
  192. package/docs/DEXBOT_COMPARISON.md +7 -7
  193. package/docs/EVOLUTION.md +10 -8
  194. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  195. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  196. package/docs/GRID_RECALCULATION.md +4 -1
  197. package/docs/GRID_RECONCILE.md +4 -4
  198. package/docs/LIFECYCLE.md +11 -11
  199. package/docs/LOGGING.md +14 -0
  200. package/docs/MPA_CREDIT_USAGE.md +1 -1
  201. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +12 -4
  202. package/docs/README.md +3 -3
  203. package/docs/WORKFLOW.md +1 -0
  204. package/docs/architecture.md +25 -16
  205. package/docs/developer_guide.md +7 -2
  206. package/market_adapter/README.md +6 -4
  207. package/package.json +6 -9
  208. package/scripts/README.md +43 -38
  209. package/tests/README.md +26 -11
  210. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  211. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  212. package/scripts/git-viewer.sh +0 -489
  213. package/scripts/postinstall.js +0 -16
@@ -16,10 +16,10 @@
16
16
  * 1. AccountOrders(options) - Class for per-bot order persistence
17
17
  * Constructor options: { botKey, ordersDir?, profilesPath? } (botKey required, throws if missing)
18
18
  * Methods:
19
- * syncMeta(botConfig), storeMasterGrid(orders, btsFeesOwed, boundaryIdx, assets, debugInputs, recentFillKeys, genesis, gapEvacStreaks, pendingFillCrawls, lastFillPivot)
19
+ * syncMeta(botConfig), storeMasterGrid(orders, btsFeesOwed, boundaryIdx, assets, debugInputs, recentFillKeys, genesis, gapEvacStreaks, pendingFillCrawls, lastFillPivot, lastMarketFill)
20
20
  * loadGrid(forceReload), loadRecentFillKeys(forceReload), loadPersistedAssets(forceReload), loadPendingFillCrawls(forceReload)
21
- * loadBoundaryIdx(forceReload), loadBtsBalance(forceReload), loadBtsFeesOwed(forceReload), loadGapEvacStreaks(forceReload), loadGenesis(forceReload), loadLastFillPivot(forceReload)
22
- * clearGrid(), clearPersistedBoundary(), clearPersistedLastFillPivot()
21
+ * loadBoundaryIdx(forceReload), loadBtsBalance(forceReload), loadBtsFeesOwed(forceReload), loadGapEvacStreaks(forceReload), loadGenesis(forceReload), loadLastFillPivot(forceReload), loadLastMarketFill(forceReload)
22
+ * clearGrid(), clearPersistedBoundary(), clearPersistedLastFillPivot(), clearPersistedLastMarketFill(), backupSnapshot(reason)
23
23
  * loadProcessedFills(options), updateProcessedFillsBatch(fills), cleanOldProcessedFills(olderThanMs)
24
24
  * getAssetBalances(forceReload)
25
25
  *
@@ -109,6 +109,12 @@ interface BotData {
109
109
  ts: number;
110
110
  }[];
111
111
  lastFillPivot?: unknown;
112
+ /** Bot-scoped last-market-fill reference (survives grid regeneration). */
113
+ lastMarketFill?: {
114
+ price: number;
115
+ type: string;
116
+ fillsAt: number;
117
+ };
112
118
  }
113
119
  /**
114
120
  * AccountOrders class - manages order grid persistence
@@ -151,6 +157,19 @@ declare class AccountOrders {
151
157
  * @private
152
158
  */
153
159
  _loadData(): BotData | null;
160
+ /**
161
+ * Reload `this.data` from disk, falling back to empty state on a miss.
162
+ * Single home for the read-modify-write preamble inside the persistence lock.
163
+ * @private
164
+ */
165
+ _reload(): void;
166
+ /**
167
+ * Reload `this.data` from disk when `forceReload` is set. Shared preamble of
168
+ * every `loadX(forceReload)` accessor.
169
+ * @param {boolean} [forceReload=false]
170
+ * @private
171
+ */
172
+ _ensureLoaded(forceReload?: boolean): void;
154
173
  /**
155
174
  * Reads and parses a JSON file.
156
175
  * @param {string} filePath - The path to the file.
@@ -201,7 +220,7 @@ declare class AccountOrders {
201
220
  * @param {Object|null} recentFillKeys - Optional fill key dedup snapshot for crash recovery
202
221
  * @param {Object|null} genesis - Optional frozen genesis (priceLevels etc)
203
222
  */
204
- storeMasterGrid(orders?: unknown[], btsFeesOwed?: number | null, boundaryIdx?: number | null, assets?: Record<string, unknown> | null, debugInputs?: unknown, recentFillKeys?: Record<string, unknown> | null, genesis?: unknown, gapEvacStreaks?: unknown, pendingFillCrawls?: unknown, lastFillPivot?: unknown): Promise<void>;
223
+ storeMasterGrid(orders?: unknown[], btsFeesOwed?: number | null, boundaryIdx?: number | null, assets?: Record<string, unknown> | null, debugInputs?: unknown, recentFillKeys?: Record<string, unknown> | null, genesis?: unknown, gapEvacStreaks?: unknown, pendingFillCrawls?: unknown, lastFillPivot?: unknown, lastMarketFill?: unknown): Promise<void>;
205
224
  /**
206
225
  * Erase a poisoned persisted boundary after GRID-LOAD rejects it with no
207
226
  * safe re-derivation. storeMasterGrid deliberately never writes a null
@@ -266,6 +285,32 @@ declare class AccountOrders {
266
285
  fillsAt: number;
267
286
  genesisHash: string;
268
287
  } | null;
288
+ /**
289
+ * Load the persisted bot-scoped last-market-fill reference.
290
+ * @param {boolean} forceReload - If true, reload from disk
291
+ * @returns {Object|null} {price, type, fillsAt} or null when absent/invalid
292
+ */
293
+ loadLastMarketFill(forceReload?: boolean): {
294
+ price: number;
295
+ type: string;
296
+ fillsAt: number;
297
+ } | null;
298
+ /**
299
+ * Erase a persisted last-market-fill row that restoreLastMarketFill
300
+ * rejected (TTL expiry / malformed). Mirrors clearPersistedLastFillPivot:
301
+ * without an explicit erase a dead row would re-arm the same rejection on
302
+ * every restart. Load-time only.
303
+ */
304
+ clearPersistedLastMarketFill(): Promise<void>;
305
+ /**
306
+ * Copy the on-disk snapshot to a timestamped sibling file before a
307
+ * destructive operation (snapshot rejection / regeneration). The reason tag
308
+ * is sanitized into the suffix: `<profile>.rejected-drift-<ts>`. Owns the
309
+ * path/storage knowledge so callers never reach through to the filesystem.
310
+ * @param {string} [reason='backup'] - Reason tag for the filename
311
+ * @returns {Promise<string|null>} Backup path, or null when absent/failed
312
+ */
313
+ backupSnapshot(reason?: string): Promise<string | null>;
269
314
  /**
270
315
  * Load persisted pending fill crawls for this bot.
271
316
  * @param {boolean} forceReload - If true, reload from disk
@@ -16,10 +16,10 @@
16
16
  * 1. AccountOrders(options) - Class for per-bot order persistence
17
17
  * Constructor options: { botKey, ordersDir?, profilesPath? } (botKey required, throws if missing)
18
18
  * Methods:
19
- * syncMeta(botConfig), storeMasterGrid(orders, btsFeesOwed, boundaryIdx, assets, debugInputs, recentFillKeys, genesis, gapEvacStreaks, pendingFillCrawls, lastFillPivot)
19
+ * syncMeta(botConfig), storeMasterGrid(orders, btsFeesOwed, boundaryIdx, assets, debugInputs, recentFillKeys, genesis, gapEvacStreaks, pendingFillCrawls, lastFillPivot, lastMarketFill)
20
20
  * loadGrid(forceReload), loadRecentFillKeys(forceReload), loadPersistedAssets(forceReload), loadPendingFillCrawls(forceReload)
21
- * loadBoundaryIdx(forceReload), loadBtsBalance(forceReload), loadBtsFeesOwed(forceReload), loadGapEvacStreaks(forceReload), loadGenesis(forceReload), loadLastFillPivot(forceReload)
22
- * clearGrid(), clearPersistedBoundary(), clearPersistedLastFillPivot()
21
+ * loadBoundaryIdx(forceReload), loadBtsBalance(forceReload), loadBtsFeesOwed(forceReload), loadGapEvacStreaks(forceReload), loadGenesis(forceReload), loadLastFillPivot(forceReload), loadLastMarketFill(forceReload)
22
+ * clearGrid(), clearPersistedBoundary(), clearPersistedLastFillPivot(), clearPersistedLastMarketFill(), backupSnapshot(reason)
23
23
  * loadProcessedFills(options), updateProcessedFillsBatch(fills), cleanOldProcessedFills(olderThanMs)
24
24
  * getAssetBalances(forceReload)
25
25
  *
@@ -66,7 +66,7 @@ import AsyncLock from './order/async_lock.js';
66
66
  import { isPhantomOrder } from './order/utils/order.js';
67
67
  import { hasGenesisLadder } from './order/genesis_policy.js';
68
68
  import * as Format from './order/format.js';
69
- import { ensureDir, nowIso, normalizeLastFillPivot } from './order/utils/system.js';
69
+ import { ensureDir, nowIso, normalizeLastFillPivot, normalizeLastMarketFill } from './order/utils/system.js';
70
70
  import Logger from './order/logger.js';
71
71
  import { getErrorMessage, getErrorCode } from './utils/errors.js';
72
72
  import { sanitizeKey } from './utils/sanitize_key.js';
@@ -194,7 +194,7 @@ class AccountOrders {
194
194
  // AsyncLock prevents concurrent read-modify-write races on file I/O
195
195
  this._persistenceLock = new AsyncLock();
196
196
  this._needsBootstrapSave = !storage.exists(this.profilesPath);
197
- this.data = this._loadData() || emptyData();
197
+ this._reload();
198
198
  if (this._needsBootstrapSave) {
199
199
  this._persist();
200
200
  }
@@ -208,6 +208,24 @@ class AccountOrders {
208
208
  // Load the file directly - per-bot files only contain their own bot's data
209
209
  return this._readFile(this.profilesPath);
210
210
  }
211
+ /**
212
+ * Reload `this.data` from disk, falling back to empty state on a miss.
213
+ * Single home for the read-modify-write preamble inside the persistence lock.
214
+ * @private
215
+ */
216
+ _reload() {
217
+ this.data = this._loadData() || emptyData();
218
+ }
219
+ /**
220
+ * Reload `this.data` from disk when `forceReload` is set. Shared preamble of
221
+ * every `loadX(forceReload)` accessor.
222
+ * @param {boolean} [forceReload=false]
223
+ * @private
224
+ */
225
+ _ensureLoaded(forceReload = false) {
226
+ if (forceReload)
227
+ this._reload();
228
+ }
211
229
  /**
212
230
  * Reads and parses a JSON file.
213
231
  * @param {string} filePath - The path to the file.
@@ -252,7 +270,7 @@ class AccountOrders {
252
270
  return;
253
271
  await this._persistenceLock.acquire(async () => {
254
272
  // Reload from disk to ensure we have the latest state
255
- this.data = this._loadData() || emptyData();
273
+ this._reload();
256
274
  const cfg = botConfig;
257
275
  const newMeta = this._buildMeta(botConfig, this.botKey, typeof cfg.botIndex === 'number' ? cfg.botIndex : 0, this.data.meta);
258
276
  const prevMeta = this.data.meta;
@@ -321,11 +339,11 @@ class AccountOrders {
321
339
  * @param {Object|null} recentFillKeys - Optional fill key dedup snapshot for crash recovery
322
340
  * @param {Object|null} genesis - Optional frozen genesis (priceLevels etc)
323
341
  */
324
- async storeMasterGrid(orders = [], btsFeesOwed = null, boundaryIdx = null, assets = null, debugInputs = null, recentFillKeys = null, genesis = null, gapEvacStreaks = undefined, pendingFillCrawls = undefined, lastFillPivot = undefined) {
342
+ async storeMasterGrid(orders = [], btsFeesOwed = null, boundaryIdx = null, assets = null, debugInputs = null, recentFillKeys = null, genesis = null, gapEvacStreaks = undefined, pendingFillCrawls = undefined, lastFillPivot = undefined, lastMarketFill = undefined) {
325
343
  // Use AsyncLock to serialize read-modify-write operations
326
344
  await this._persistenceLock.acquire(async () => {
327
345
  // Reload from disk before writing to prevent race conditions
328
- this.data = this._loadData() || emptyData();
346
+ this._reload();
329
347
  const snapshot = Array.isArray(orders) ? orders.map((order) => this._serializeOrder(order)) : [];
330
348
  const debugSnapshot = debugInputs ? cloneForDebug(debugInputs) : null;
331
349
  this.data.grid = snapshot;
@@ -424,6 +442,26 @@ class AccountOrders {
424
442
  }
425
443
  }
426
444
  }
445
+ // Bot-scoped last-market-fill reference. Same absent-value contract as
446
+ // lastFillPivot above: undefined is a legacy no-op, null clears, a
447
+ // validated row is written, any other malformed shape clears (never
448
+ // store a stale row). The difference from the pivot is lifetime only —
449
+ // clearGrid() deliberately preserves this row, so it survives a grid
450
+ // regeneration instead of being bound to one generation.
451
+ if (lastMarketFill !== undefined) {
452
+ if (lastMarketFill === null) {
453
+ delete this.data.lastMarketFill;
454
+ }
455
+ else {
456
+ const normalized = normalizeLastMarketFill(lastMarketFill);
457
+ if (normalized) {
458
+ this.data.lastMarketFill = normalized;
459
+ }
460
+ else {
461
+ delete this.data.lastMarketFill;
462
+ }
463
+ }
464
+ }
427
465
  const timestamp = nowIso();
428
466
  this.data.lastUpdated = timestamp;
429
467
  if (this.data.meta)
@@ -443,7 +481,7 @@ class AccountOrders {
443
481
  */
444
482
  async clearPersistedBoundary() {
445
483
  await this._persistenceLock.acquire(async () => {
446
- this.data = this._loadData() || emptyData();
484
+ this._reload();
447
485
  this.data.boundaryIdx = null;
448
486
  this._persist();
449
487
  });
@@ -461,7 +499,7 @@ class AccountOrders {
461
499
  */
462
500
  async clearPersistedLastFillPivot() {
463
501
  await this._persistenceLock.acquire(async () => {
464
- this.data = this._loadData() || emptyData();
502
+ this._reload();
465
503
  delete this.data.lastFillPivot;
466
504
  this.data.lastUpdated = nowIso();
467
505
  this._persist();
@@ -473,9 +511,7 @@ class AccountOrders {
473
511
  * @returns {Array|null} Order grid array or null if not found
474
512
  */
475
513
  loadGrid(forceReload = false) {
476
- if (forceReload) {
477
- this.data = this._loadData() || emptyData();
478
- }
514
+ this._ensureLoaded(forceReload);
479
515
  return (this.data && Array.isArray(this.data.grid)) ? this.data.grid : null;
480
516
  }
481
517
  /**
@@ -496,9 +532,7 @@ class AccountOrders {
496
532
  * @returns {Object|null} The genesis object, or null when absent/invalid
497
533
  */
498
534
  loadGenesis(forceReload = false) {
499
- if (forceReload) {
500
- this.data = this._loadData() || emptyData();
501
- }
535
+ this._ensureLoaded(forceReload);
502
536
  const genesis = this.data?.genesis;
503
537
  // Same predicate as loadGrid/genesis_policy: one definition of "usable
504
538
  // ladder", so the schema gate cannot diverge from the load-time gate.
@@ -531,31 +565,73 @@ class AccountOrders {
531
565
  * @returns {Object|null} {slotId: count} map or null when absent
532
566
  */
533
567
  loadGapEvacStreaks(forceReload = false) {
534
- if (forceReload) {
535
- this.data = this._loadData() || emptyData();
536
- }
568
+ this._ensureLoaded(forceReload);
537
569
  if (this.data && this.data.gapEvacStreaks && typeof this.data.gapEvacStreaks === 'object') {
538
570
  return this.data.gapEvacStreaks;
539
571
  }
540
572
  return null;
541
573
  }
542
574
  loadLastFillPivot(forceReload = false) {
543
- if (forceReload) {
544
- this.data = this._loadData() || emptyData();
545
- }
575
+ this._ensureLoaded(forceReload);
546
576
  // Shared row gate (normalizeLastFillPivot): identical validation to the
547
577
  // storeMasterGrid sanitizer, one shape contract for the whole ledger.
548
578
  return normalizeLastFillPivot(this.data && this.data.lastFillPivot);
549
579
  }
580
+ /**
581
+ * Load the persisted bot-scoped last-market-fill reference.
582
+ * @param {boolean} forceReload - If true, reload from disk
583
+ * @returns {Object|null} {price, type, fillsAt} or null when absent/invalid
584
+ */
585
+ loadLastMarketFill(forceReload = false) {
586
+ this._ensureLoaded(forceReload);
587
+ return normalizeLastMarketFill(this.data && this.data.lastMarketFill);
588
+ }
589
+ /**
590
+ * Erase a persisted last-market-fill row that restoreLastMarketFill
591
+ * rejected (TTL expiry / malformed). Mirrors clearPersistedLastFillPivot:
592
+ * without an explicit erase a dead row would re-arm the same rejection on
593
+ * every restart. Load-time only.
594
+ */
595
+ async clearPersistedLastMarketFill() {
596
+ await this._persistenceLock.acquire(async () => {
597
+ this._reload();
598
+ delete this.data.lastMarketFill;
599
+ this.data.lastUpdated = nowIso();
600
+ this._persist();
601
+ });
602
+ }
603
+ /**
604
+ * Copy the on-disk snapshot to a timestamped sibling file before a
605
+ * destructive operation (snapshot rejection / regeneration). The reason tag
606
+ * is sanitized into the suffix: `<profile>.rejected-drift-<ts>`. Owns the
607
+ * path/storage knowledge so callers never reach through to the filesystem.
608
+ * @param {string} [reason='backup'] - Reason tag for the filename
609
+ * @returns {Promise<string|null>} Backup path, or null when absent/failed
610
+ */
611
+ async backupSnapshot(reason = 'backup') {
612
+ return await this._persistenceLock.acquire(async () => {
613
+ try {
614
+ if (!storage.exists(this.profilesPath))
615
+ return null;
616
+ const ts = new Date().toISOString().replace(/[:.]/g, '-');
617
+ const tag = String(reason).toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '') || 'backup';
618
+ const backupPath = `${this.profilesPath}.${tag}-${ts}`;
619
+ const snapshot = storage.readJSON(this.profilesPath);
620
+ storage.writeJSON(backupPath, snapshot, { fsync: true });
621
+ return backupPath;
622
+ }
623
+ catch {
624
+ return null;
625
+ }
626
+ });
627
+ }
550
628
  /**
551
629
  * Load persisted pending fill crawls for this bot.
552
630
  * @param {boolean} forceReload - If true, reload from disk
553
631
  * @returns {Array} Sanitized pending crawl entries (possibly empty)
554
632
  */
555
633
  loadPendingFillCrawls(forceReload = false) {
556
- if (forceReload) {
557
- this.data = this._loadData() || emptyData();
558
- }
634
+ this._ensureLoaded(forceReload);
559
635
  const out = [];
560
636
  const stored = this.data && this.data.pendingFillCrawls;
561
637
  if (Array.isArray(stored)) {
@@ -574,9 +650,7 @@ class AccountOrders {
574
650
  * @returns {Object|null} Recent fill keys map or null if not found
575
651
  */
576
652
  loadRecentFillKeys(forceReload = false) {
577
- if (forceReload) {
578
- this.data = this._loadData() || emptyData();
579
- }
653
+ this._ensureLoaded(forceReload);
580
654
  if (this.data && this.data.recentFillKeys) {
581
655
  return this.data.recentFillKeys;
582
656
  }
@@ -588,9 +662,7 @@ class AccountOrders {
588
662
  * @returns {Object|null} Asset metadata { assetA, assetB } or null if not found
589
663
  */
590
664
  loadPersistedAssets(forceReload = false) {
591
- if (forceReload) {
592
- this.data = this._loadData() || emptyData();
593
- }
665
+ this._ensureLoaded(forceReload);
594
666
  if (this.data && this.data.assets) {
595
667
  return this.data.assets;
596
668
  }
@@ -602,9 +674,7 @@ class AccountOrders {
602
674
  * @returns {number|null} Boundary index or null if not found
603
675
  */
604
676
  loadBoundaryIdx(forceReload = false) {
605
- if (forceReload) {
606
- this.data = this._loadData() || emptyData();
607
- }
677
+ this._ensureLoaded(forceReload);
608
678
  if (this.data) {
609
679
  const idx = this.data.boundaryIdx;
610
680
  if (typeof idx === 'number' && Number.isFinite(idx)) {
@@ -619,9 +689,7 @@ class AccountOrders {
619
689
  * @returns {Object|null} BTS balance { free, total, locked } or null if not found
620
690
  */
621
691
  loadBtsBalance(forceReload = false) {
622
- if (forceReload) {
623
- this.data = this._loadData() || emptyData();
624
- }
692
+ this._ensureLoaded(forceReload);
625
693
  if (this.data && this.data.btsBalance && typeof this.data.btsBalance === 'object') {
626
694
  return this.data.btsBalance;
627
695
  }
@@ -635,9 +703,7 @@ class AccountOrders {
635
703
  * @returns {number} BTS fees owed or 0 if not found
636
704
  */
637
705
  loadBtsFeesOwed(forceReload = false) {
638
- if (forceReload) {
639
- this.data = this._loadData() || emptyData();
640
- }
706
+ this._ensureLoaded(forceReload);
641
707
  if (this.data) {
642
708
  const fees = this.data.btsFeesOwed;
643
709
  if (typeof fees === 'number' && Number.isFinite(fees)) {
@@ -652,7 +718,7 @@ class AccountOrders {
652
718
  */
653
719
  async clearGrid() {
654
720
  return await this._persistenceLock.acquire(async () => {
655
- this.data = this._loadData() || emptyData();
721
+ this._reload();
656
722
  this.data.grid = [];
657
723
  this.data.btsFeesOwed = 0;
658
724
  this.data.boundaryIdx = null;
@@ -664,6 +730,9 @@ class AccountOrders {
664
730
  // generation (its slot ids and genesis): a rebuilt grid must re-arm on
665
731
  // a fresh fill, not inherit a pivot validated against wiped geometry.
666
732
  delete this.data.lastFillPivot;
733
+ // The bot-scoped last-market-fill reference is DELIBERATELY preserved:
734
+ // it records the last price the ACCOUNT traded at, not grid geometry, so
735
+ // a rebuilt grid still must not trade through it. (TTL applied on restore.)
667
736
  this.data.lastUpdated = nowIso();
668
737
  this._persist();
669
738
  return true;
@@ -680,9 +749,7 @@ class AccountOrders {
680
749
  const minTimestamp = typeof options === 'object' && options !== null && Number.isFinite(options.minTimestamp)
681
750
  ? options.minTimestamp
682
751
  : null;
683
- if (forceReload) {
684
- this.data = this._loadData() || emptyData();
685
- }
752
+ this._ensureLoaded(forceReload);
686
753
  if (this.data) {
687
754
  const fills = this.data.processedFills || {};
688
755
  const entries = Object.entries(fills).filter(([, timestamp]) => minTimestamp == null || (Number.isFinite(timestamp) && timestamp >= minTimestamp));
@@ -698,7 +765,7 @@ class AccountOrders {
698
765
  if (!(fills instanceof Map) || fills.size === 0)
699
766
  return;
700
767
  await this._persistenceLock.acquire(async () => {
701
- this.data = this._loadData() || emptyData();
768
+ this._reload();
702
769
  if (!this.data.processedFills) {
703
770
  this.data.processedFills = {};
704
771
  }
@@ -725,7 +792,7 @@ class AccountOrders {
725
792
  async cleanOldProcessedFills(olderThanMs = 3600000) {
726
793
  // Default: 1 hour (3600000ms)
727
794
  await this._persistenceLock.acquire(async () => {
728
- this.data = this._loadData() || emptyData();
795
+ this._reload();
729
796
  if (!this.data.processedFills) {
730
797
  return;
731
798
  }
@@ -751,9 +818,7 @@ class AccountOrders {
751
818
  * @returns {Object|null} Balance summary or null if no data
752
819
  */
753
820
  getAssetBalances(forceReload = false) {
754
- if (forceReload) {
755
- this.data = this._loadData() || emptyData();
756
- }
821
+ this._ensureLoaded(forceReload);
757
822
  if (!this.data)
758
823
  return null;
759
824
  const meta = this.data.meta || {};
@@ -26,7 +26,7 @@ interface ChainConfig {
26
26
  * again, but a recovery attempt is in flight/recent.
27
27
  * - `unavailable` no live socket to tear down, so no recovery attempt exists.
28
28
  */
29
- export type ForcedReconnectOutcome = 'issued' | 'coalesced' | 'unavailable';
29
+ type ForcedReconnectOutcome = 'issued' | 'coalesced' | 'unavailable';
30
30
  declare function createChainClient(config?: ChainClientConfig): {
31
31
  transport: {
32
32
  connect: (servers?: string[], autoReconnect?: boolean) => Promise<void>;
@@ -265,15 +265,16 @@ function createChainClient(config = {}) {
265
265
  function noteStaleApiError(apiName) {
266
266
  staleApiEscalation.note(apiName);
267
267
  }
268
- async function dbCall(method, args) {
269
- return callWithApiRecovery('database', toRpcMethodName(method), args || [], () => _dbApiId, (id) => { _dbApiId = id; });
270
- }
271
- async function historyCall(method, args) {
272
- return callWithApiRecovery('history', toRpcMethodName(method), args || [], () => _historyApiId, (id) => { _historyApiId = id; });
273
- }
274
- async function broadcastCall(method, args) {
275
- return callWithApiRecovery('network_broadcast', method, args || [], () => _broadcastApiId, (id) => { _broadcastApiId = id; });
268
+ /**
269
+ * Bind a login_api namespace to its cached api-id slot. Centralizes the
270
+ * `callWithApiRecovery` wiring shared by dbCall/historyCall/broadcastCall.
271
+ */
272
+ function apiCaller(apiName, normalizeMethod, getApiId, setApiId) {
273
+ return (method, args) => callWithApiRecovery(apiName, normalizeMethod(method), args || [], getApiId, setApiId);
276
274
  }
275
+ const dbCall = apiCaller('database', toRpcMethodName, () => _dbApiId, (id) => { _dbApiId = id; });
276
+ const historyCall = apiCaller('history', toRpcMethodName, () => _historyApiId, (id) => { _historyApiId = id; });
277
+ const broadcastCall = apiCaller('network_broadcast', (method) => method, () => _broadcastApiId, (id) => { _broadcastApiId = id; });
277
278
  async function broadcastTx(signedTx) {
278
279
  return broadcastCall('broadcast_transaction', [signedTx]);
279
280
  }
@@ -464,12 +465,12 @@ function createReadOnlyClient(config = {}) {
464
465
  function noteStaleApiError() {
465
466
  staleApiEscalation.note();
466
467
  }
467
- async function db(method, args) {
468
- return callWithRecovery(toRpcMethodName(method), args || [], () => _dbApiId, (id) => { _dbApiId = id; });
469
- }
470
- async function history(method, args) {
471
- return callWithRecovery(toRpcMethodName(method), args || [], () => _historyApiId, (id) => { _historyApiId = id; });
468
+ /** Read-channel caller: wraps `callWithRecovery` for a bound api-id slot. */
469
+ function recoveredCaller(getApiId, setApiId) {
470
+ return (method, args) => callWithRecovery(toRpcMethodName(method), args || [], getApiId, setApiId);
472
471
  }
472
+ const db = recoveredCaller(() => _dbApiId, (id) => { _dbApiId = id; });
473
+ const history = recoveredCaller(() => _historyApiId, (id) => { _historyApiId = id; });
473
474
  function setNodes(servers) {
474
475
  transport._setNodes(servers);
475
476
  }
@@ -1,4 +1,3 @@
1
- declare function equalsBytes(a: Uint8Array, b: Uint8Array): boolean;
2
1
  declare function isValidPrivateKeyBytes(rawKey: Uint8Array): boolean;
3
2
  /**
4
3
  * Recover the compressed public key for a signature component (r, s) and a
@@ -29,5 +28,5 @@ declare function wifDecodePayload(payload: Uint8Array): {
29
28
  privateKey: Uint8Array;
30
29
  compressed: boolean;
31
30
  };
32
- export { equalsBytes, isValidPrivateKeyBytes, recoverPublicKeyBytes, verifyBytes, buildSignatureFromK, buildPublicKeyDer, buildSignatureDer, wifDecodePayload, };
31
+ export { isValidPrivateKeyBytes, recoverPublicKeyBytes, verifyBytes, buildSignatureFromK, buildPublicKeyDer, buildSignatureDer, wifDecodePayload, };
33
32
  //# sourceMappingURL=ecc_core.d.ts.map
@@ -209,5 +209,5 @@ function wifDecodePayload(payload) {
209
209
  }
210
210
  return { privateKey, compressed };
211
211
  }
212
- export { equalsBytes, isValidPrivateKeyBytes, recoverPublicKeyBytes, verifyBytes, buildSignatureFromK, buildPublicKeyDer, buildSignatureDer, wifDecodePayload, };
212
+ export { isValidPrivateKeyBytes, recoverPublicKeyBytes, verifyBytes, buildSignatureFromK, buildPublicKeyDer, buildSignatureDer, wifDecodePayload, };
213
213
  //# sourceMappingURL=ecc_core.js.map
@@ -73,37 +73,34 @@ function createResolvers(chainClient) {
73
73
  throw err;
74
74
  }
75
75
  }
76
- async function resolveAccountId(name) {
77
- if (!name)
78
- throw new Error('account name required');
79
- if (/^1\.2\./.test(String(name)))
80
- return name;
81
- const cacheKey = `id:${name}`;
76
+ /**
77
+ * Resolve an account reference to the requested field, caching through
78
+ * `accountIdCache`. `direction` selects the returned field ('id' or
79
+ * 'name'); a reference already shaped as the target is returned untouched.
80
+ */
81
+ async function resolveAccountField(ref, direction) {
82
+ if (!ref)
83
+ throw new Error(`account ${direction === 'id' ? 'name' : 'id'} required`);
84
+ const isChainId = /^1\.2\./.test(String(ref));
85
+ if (direction === 'id' ? isChainId : !isChainId)
86
+ return ref;
87
+ const cacheKey = `${direction}:${ref}`;
82
88
  const cached = accountIdCache.get(cacheKey);
83
89
  if (cached)
84
90
  return cached;
85
- const account = await resolveAccount(name);
86
- if (account && account.id) {
87
- accountIdCache.set(cacheKey, account.id);
88
- return account.id;
91
+ const account = await resolveAccount(ref);
92
+ const result = direction === 'id' ? account?.id : account?.name;
93
+ if (result) {
94
+ accountIdCache.set(cacheKey, result);
95
+ return result;
89
96
  }
90
- throw new Error(`Could not resolve account ID for: ${name}`);
97
+ throw new Error(`Could not resolve account ${direction === 'id' ? 'ID' : 'name'} for: ${ref}`);
98
+ }
99
+ async function resolveAccountId(name) {
100
+ return resolveAccountField(name, 'id');
91
101
  }
92
102
  async function resolveAccountName(id) {
93
- if (!id)
94
- throw new Error('account id required');
95
- if (!/^1\.2\./.test(String(id)))
96
- return id;
97
- const cacheKey = `name:${id}`;
98
- const cached = accountIdCache.get(cacheKey);
99
- if (cached)
100
- return cached;
101
- const account = await resolveAccount(id);
102
- if (account && account.name) {
103
- accountIdCache.set(cacheKey, account.name);
104
- return account.name;
105
- }
106
- throw new Error(`Could not resolve account name for: ${id}`);
103
+ return resolveAccountField(id, 'name');
107
104
  }
108
105
  function invalidateAsset(assetId) {
109
106
  const cached = assetCache.get(`asset:${assetId}`);
@@ -1,7 +1,6 @@
1
1
  declare const GRAPHENE_BLOCKCHAIN_PRECISION: number;
2
2
  declare const GRAPHENE_ADDRESS_PREFIX: string;
3
3
  declare const GRAPHENE_CHAIN_ID: string;
4
- declare const GRAPHENE_100_PERCENT: number;
5
4
  declare const OP_LIMIT_ORDER_CREATE: number;
6
5
  declare const OP_LIMIT_ORDER_CANCEL: number;
7
6
  declare const OP_FILL_ORDER: number;
@@ -35,5 +34,5 @@ declare const OBJECT_TYPE: {
35
34
  credit_offer: number;
36
35
  credit_deal: number;
37
36
  };
38
- export { GRAPHENE_BLOCKCHAIN_PRECISION, GRAPHENE_ADDRESS_PREFIX, GRAPHENE_CHAIN_ID, GRAPHENE_100_PERCENT, OP_LIMIT_ORDER_CREATE, OP_LIMIT_ORDER_CANCEL, OP_FILL_ORDER, RESERVED_SPACES, OBJECT_TYPE };
37
+ export { GRAPHENE_BLOCKCHAIN_PRECISION, GRAPHENE_ADDRESS_PREFIX, GRAPHENE_CHAIN_ID, OP_LIMIT_ORDER_CREATE, OP_LIMIT_ORDER_CANCEL, OP_FILL_ORDER, RESERVED_SPACES, OBJECT_TYPE };
39
38
  //# sourceMappingURL=chain_constants.d.ts.map
@@ -4,7 +4,6 @@ const { CHAIN, OPERATIONS } = NATIVE_CLIENT;
4
4
  const GRAPHENE_BLOCKCHAIN_PRECISION = CHAIN.PRECISION;
5
5
  const GRAPHENE_ADDRESS_PREFIX = CHAIN.ADDRESS_PREFIX;
6
6
  const GRAPHENE_CHAIN_ID = CHAIN.CHAIN_ID;
7
- const GRAPHENE_100_PERCENT = CHAIN.PERCENT_100;
8
7
  const OP_LIMIT_ORDER_CREATE = OPERATIONS.LIMIT_ORDER_CREATE;
9
8
  const OP_LIMIT_ORDER_CANCEL = OPERATIONS.LIMIT_ORDER_CANCEL;
10
9
  const OP_FILL_ORDER = OPERATIONS.FILL_ORDER;
@@ -38,5 +37,5 @@ const OBJECT_TYPE = {
38
37
  credit_offer: 21,
39
38
  credit_deal: 22,
40
39
  };
41
- export { GRAPHENE_BLOCKCHAIN_PRECISION, GRAPHENE_ADDRESS_PREFIX, GRAPHENE_CHAIN_ID, GRAPHENE_100_PERCENT, OP_LIMIT_ORDER_CREATE, OP_LIMIT_ORDER_CANCEL, OP_FILL_ORDER, RESERVED_SPACES, OBJECT_TYPE };
40
+ export { GRAPHENE_BLOCKCHAIN_PRECISION, GRAPHENE_ADDRESS_PREFIX, GRAPHENE_CHAIN_ID, OP_LIMIT_ORDER_CREATE, OP_LIMIT_ORDER_CANCEL, OP_FILL_ORDER, RESERVED_SPACES, OBJECT_TYPE };
42
41
  //# sourceMappingURL=chain_constants.js.map