dexbot 1.6.13 → 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 (93) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +2 -2
  3. package/claw/docs/AI_BOT_LIBRARY_API.md +1 -1
  4. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  5. package/claw/modules/claw_catalog.ts +8 -4
  6. package/claw/modules/dexbot_profiles.ts +59 -15
  7. package/claw/modules/types.ts +2 -1
  8. package/claw/package.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/claw/skills/margin-trading/SKILL.md +1 -1
  12. package/claw/skills/margin-trading/references/position-management.md +1 -1
  13. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +25 -25
  14. package/dist/modules/account_bots.d.ts +7 -6
  15. package/dist/modules/account_bots.js +10 -10
  16. package/dist/modules/account_orders.d.ts +36 -4
  17. package/dist/modules/account_orders.js +76 -5
  18. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  19. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  20. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  21. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  22. package/dist/modules/bot_defaults.d.ts +16 -2
  23. package/dist/modules/bot_defaults.js +34 -8
  24. package/dist/modules/bot_settings.d.ts +4 -0
  25. package/dist/modules/bot_settings.js +55 -21
  26. package/dist/modules/config.js +6 -1
  27. package/dist/modules/constants.d.ts +7 -5
  28. package/dist/modules/constants.js +12 -5
  29. package/dist/modules/dexbot_class.d.ts +5 -0
  30. package/dist/modules/dexbot_class.js +8 -3
  31. package/dist/modules/dexbot_cow_runtime.d.ts +62 -174
  32. package/dist/modules/dexbot_cow_runtime.js +331 -46
  33. package/dist/modules/dexbot_credential_client.d.ts +1 -16
  34. package/dist/modules/dexbot_credential_client.js +1 -1
  35. package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
  36. package/dist/modules/dexbot_fill_runtime.js +12 -1
  37. package/dist/modules/dexbot_maintenance_runtime.d.ts +18 -80
  38. package/dist/modules/dexbot_maintenance_runtime.js +57 -68
  39. package/dist/modules/dexbot_startup_runtime.js +12 -0
  40. package/dist/modules/dexbot_state_recovery.js +16 -0
  41. package/dist/modules/key_store.d.ts +0 -5
  42. package/dist/modules/key_store.js +1 -1
  43. package/dist/modules/order/accounting.js +11 -11
  44. package/dist/modules/order/export.js +2 -2
  45. package/dist/modules/order/format.d.ts +15 -1
  46. package/dist/modules/order/format.js +19 -1
  47. package/dist/modules/order/genesis_policy.d.ts +1 -1
  48. package/dist/modules/order/genesis_policy.js +1 -1
  49. package/dist/modules/order/grid.d.ts +23 -11
  50. package/dist/modules/order/grid.js +383 -51
  51. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  52. package/dist/modules/order/grid_reconcile.js +5 -5
  53. package/dist/modules/order/grid_reconcile_internal.js +48 -40
  54. package/dist/modules/order/index.d.ts +34 -8
  55. package/dist/modules/order/logger.js +2 -2
  56. package/dist/modules/order/manager.d.ts +9 -2
  57. package/dist/modules/order/manager.js +58 -24
  58. package/dist/modules/order/strategy.d.ts +2 -2
  59. package/dist/modules/order/strategy.js +51 -21
  60. package/dist/modules/order/sync_engine.js +4 -0
  61. package/dist/modules/order/utils/math.d.ts +3 -3
  62. package/dist/modules/order/utils/math.js +38 -27
  63. package/dist/modules/order/utils/order.d.ts +58 -58
  64. package/dist/modules/order/utils/order.js +119 -102
  65. package/dist/modules/order/utils/system.d.ts +193 -6
  66. package/dist/modules/order/utils/system.js +392 -29
  67. package/dist/modules/order/utils/validate.js +26 -4
  68. package/dist/modules/runtime_settings.d.ts +1 -1
  69. package/dist/modules/runtime_settings.js +3 -3
  70. package/dist/modules/types.d.ts +48 -4
  71. package/dist/scripts/analyze-orders.d.ts +1 -1
  72. package/dist/scripts/analyze-orders.js +4 -4
  73. package/dist/scripts/divergence-calc.js +6 -6
  74. package/dist/scripts/validate_bots.d.ts +1 -1
  75. package/dist/scripts/validate_bots.js +3 -3
  76. package/dist/unlock.js +7 -2
  77. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -2
  78. package/docs/COW_INVARIANTS.md +6 -6
  79. package/docs/DEXBOT_COMPARISON.md +5 -5
  80. package/docs/EVOLUTION.md +8 -7
  81. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  82. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  83. package/docs/GRID_RECALCULATION.md +4 -1
  84. package/docs/GRID_RECONCILE.md +4 -4
  85. package/docs/LIFECYCLE.md +11 -11
  86. package/docs/LOGGING.md +14 -0
  87. package/docs/MPA_CREDIT_USAGE.md +1 -1
  88. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +12 -4
  89. package/docs/README.md +3 -3
  90. package/docs/architecture.md +6 -6
  91. package/docs/developer_guide.md +7 -2
  92. package/package.json +1 -1
  93. package/tests/README.md +1 -1
@@ -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
@@ -47,14 +47,28 @@ export declare const DRAFT_SEED_ORDER: string[];
47
47
  * @returns {boolean}
48
48
  */
49
49
  export declare function isUnsetGridPrice(value: unknown): boolean;
50
+ /**
51
+ * Legacy bot-config key aliases: `activeOrders` → `coreOrders` and
52
+ * `reserveOrders` → `edgeOrders`. Applied at every read/seed funnel so a
53
+ * pre-rename or hand-edited `bots.json` keeps working: the new key wins when
54
+ * both are present, the legacy key is dropped, and a later save rewrites the
55
+ * entry in canonical form. Mutates and returns the passed object.
56
+ *
57
+ * Must run BEFORE fingerprinting and the live-config allowlist so both see the
58
+ * canonical key (the maintained-key list and the raw-key fingerprint would
59
+ * otherwise miss a legacy entry).
60
+ * @param {Object} data - Bot entry or runtime config.
61
+ * @returns {Object} The same object, aliased in place.
62
+ */
63
+ export declare function migrateLegacyOrderKeys<T extends UnknownRecord>(data: T): T;
50
64
  /**
51
65
  * Editor draft seed (formerly the `normalizeBotDraft` if-chain in
52
66
  * modules/account_bots.ts). Deep-clones the input, then applies defaults:
53
67
  *
54
- * * count objects (`weightDistribution`/`botFunds`/`activeOrders`): falsy
68
+ * * count objects (`weightDistribution`/`botFunds`/`coreOrders`): falsy
55
69
  * input → default clone; truthy input (including partials) kept verbatim —
56
70
  * never deep-filled;
57
- * * `reserveOrders`: number migration / invalid → default (see seedReserveOrders);
71
+ * * `edgeOrders`: number migration / invalid → default (see seedEdgeOrders);
58
72
  * * `startPrice`: undefined → `default || 'pool'` (falsy defaults fall back);
59
73
  * * `gridPrice`: undefined → `DEFAULT_CONFIG.gridPrice` ("ama3" today),
60
74
  * falling back to null only when the default itself is null (Phase 2:
@@ -33,7 +33,7 @@ export const DRAFT_EXCLUDED_KEYS = ['assetA', 'assetB', 'creditOnly', 'min_BTS_v
33
33
  * fails when a new DEFAULT_CONFIG key is added without classifying it here.
34
34
  */
35
35
  export const DRAFT_SEED_ORDER = [
36
- 'weightDistribution', 'botFunds', 'activeOrders', 'reserveOrders',
36
+ 'weightDistribution', 'botFunds', 'coreOrders', 'edgeOrders',
37
37
  'active', 'dryRun', 'minPrice', 'maxPrice', 'incrementPercent',
38
38
  'targetSpreadPercent', 'startPrice', 'gridPrice',
39
39
  ];
@@ -68,10 +68,35 @@ function clone(value) {
68
68
  return value;
69
69
  return JSON.parse(JSON.stringify(value));
70
70
  }
71
+ /**
72
+ * Legacy bot-config key aliases: `activeOrders` → `coreOrders` and
73
+ * `reserveOrders` → `edgeOrders`. Applied at every read/seed funnel so a
74
+ * pre-rename or hand-edited `bots.json` keeps working: the new key wins when
75
+ * both are present, the legacy key is dropped, and a later save rewrites the
76
+ * entry in canonical form. Mutates and returns the passed object.
77
+ *
78
+ * Must run BEFORE fingerprinting and the live-config allowlist so both see the
79
+ * canonical key (the maintained-key list and the raw-key fingerprint would
80
+ * otherwise miss a legacy entry).
81
+ * @param {Object} data - Bot entry or runtime config.
82
+ * @returns {Object} The same object, aliased in place.
83
+ */
84
+ export function migrateLegacyOrderKeys(data) {
85
+ const record = data;
86
+ if (record.coreOrders === undefined && record.activeOrders !== undefined) {
87
+ record.coreOrders = record.activeOrders;
88
+ }
89
+ if (record.edgeOrders === undefined && record.reserveOrders !== undefined) {
90
+ record.edgeOrders = record.reserveOrders;
91
+ }
92
+ delete record.activeOrders;
93
+ delete record.reserveOrders;
94
+ return data;
95
+ }
71
96
  /** Numbers migrate to `{ buy, sell: 0 }` (floored, clamped at 0); anything
72
97
  * that is not a plain object becomes the default; plain objects — including
73
98
  * partial ones — are kept verbatim. */
74
- function seedReserveOrders(value, def) {
99
+ function seedEdgeOrders(value, def) {
75
100
  if (typeof value === 'number') {
76
101
  return { buy: Math.max(0, Math.floor(value)), sell: 0 };
77
102
  }
@@ -84,10 +109,10 @@ function seedReserveOrders(value, def) {
84
109
  * Editor draft seed (formerly the `normalizeBotDraft` if-chain in
85
110
  * modules/account_bots.ts). Deep-clones the input, then applies defaults:
86
111
  *
87
- * * count objects (`weightDistribution`/`botFunds`/`activeOrders`): falsy
112
+ * * count objects (`weightDistribution`/`botFunds`/`coreOrders`): falsy
88
113
  * input → default clone; truthy input (including partials) kept verbatim —
89
114
  * never deep-filled;
90
- * * `reserveOrders`: number migration / invalid → default (see seedReserveOrders);
115
+ * * `edgeOrders`: number migration / invalid → default (see seedEdgeOrders);
91
116
  * * `startPrice`: undefined → `default || 'pool'` (falsy defaults fall back);
92
117
  * * `gridPrice`: undefined → `DEFAULT_CONFIG.gridPrice` ("ama3" today),
93
118
  * falling back to null only when the default itself is null (Phase 2:
@@ -96,11 +121,11 @@ function seedReserveOrders(value, def) {
96
121
  */
97
122
  export function seedBotDraft(base, options = {}) {
98
123
  const defaults = options.defaults ?? DEFAULT_CONFIG;
99
- const data = JSON.parse(JSON.stringify(base ?? {}));
124
+ const data = migrateLegacyOrderKeys(JSON.parse(JSON.stringify(base ?? {})));
100
125
  for (const key of DRAFT_SEED_ORDER) {
101
126
  const def = defaults[key];
102
- if (key === 'reserveOrders') {
103
- data.reserveOrders = seedReserveOrders(data.reserveOrders, def);
127
+ if (key === 'edgeOrders') {
128
+ data.edgeOrders = seedEdgeOrders(data.edgeOrders, def);
104
129
  }
105
130
  else if (key === 'startPrice') {
106
131
  if (data.startPrice === undefined)
@@ -139,7 +164,8 @@ export function seedBotDraft(base, options = {}) {
139
164
  */
140
165
  export function seedBotEntry(entry, options = {}) {
141
166
  const defaults = options.defaults ?? DEFAULT_CONFIG;
142
- return { active: entry.active === undefined ? defaults.active : entry.active, ...entry };
167
+ const data = migrateLegacyOrderKeys({ ...entry });
168
+ return { active: data.active === undefined ? defaults.active : data.active, ...data };
143
169
  }
144
170
  /**
145
171
  * Runtime config seed (formerly `{ ...DEFAULT_CONFIG, ...config }` in the
@@ -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
  }
@@ -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)
@@ -28,7 +28,7 @@
28
28
  * Price: startPrice, minPrice, maxPrice, incrementPercent, targetSpreadPercent
29
29
  * Control: active, dryRun
30
30
  * Trading pair: assetA, assetB
31
- * Allocation: weightDistribution, botFunds, activeOrders
31
+ * Allocation: weightDistribution, botFunds, coreOrders
32
32
  *
33
33
  * TIMING PARAMETERS:
34
34
  * 4. TIMING - Operational timing constants
@@ -173,11 +173,11 @@ declare let DEFAULT_CONFIG: {
173
173
  sell: string;
174
174
  buy: string;
175
175
  };
176
- activeOrders: {
176
+ coreOrders: {
177
177
  sell: number;
178
178
  buy: number;
179
179
  };
180
- reserveOrders: {
180
+ edgeOrders: {
181
181
  buy: number;
182
182
  sell: number;
183
183
  };
@@ -225,6 +225,7 @@ declare let TIMING: {
225
225
  FILL_TOTALS_RETRY_MAX_MS: number;
226
226
  SPREAD_STALE_WARN_MS: number;
227
227
  SPREAD_STALE_ESCALATE_MS: number;
228
+ SPREAD_CORRECTION_SYNC_FRESH_MS: number;
228
229
  SPREAD_STALE_RESYNC_COOLDOWN_MS: number;
229
230
  BOUNDARY_HOLD_RESYNC_THRESHOLD: number;
230
231
  BOUNDARY_HOLD_RESYNC_COOLDOWN_MS: number;
@@ -764,6 +765,7 @@ declare function buildDefaultGeneralSettings(): {
764
765
  FILL_TOTALS_RETRY_MAX_MS: number;
765
766
  SPREAD_STALE_WARN_MS: number;
766
767
  SPREAD_STALE_ESCALATE_MS: number;
768
+ SPREAD_CORRECTION_SYNC_FRESH_MS: number;
767
769
  SPREAD_STALE_RESYNC_COOLDOWN_MS: number;
768
770
  BOUNDARY_HOLD_RESYNC_THRESHOLD: number;
769
771
  BOUNDARY_HOLD_RESYNC_COOLDOWN_MS: number;
@@ -986,11 +988,11 @@ declare function buildDefaultGeneralSettings(): {
986
988
  sell: string;
987
989
  buy: string;
988
990
  };
989
- activeOrders: {
991
+ coreOrders: {
990
992
  sell: number;
991
993
  buy: number;
992
994
  };
993
- reserveOrders: {
995
+ edgeOrders: {
994
996
  buy: number;
995
997
  sell: number;
996
998
  };
@@ -29,7 +29,7 @@
29
29
  * Price: startPrice, minPrice, maxPrice, incrementPercent, targetSpreadPercent
30
30
  * Control: active, dryRun
31
31
  * Trading pair: assetA, assetB
32
- * Allocation: weightDistribution, botFunds, activeOrders
32
+ * Allocation: weightDistribution, botFunds, coreOrders
33
33
  *
34
34
  * TIMING PARAMETERS:
35
35
  * 4. TIMING - Operational timing constants
@@ -196,10 +196,10 @@ let DEFAULT_CONFIG = {
196
196
  // Fund allocation
197
197
  weightDistribution: { sell: 1, buy: 1 }, // Geometric weight for order sizing (1 = ~1:2 center/outer split, 0.5 = linear)
198
198
  botFunds: { sell: "100%", buy: "100%" }, // Percentage of wallet balance to allocate ("100%" or numeric value)
199
- activeOrders: { sell: 20, buy: 20 }, // Number of orders to maintain closest to market on each side
200
- reserveOrders: { buy: 0, sell: 0 }, // Edge-pinned insurance orders resting live outside the window (buy: grid floor, sell: grid ceiling; 0 disables)
199
+ coreOrders: { sell: 20, buy: 20 }, // Number of window orders to maintain closest to market on each side
200
+ edgeOrders: { buy: 0, sell: 0 }, // Edge-pinned insurance orders resting live outside the window (buy: grid floor, sell: grid ceiling; 0 disables)
201
201
  // BTS fee management for non-BTS pairs
202
- min_BTS_value: null, // Minimum BTS balance to maintain (null = auto from activeOrders × fees × multiplier)
202
+ min_BTS_value: null, // Minimum BTS balance to maintain (null = auto from coreOrders × fees × multiplier)
203
203
  };
204
204
  // Range quality zones for price bounds (minPrice/maxPrice multipliers).
205
205
  // Used for pre-entry legend in the bot editor (mountain-style).
@@ -330,6 +330,13 @@ let TIMING = {
330
330
  // by moving the boundary). Time-based so it holds for any tick cadence.
331
331
  SPREAD_STALE_WARN_MS: 10 * 60 * 1000, // 10 minutes
332
332
  SPREAD_STALE_ESCALATE_MS: 30 * 60 * 1000, // 30 minutes
333
+ // SPREAD_CORRECTION_SYNC_FRESH_MS: how old the last completed open-orders
334
+ // sync may be before a spread-correction CREATE loses its LAST-FILL-GUARD
335
+ // bypass. A stale local snapshot (old sync or known-unmatched chain
336
+ // orders) can hide the real window edge, so the bypass is withheld and the
337
+ // guard applies instead of trusting the stale anchor. Fail-open when no
338
+ // sync timestamp exists yet.
339
+ SPREAD_CORRECTION_SYNC_FRESH_MS: 10 * 60 * 1000, // 10 minutes
333
340
  // Dedicated escalation cooldown for the spread-stale watchdog. Deliberately
334
341
  // separate from BOUNDARY_HOLD_RESYNC_COOLDOWN_MS so tuning boundary-hold
335
342
  // behavior never silently changes the spread watchdog cadence.
@@ -538,7 +545,7 @@ let GRID_LIMITS = {
538
545
  // to a price ladder ("no genesis" -- the genesis-less state analysed in
539
546
  // docs/GRID_PRICE_INVARIANT.md). A genesis-less grid is NOT repairable in
540
547
  // place: every consumer (nearest-slot adoption, the materialize
541
- // descriptor-price fallback, reserve-edge anchoring) has no authority for a
548
+ // descriptor-price fallback, edge anchoring) has no authority for a
542
549
  // slot's price, which is exactly how an off-grid price became grid evidence
543
550
  // and was re-emitted. The load and sync gates refuse that state outright —
544
551
  // no tolerance matcher remains.
@@ -985,6 +985,7 @@ declare class DEXBot implements BotLike {
985
985
  * @returns {Object} Metrics snapshot
986
986
  */
987
987
  getMetrics(): {
988
+ boundaryDriftExceedsWindowCount: number;
988
989
  queueDepth: number;
989
990
  fillProcessingLockActive: boolean;
990
991
  divergenceLockActive: boolean;
@@ -1001,6 +1002,10 @@ declare class DEXBot implements BotLike {
1001
1002
  maxQueueDepth: number;
1002
1003
  gridLockContention: number;
1003
1004
  fundRecalcCount: number;
1005
+ refusedCommitCount: number;
1006
+ orphanFillCreditedCount: number;
1007
+ restampBuyAboveAnchorCount: number;
1008
+ gapBandPlacementShadowCount: number;
1004
1009
  };
1005
1010
  /**
1006
1011
  * Execute grid maintenance checks in strict order with pipeline consensus.
@@ -267,7 +267,12 @@ class DEXBot {
267
267
  lockContentionEvents: 0,
268
268
  gridLockContention: 0,
269
269
  fundRecalcCount: 0,
270
- maxQueueDepth: 0
270
+ maxQueueDepth: 0,
271
+ refusedCommitCount: 0,
272
+ orphanFillCreditedCount: 0,
273
+ restampBuyAboveAnchorCount: 0,
274
+ boundaryDriftExceedsWindowCount: 0,
275
+ gapBandPlacementShadowCount: 0
271
276
  };
272
277
  // Shutdown state
273
278
  this._shuttingDown = false;
@@ -1073,8 +1078,8 @@ class DEXBot {
1073
1078
  }
1074
1079
  let anyDeferred = false;
1075
1080
  try {
1076
- const activeSell = this.manager?.config?.activeOrders?.sell ?? 1;
1077
- const activeBuy = this.manager?.config?.activeOrders?.buy ?? 1;
1081
+ const activeSell = this.manager?.config?.coreOrders?.sell ?? 1;
1082
+ const activeBuy = this.manager?.config?.coreOrders?.buy ?? 1;
1078
1083
  const legacyCap = Math.max(Math.floor(activeSell / 2), Math.floor(activeBuy / 2), 1);
1079
1084
  const shiftBudget = legacyCap;
1080
1085
  this.manager._boundaryShiftBudget = shiftBudget;