dexbot 1.6.13 → 1.6.15

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 (114) hide show
  1. package/CHANGELOG.md +66 -4
  2. package/README.md +2 -2
  3. package/analysis/README.md +6 -6
  4. package/analysis/tradingview/README.md +2 -1
  5. package/claw/README.md +7 -7
  6. package/claw/docs/AI_BOT_LIBRARY_API.md +1 -1
  7. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  8. package/claw/modules/claw_catalog.ts +8 -4
  9. package/claw/modules/dexbot_profiles.ts +59 -15
  10. package/claw/modules/types.ts +2 -1
  11. package/claw/package.json +1 -1
  12. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  13. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  14. package/claw/skills/margin-trading/SKILL.md +1 -1
  15. package/claw/skills/margin-trading/references/position-management.md +1 -1
  16. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +105 -31
  17. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +36 -2
  18. package/dist/dexbot.js +23 -3
  19. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
  20. package/dist/modules/account_bots.d.ts +10 -6
  21. package/dist/modules/account_bots.js +13 -10
  22. package/dist/modules/account_orders.d.ts +36 -4
  23. package/dist/modules/account_orders.js +76 -5
  24. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  25. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  26. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  27. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  28. package/dist/modules/bitshares-native/subscriptions.js +1 -1
  29. package/dist/modules/bot_defaults.d.ts +29 -4
  30. package/dist/modules/bot_defaults.js +65 -10
  31. package/dist/modules/bot_settings.d.ts +4 -0
  32. package/dist/modules/bot_settings.js +58 -21
  33. package/dist/modules/config.js +6 -1
  34. package/dist/modules/constants.d.ts +13 -5
  35. package/dist/modules/constants.js +36 -5
  36. package/dist/modules/credit_runtime.d.ts +35 -5
  37. package/dist/modules/credit_runtime.js +219 -38
  38. package/dist/modules/dexbot_class.d.ts +23 -0
  39. package/dist/modules/dexbot_class.js +60 -17
  40. package/dist/modules/dexbot_cow_runtime.d.ts +62 -174
  41. package/dist/modules/dexbot_cow_runtime.js +350 -64
  42. package/dist/modules/dexbot_credential_client.d.ts +1 -16
  43. package/dist/modules/dexbot_credential_client.js +1 -1
  44. package/dist/modules/dexbot_fill_runtime.d.ts +2 -2
  45. package/dist/modules/dexbot_fill_runtime.js +16 -8
  46. package/dist/modules/dexbot_maintenance_runtime.d.ts +24 -81
  47. package/dist/modules/dexbot_maintenance_runtime.js +104 -70
  48. package/dist/modules/dexbot_startup_runtime.js +15 -2
  49. package/dist/modules/dexbot_state_recovery.js +17 -1
  50. package/dist/modules/key_store.d.ts +0 -5
  51. package/dist/modules/key_store.js +1 -1
  52. package/dist/modules/order/accounting.js +11 -11
  53. package/dist/modules/order/export.js +4 -4
  54. package/dist/modules/order/format.d.ts +15 -1
  55. package/dist/modules/order/format.js +19 -1
  56. package/dist/modules/order/genesis_policy.d.ts +1 -1
  57. package/dist/modules/order/genesis_policy.js +1 -1
  58. package/dist/modules/order/grid.d.ts +141 -12
  59. package/dist/modules/order/grid.js +666 -92
  60. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  61. package/dist/modules/order/grid_reconcile.js +9 -8
  62. package/dist/modules/order/grid_reconcile_internal.js +61 -58
  63. package/dist/modules/order/index.d.ts +37 -9
  64. package/dist/modules/order/logger.js +2 -2
  65. package/dist/modules/order/manager.d.ts +10 -2
  66. package/dist/modules/order/manager.js +56 -31
  67. package/dist/modules/order/strategy.d.ts +2 -2
  68. package/dist/modules/order/strategy.js +51 -21
  69. package/dist/modules/order/sync_engine.js +22 -9
  70. package/dist/modules/order/utils/math.d.ts +101 -29
  71. package/dist/modules/order/utils/math.js +215 -84
  72. package/dist/modules/order/utils/order.d.ts +58 -58
  73. package/dist/modules/order/utils/order.js +135 -106
  74. package/dist/modules/order/utils/system.d.ts +193 -6
  75. package/dist/modules/order/utils/system.js +394 -31
  76. package/dist/modules/order/utils/validate.d.ts +1 -1
  77. package/dist/modules/order/utils/validate.js +71 -59
  78. package/dist/modules/runtime_settings.d.ts +1 -1
  79. package/dist/modules/runtime_settings.js +3 -3
  80. package/dist/modules/types.d.ts +55 -4
  81. package/dist/scripts/analyze-credit.js +44 -27
  82. package/dist/scripts/analyze-orders.d.ts +1 -1
  83. package/dist/scripts/analyze-orders.js +4 -4
  84. package/dist/scripts/diagnose-pool-history.js +35 -30
  85. package/dist/scripts/divergence-calc.js +6 -6
  86. package/dist/scripts/pnl.js +1 -1
  87. package/dist/scripts/rich_list.d.ts +18 -0
  88. package/dist/scripts/rich_list.js +461 -0
  89. package/dist/scripts/run-tests.js +80 -4
  90. package/dist/scripts/validate_bots.d.ts +1 -1
  91. package/dist/scripts/validate_bots.js +3 -3
  92. package/dist/unlock.d.ts +2 -1
  93. package/dist/unlock.js +11 -5
  94. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -2
  95. package/docs/COW_INVARIANTS.md +12 -6
  96. package/docs/DEXBOT_COMPARISON.md +7 -7
  97. package/docs/EVOLUTION.md +10 -8
  98. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  99. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  100. package/docs/GRID_RECALCULATION.md +4 -1
  101. package/docs/GRID_RECONCILE.md +4 -4
  102. package/docs/LIFECYCLE.md +11 -11
  103. package/docs/LOGGING.md +30 -1
  104. package/docs/MPA_CREDIT_USAGE.md +11 -6
  105. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +170 -12
  106. package/docs/README.md +3 -3
  107. package/docs/WORKFLOW.md +1 -0
  108. package/docs/architecture.md +62 -8
  109. package/docs/developer_guide.md +12 -3
  110. package/market_adapter/README.md +4 -4
  111. package/modules/README.md +1 -1
  112. package/package.json +2 -1
  113. package/scripts/README.md +59 -32
  114. package/tests/README.md +12 -3
@@ -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
@@ -214,7 +220,7 @@ declare class AccountOrders {
214
220
  * @param {Object|null} recentFillKeys - Optional fill key dedup snapshot for crash recovery
215
221
  * @param {Object|null} genesis - Optional frozen genesis (priceLevels etc)
216
222
  */
217
- 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>;
218
224
  /**
219
225
  * Erase a poisoned persisted boundary after GRID-LOAD rejects it with no
220
226
  * safe re-derivation. storeMasterGrid deliberately never writes a null
@@ -279,6 +285,32 @@ declare class AccountOrders {
279
285
  fillsAt: number;
280
286
  genesisHash: string;
281
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>;
282
314
  /**
283
315
  * Load persisted pending fill crawls for this bot.
284
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';
@@ -339,7 +339,7 @@ class AccountOrders {
339
339
  * @param {Object|null} recentFillKeys - Optional fill key dedup snapshot for crash recovery
340
340
  * @param {Object|null} genesis - Optional frozen genesis (priceLevels etc)
341
341
  */
342
- 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) {
343
343
  // Use AsyncLock to serialize read-modify-write operations
344
344
  await this._persistenceLock.acquire(async () => {
345
345
  // Reload from disk before writing to prevent race conditions
@@ -442,6 +442,26 @@ class AccountOrders {
442
442
  }
443
443
  }
444
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
+ }
445
465
  const timestamp = nowIso();
446
466
  this.data.lastUpdated = timestamp;
447
467
  if (this.data.meta)
@@ -557,6 +577,54 @@ class AccountOrders {
557
577
  // storeMasterGrid sanitizer, one shape contract for the whole ledger.
558
578
  return normalizeLastFillPivot(this.data && this.data.lastFillPivot);
559
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
+ }
560
628
  /**
561
629
  * Load persisted pending fill crawls for this bot.
562
630
  * @param {boolean} forceReload - If true, reload from disk
@@ -662,6 +730,9 @@ class AccountOrders {
662
730
  // generation (its slot ids and genesis): a rebuilt grid must re-arm on
663
731
  // a fresh fill, not inherit a pivot validated against wiped geometry.
664
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.)
665
736
  this.data.lastUpdated = nowIso();
666
737
  this._persist();
667
738
  return true;
@@ -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
@@ -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
@@ -1079,7 +1079,7 @@ function createSubscriptionManager(chainClient, overrides = {}) {
1079
1079
  // already armed by handleNotice cursor advances and by
1080
1080
  // resubscribeEntry/resubscribeAll on disconnects. Poll does NOT arm
1081
1081
  // unconditionally — that would turn every 60s tick into a 40-page
1082
- // re-fetch forever (~80 pages/min for bbot9+bbot4). If a gap-recovery
1082
+ // re-fetch forever (~80 pages/min across several tracked accounts). If a gap-recovery
1083
1083
  // fetch previously threw, _gapRecovery stays true and the next poll
1084
1084
  // will run the lookback; otherwise this tick is just a plain >cursor
1085
1085
  // scan with no lookback. Eager gap-recovery scheduled in handleNotice
@@ -18,7 +18,7 @@
18
18
  * Mode rules are pinned by tests/test_bot_defaults_characterization.ts and
19
19
  * tests/test_bot_defaults_parity.ts — update them together with this file.
20
20
  */
21
- import type { UnknownRecord } from './types.js';
21
+ import type { UnknownRecord, BotMetrics } from './types.js';
22
22
  interface SeedOptions {
23
23
  /** Defaults source; omit to use the merged DEFAULT_CONFIG. */
24
24
  defaults?: UnknownRecord;
@@ -27,7 +27,9 @@ interface SeedOptions {
27
27
  * DEFAULT_CONFIG keys the draft seed must NEVER add. Seeding these would change
28
28
  * persisted bots.json bytes for existing bots and pre-satisfy
29
29
  * `validateBotEntry`'s required-key check (assetA/assetB), hiding genuine
30
- * configuration mistakes from the validator.
30
+ * configuration mistakes from the validator. `activeOrders`/`reserveOrders` are
31
+ * legacy aliases migrated to `coreOrders`/`edgeOrders`, kept here so an older
32
+ * general.settings.json that still carries them does not fail the parity guard.
31
33
  */
32
34
  export declare const DRAFT_EXCLUDED_KEYS: string[];
33
35
  /**
@@ -47,14 +49,28 @@ export declare const DRAFT_SEED_ORDER: string[];
47
49
  * @returns {boolean}
48
50
  */
49
51
  export declare function isUnsetGridPrice(value: unknown): boolean;
52
+ /**
53
+ * Legacy bot-config key aliases: `activeOrders` → `coreOrders` and
54
+ * `reserveOrders` → `edgeOrders`. Applied at every read/seed funnel so a
55
+ * pre-rename or hand-edited `bots.json` keeps working: the new key wins when
56
+ * both are present, the legacy key is dropped, and a later save rewrites the
57
+ * entry in canonical form. Mutates and returns the passed object.
58
+ *
59
+ * Must run BEFORE fingerprinting and the live-config allowlist so both see the
60
+ * canonical key (the maintained-key list and the raw-key fingerprint would
61
+ * otherwise miss a legacy entry).
62
+ * @param {Object} data - Bot entry or runtime config.
63
+ * @returns {Object} The same object, aliased in place.
64
+ */
65
+ export declare function migrateLegacyOrderKeys<T extends UnknownRecord>(data: T): T;
50
66
  /**
51
67
  * Editor draft seed (formerly the `normalizeBotDraft` if-chain in
52
68
  * modules/account_bots.ts). Deep-clones the input, then applies defaults:
53
69
  *
54
- * * count objects (`weightDistribution`/`botFunds`/`activeOrders`): falsy
70
+ * * count objects (`weightDistribution`/`botFunds`/`coreOrders`): falsy
55
71
  * input → default clone; truthy input (including partials) kept verbatim —
56
72
  * never deep-filled;
57
- * * `reserveOrders`: number migration / invalid → default (see seedReserveOrders);
73
+ * * `edgeOrders`: number migration / invalid → default (see seedEdgeOrders);
58
74
  * * `startPrice`: undefined → `default || 'pool'` (falsy defaults fall back);
59
75
  * * `gridPrice`: undefined → `DEFAULT_CONFIG.gridPrice` ("ama3" today),
60
76
  * falling back to null only when the default itself is null (Phase 2:
@@ -86,5 +102,14 @@ export declare function seedBotEntry<T extends UnknownRecord>(entry: T, options?
86
102
  * (the historical shallow spread aliased every nested default object).
87
103
  */
88
104
  export declare function seedBotRuntimeConfig(config?: UnknownRecord, options?: SeedOptions): UnknownRecord;
105
+ /**
106
+ * Fresh zeroed metrics for the bot and its order manager. Both layers used to
107
+ * declare the shared counters independently, so a new shared counter had to be
108
+ * added twice (and could drift). The manager spreads this base and adds its own
109
+ * runtime-only counters (lock stats, sync timing, start time); the bot uses it
110
+ * verbatim. Single source of truth for the shared `BotMetrics` defaults.
111
+ * @returns {Object} A new metrics object with every shared counter zeroed
112
+ */
113
+ export declare function createDefaultBotMetrics(): BotMetrics;
89
114
  export {};
90
115
  //# sourceMappingURL=bot_defaults.d.ts.map
@@ -23,9 +23,11 @@ import { DEFAULT_CONFIG } from './constants.js';
23
23
  * DEFAULT_CONFIG keys the draft seed must NEVER add. Seeding these would change
24
24
  * persisted bots.json bytes for existing bots and pre-satisfy
25
25
  * `validateBotEntry`'s required-key check (assetA/assetB), hiding genuine
26
- * configuration mistakes from the validator.
26
+ * configuration mistakes from the validator. `activeOrders`/`reserveOrders` are
27
+ * legacy aliases migrated to `coreOrders`/`edgeOrders`, kept here so an older
28
+ * general.settings.json that still carries them does not fail the parity guard.
27
29
  */
28
- export const DRAFT_EXCLUDED_KEYS = ['assetA', 'assetB', 'creditOnly', 'min_BTS_value'];
30
+ export const DRAFT_EXCLUDED_KEYS = ['assetA', 'assetB', 'creditOnly', 'min_BTS_value', 'activeOrders', 'reserveOrders'];
29
31
  /**
30
32
  * Draft seed order — kept identical to the historical if-chain so a freshly
31
33
  * created bot's JSON key order does not change. Together with
@@ -33,7 +35,7 @@ export const DRAFT_EXCLUDED_KEYS = ['assetA', 'assetB', 'creditOnly', 'min_BTS_v
33
35
  * fails when a new DEFAULT_CONFIG key is added without classifying it here.
34
36
  */
35
37
  export const DRAFT_SEED_ORDER = [
36
- 'weightDistribution', 'botFunds', 'activeOrders', 'reserveOrders',
38
+ 'weightDistribution', 'botFunds', 'coreOrders', 'edgeOrders',
37
39
  'active', 'dryRun', 'minPrice', 'maxPrice', 'incrementPercent',
38
40
  'targetSpreadPercent', 'startPrice', 'gridPrice',
39
41
  ];
@@ -68,10 +70,35 @@ function clone(value) {
68
70
  return value;
69
71
  return JSON.parse(JSON.stringify(value));
70
72
  }
73
+ /**
74
+ * Legacy bot-config key aliases: `activeOrders` → `coreOrders` and
75
+ * `reserveOrders` → `edgeOrders`. Applied at every read/seed funnel so a
76
+ * pre-rename or hand-edited `bots.json` keeps working: the new key wins when
77
+ * both are present, the legacy key is dropped, and a later save rewrites the
78
+ * entry in canonical form. Mutates and returns the passed object.
79
+ *
80
+ * Must run BEFORE fingerprinting and the live-config allowlist so both see the
81
+ * canonical key (the maintained-key list and the raw-key fingerprint would
82
+ * otherwise miss a legacy entry).
83
+ * @param {Object} data - Bot entry or runtime config.
84
+ * @returns {Object} The same object, aliased in place.
85
+ */
86
+ export function migrateLegacyOrderKeys(data) {
87
+ const record = data;
88
+ if (record.coreOrders === undefined && record.activeOrders !== undefined) {
89
+ record.coreOrders = record.activeOrders;
90
+ }
91
+ if (record.edgeOrders === undefined && record.reserveOrders !== undefined) {
92
+ record.edgeOrders = record.reserveOrders;
93
+ }
94
+ delete record.activeOrders;
95
+ delete record.reserveOrders;
96
+ return data;
97
+ }
71
98
  /** Numbers migrate to `{ buy, sell: 0 }` (floored, clamped at 0); anything
72
99
  * that is not a plain object becomes the default; plain objects — including
73
100
  * partial ones — are kept verbatim. */
74
- function seedReserveOrders(value, def) {
101
+ function seedEdgeOrders(value, def) {
75
102
  if (typeof value === 'number') {
76
103
  return { buy: Math.max(0, Math.floor(value)), sell: 0 };
77
104
  }
@@ -84,10 +111,10 @@ function seedReserveOrders(value, def) {
84
111
  * Editor draft seed (formerly the `normalizeBotDraft` if-chain in
85
112
  * modules/account_bots.ts). Deep-clones the input, then applies defaults:
86
113
  *
87
- * * count objects (`weightDistribution`/`botFunds`/`activeOrders`): falsy
114
+ * * count objects (`weightDistribution`/`botFunds`/`coreOrders`): falsy
88
115
  * input → default clone; truthy input (including partials) kept verbatim —
89
116
  * never deep-filled;
90
- * * `reserveOrders`: number migration / invalid → default (see seedReserveOrders);
117
+ * * `edgeOrders`: number migration / invalid → default (see seedEdgeOrders);
91
118
  * * `startPrice`: undefined → `default || 'pool'` (falsy defaults fall back);
92
119
  * * `gridPrice`: undefined → `DEFAULT_CONFIG.gridPrice` ("ama3" today),
93
120
  * falling back to null only when the default itself is null (Phase 2:
@@ -96,11 +123,11 @@ function seedReserveOrders(value, def) {
96
123
  */
97
124
  export function seedBotDraft(base, options = {}) {
98
125
  const defaults = options.defaults ?? DEFAULT_CONFIG;
99
- const data = JSON.parse(JSON.stringify(base ?? {}));
126
+ const data = migrateLegacyOrderKeys(JSON.parse(JSON.stringify(base ?? {})));
100
127
  for (const key of DRAFT_SEED_ORDER) {
101
128
  const def = defaults[key];
102
- if (key === 'reserveOrders') {
103
- data.reserveOrders = seedReserveOrders(data.reserveOrders, def);
129
+ if (key === 'edgeOrders') {
130
+ data.edgeOrders = seedEdgeOrders(data.edgeOrders, def);
104
131
  }
105
132
  else if (key === 'startPrice') {
106
133
  if (data.startPrice === undefined)
@@ -139,7 +166,8 @@ export function seedBotDraft(base, options = {}) {
139
166
  */
140
167
  export function seedBotEntry(entry, options = {}) {
141
168
  const defaults = options.defaults ?? DEFAULT_CONFIG;
142
- return { active: entry.active === undefined ? defaults.active : entry.active, ...entry };
169
+ const data = migrateLegacyOrderKeys({ ...entry });
170
+ return { active: data.active === undefined ? defaults.active : data.active, ...data };
143
171
  }
144
172
  /**
145
173
  * Runtime config seed (formerly `{ ...DEFAULT_CONFIG, ...config }` in the
@@ -162,4 +190,31 @@ export function seedBotRuntimeConfig(config = {}, options = {}) {
162
190
  }
163
191
  return out;
164
192
  }
193
+ /**
194
+ * Fresh zeroed metrics for the bot and its order manager. Both layers used to
195
+ * declare the shared counters independently, so a new shared counter had to be
196
+ * added twice (and could drift). The manager spreads this base and adds its own
197
+ * runtime-only counters (lock stats, sync timing, start time); the bot uses it
198
+ * verbatim. Single source of truth for the shared `BotMetrics` defaults.
199
+ * @returns {Object} A new metrics object with every shared counter zeroed
200
+ */
201
+ export function createDefaultBotMetrics() {
202
+ return {
203
+ fillsProcessed: 0,
204
+ batchesExecuted: 0,
205
+ fillProcessingTimeMs: 0,
206
+ lockContentionEvents: 0,
207
+ maxQueueDepth: 0,
208
+ gridLockContention: 0,
209
+ fundRecalcCount: 0,
210
+ refusedCommitCount: 0,
211
+ orphanFillCreditedCount: 0,
212
+ restampBuyAboveAnchorCount: 0,
213
+ boundaryDriftExceedsWindowCount: 0,
214
+ gapBandPlacementShadowCount: 0,
215
+ spreadCorrectionRefusedCount: 0,
216
+ spreadCorrectionRefusalCauses: {},
217
+ spreadCorrectionRetryCount: 0
218
+ };
219
+ }
165
220
  //# sourceMappingURL=bot_defaults.js.map
@@ -20,7 +20,11 @@ export interface BotEntry extends UnknownRecord {
20
20
  botKey?: string;
21
21
  botIndex?: number;
22
22
  preferredAccount?: string;
23
+ coreOrders?: UnknownRecord;
24
+ edgeOrders?: number | UnknownRecord;
25
+ /** @deprecated legacy key, migrated to `coreOrders` at read time. */
23
26
  activeOrders?: UnknownRecord;
27
+ /** @deprecated legacy key, migrated to `edgeOrders` at read time. */
24
28
  reserveOrders?: number | UnknownRecord;
25
29
  botFunds?: {
26
30
  buy?: unknown;
@@ -1,8 +1,8 @@
1
1
  import { getStorage } from './storage/index.js';
2
- import { readBotsFileSync } from './bots_file_lock.js';
2
+ import { readBotsFileSync, writeJsonFileAtomic } from './bots_file_lock.js';
3
3
  import { parseJsonWithComments } from './order/utils/system.js';
4
4
  import { createBotKey } from './account_orders.js';
5
- import { seedBotEntry } from './bot_defaults.js';
5
+ import { seedBotEntry, migrateLegacyOrderKeys } from './bot_defaults.js';
6
6
  import { isSameBotName } from './utils/sanitize_key.js';
7
7
  import { isPositiveNumber, isPositiveNumberOrPercent, toDecimal } from './order/utils/math.js';
8
8
  import { resolveMinCollateralIncreaseThreshold } from './cr_planner.js';
@@ -20,6 +20,11 @@ function loadSettingsFile(filePath, { silent = false, exitOnError = true } = {})
20
20
  }
21
21
  try {
22
22
  const { config } = readBotsFileSync(filePath, parseJsonWithComments);
23
+ // Upgrade a pre-rename file in place: legacy `activeOrders`/
24
+ // `reserveOrders` keys become `coreOrders`/`edgeOrders` and the file is
25
+ // rewritten in canonical form. Idempotent; a failed write is
26
+ // non-fatal because the in-memory config is already canonical.
27
+ migratePersistedOrderKeys(filePath, config);
23
28
  return { config, filePath };
24
29
  }
25
30
  catch (err) {
@@ -50,6 +55,32 @@ function resolveRawBotEntries(settings) {
50
55
  return [settings];
51
56
  return [];
52
57
  }
58
+ /**
59
+ * Persist the user-settings key upgrade: rewrite bots.json in canonical form
60
+ * when any entry still carries the legacy `activeOrders`/`reserveOrders` keys.
61
+ * Runs at the read funnel so an old file is transparently migrated.
62
+ * @param {string} filePath - bots.json path
63
+ * @param {unknown} config - Parsed bots.json document (mutated in place)
64
+ * @returns {boolean} True when a legacy key was found and upgraded
65
+ */
66
+ function migratePersistedOrderKeys(filePath, config) {
67
+ let changed = false;
68
+ for (const entry of resolveRawBotEntries(config)) {
69
+ if (isUnknownRecord(entry) && ('activeOrders' in entry || 'reserveOrders' in entry)) {
70
+ migrateLegacyOrderKeys(entry);
71
+ changed = true;
72
+ }
73
+ }
74
+ if (changed) {
75
+ try {
76
+ writeJsonFileAtomic(filePath, config);
77
+ }
78
+ catch (err) {
79
+ console.error('Failed to persist upgraded bot settings to', filePath, '-', getErrorMessage(err));
80
+ }
81
+ }
82
+ return changed;
83
+ }
53
84
  function normalizeBotEntry(entry, index = 0) {
54
85
  // active default + raw passthrough live in modules/bot_defaults.ts
55
86
  // (shared with the claw copy — one semantics for both).
@@ -81,40 +112,43 @@ function selectActiveBotEntries(settings) {
81
112
  }
82
113
  function validateBotEntry(b, i, src) {
83
114
  const problems = [];
115
+ // Legacy `activeOrders`/`reserveOrders` keys are accepted and validated
116
+ // under their canonical names so a pre-rename bots.json is not rejected.
117
+ const entry = migrateLegacyOrderKeys({ ...b });
84
118
  const isCreditOnly = b.creditOnly === true;
85
- const required = isCreditOnly ? [] : ['assetA', 'assetB', 'activeOrders', 'botFunds'];
119
+ const required = isCreditOnly ? [] : ['assetA', 'assetB', 'coreOrders', 'botFunds'];
86
120
  for (const k of required) {
87
- if (!(k in b))
121
+ if (!(k in entry))
88
122
  problems.push(`missing '${k}'`);
89
123
  }
90
- if ('activeOrders' in b) {
91
- if (typeof b.activeOrders !== 'object' || b.activeOrders === null)
92
- problems.push("'activeOrders' must be an object");
124
+ if ('coreOrders' in entry) {
125
+ if (typeof entry.coreOrders !== 'object' || entry.coreOrders === null)
126
+ problems.push("'coreOrders' must be an object");
93
127
  else {
94
- if (!('buy' in b.activeOrders))
95
- problems.push("activeOrders missing 'buy'");
96
- if (!('sell' in b.activeOrders))
97
- problems.push("activeOrders missing 'sell'");
128
+ if (!('buy' in entry.coreOrders))
129
+ problems.push("coreOrders missing 'buy'");
130
+ if (!('sell' in entry.coreOrders))
131
+ problems.push("coreOrders missing 'sell'");
98
132
  }
99
133
  }
100
- if ('reserveOrders' in b && b.reserveOrders !== undefined && b.reserveOrders !== null) {
101
- if (typeof b.reserveOrders === 'number') {
102
- // Legacy numeric form migrates at read time (resolveReserveCount):
134
+ if ('edgeOrders' in entry && entry.edgeOrders !== undefined && entry.edgeOrders !== null) {
135
+ if (typeof entry.edgeOrders === 'number') {
136
+ // Legacy numeric form migrates at read time (resolveEdgeCount):
103
137
  // { buy: n, sell: 0 }. Accept it here so a hand-edited bots.json
104
138
  // that bypassed the editor is not rejected for a form the runtime
105
139
  // still understands.
106
- if (!Number.isInteger(b.reserveOrders) || b.reserveOrders < 0)
107
- problems.push("'reserveOrders' numeric form must be a non-negative integer");
140
+ if (!Number.isInteger(entry.edgeOrders) || entry.edgeOrders < 0)
141
+ problems.push("'edgeOrders' numeric form must be a non-negative integer");
108
142
  }
109
- else if (typeof b.reserveOrders !== 'object' || Array.isArray(b.reserveOrders)) {
110
- problems.push("'reserveOrders' must be an object {buy, sell}");
143
+ else if (typeof entry.edgeOrders !== 'object' || Array.isArray(entry.edgeOrders)) {
144
+ problems.push("'edgeOrders' must be an object {buy, sell}");
111
145
  }
112
146
  else {
113
147
  for (const side of ['buy', 'sell']) {
114
- const reserveOrders = b.reserveOrders;
115
- const v = reserveOrders[side];
148
+ const edgeOrders = entry.edgeOrders;
149
+ const v = edgeOrders[side];
116
150
  if (v !== undefined && (!Number.isInteger(Number(v)) || Number(v) < 0))
117
- problems.push(`'reserveOrders.${side}' must be a non-negative integer`);
151
+ problems.push(`'edgeOrders.${side}' must be a non-negative integer`);
118
152
  }
119
153
  }
120
154
  }
@@ -243,6 +277,9 @@ function validateBotEntry(b, i, src) {
243
277
  if ('renewOnly' in item && typeof item.renewOnly !== 'boolean') {
244
278
  problems.push(`debtPolicy.lending[${idx}].renewOnly must be a boolean`);
245
279
  }
280
+ if ('useFreeCollateral' in item && typeof item.useFreeCollateral !== 'boolean') {
281
+ problems.push(`debtPolicy.lending[${idx}].useFreeCollateral must be a boolean`);
282
+ }
246
283
  if ('allowedOfferIds' in item) {
247
284
  if (!Array.isArray(item.allowedOfferIds)) {
248
285
  problems.push(`debtPolicy.lending[${idx}].allowedOfferIds must be an array`);
@@ -120,8 +120,13 @@ function getTxBuilderFeeCacheTtl() {
120
120
  : undefined;
121
121
  }
122
122
  function setUmask(mode) {
123
+ // Worker threads cannot set the process-wide umask, so skip gracefully
124
+ // there (matches Runtime.umask()'s try/catch guard).
123
125
  if (hasProcess()) {
124
- process.umask(mode);
126
+ try {
127
+ process.umask(mode);
128
+ }
129
+ catch { /* not supported in workers */ }
125
130
  }
126
131
  }
127
132
  // Make path-related env keys live (ESM cache not invalidated via require.cache in tests)