dexbot 1.7.1 → 1.7.3

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 (66) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/claw/package.json +1 -1
  3. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  4. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  5. package/dist/analysis/grid_correction_check.d.ts +60 -1
  6. package/dist/analysis/grid_correction_check.js +268 -18
  7. package/dist/analysis/pivot_timeline.d.ts +78 -0
  8. package/dist/analysis/pivot_timeline.js +360 -0
  9. package/dist/market_adapter/utils/file_lock.js +16 -4
  10. package/dist/modules/account_bots.d.ts +7 -0
  11. package/dist/modules/account_bots.js +7 -5
  12. package/dist/modules/bot_defaults.js +6 -1
  13. package/dist/modules/constants.d.ts +14 -0
  14. package/dist/modules/constants.js +82 -2
  15. package/dist/modules/dexbot_class.d.ts +39 -0
  16. package/dist/modules/dexbot_class.js +86 -1
  17. package/dist/modules/dexbot_cow_runtime.d.ts +31 -1
  18. package/dist/modules/dexbot_cow_runtime.js +299 -75
  19. package/dist/modules/dexbot_maintenance_runtime.d.ts +32 -2
  20. package/dist/modules/dexbot_maintenance_runtime.js +196 -16
  21. package/dist/modules/dexbot_state_recovery.js +15 -1
  22. package/dist/modules/launcher/instance_lock.d.ts +27 -0
  23. package/dist/modules/launcher/instance_lock.js +131 -0
  24. package/dist/modules/node_flap_score.d.ts +6 -6
  25. package/dist/modules/node_flap_score.js +6 -6
  26. package/dist/modules/order/accounting.d.ts +9 -4
  27. package/dist/modules/order/accounting.js +89 -26
  28. package/dist/modules/order/async_lock.d.ts +7 -1
  29. package/dist/modules/order/async_lock.js +7 -1
  30. package/dist/modules/order/export.js +25 -18
  31. package/dist/modules/order/fill_ledger.d.ts +99 -0
  32. package/dist/modules/order/fill_ledger.js +103 -0
  33. package/dist/modules/order/grid.d.ts +94 -18
  34. package/dist/modules/order/grid.js +247 -75
  35. package/dist/modules/order/grid_reconcile_internal.js +16 -4
  36. package/dist/modules/order/index.d.ts +29 -6
  37. package/dist/modules/order/index.js +5 -5
  38. package/dist/modules/order/lifecycle.js +3 -3
  39. package/dist/modules/order/manager.d.ts +36 -24
  40. package/dist/modules/order/manager.js +159 -39
  41. package/dist/modules/order/placement_lock.d.ts +30 -0
  42. package/dist/modules/order/placement_lock.js +48 -0
  43. package/dist/modules/order/sync_engine.d.ts +66 -118
  44. package/dist/modules/order/sync_engine.js +118 -162
  45. package/dist/modules/order/utils/math.d.ts +7 -3
  46. package/dist/modules/order/utils/math.js +7 -3
  47. package/dist/modules/order/utils/order.d.ts +79 -42
  48. package/dist/modules/order/utils/order.js +183 -86
  49. package/dist/modules/order/utils/system.d.ts +192 -8
  50. package/dist/modules/order/utils/system.js +534 -34
  51. package/dist/modules/paths.d.ts +1 -0
  52. package/dist/modules/paths.js +1 -0
  53. package/dist/modules/timing_policy.js +4 -2
  54. package/dist/modules/types.d.ts +49 -27
  55. package/dist/pm2.js +126 -0
  56. package/dist/unlock.js +26 -1
  57. package/docs/COW_INVARIANTS.md +5 -1
  58. package/docs/DEXBOT_COMPARISON.md +5 -5
  59. package/docs/EVOLUTION.md +10 -8
  60. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  61. package/docs/GRID_RECONCILE.md +3 -3
  62. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +192 -31
  63. package/docs/README.md +1 -1
  64. package/docs/architecture.md +26 -8
  65. package/modules/README.md +4 -0
  66. package/package.json +4 -3
@@ -6,7 +6,7 @@
6
6
  * Exports a single Accountant class that manages all fund accounting operations.
7
7
  *
8
8
  * ===============================================================================
9
- * TABLE OF CONTENTS - Accountant Class (26 methods)
9
+ * TABLE OF CONTENTS - Accountant Class (27 methods)
10
10
  * ===============================================================================
11
11
  *
12
12
  * CORE INITIALIZATION & RECALCULATION (2 methods)
@@ -56,6 +56,7 @@
56
56
  * 25. _recalibrateTrackedFundsFromChain(mgr, openOrders) - Recalibrate tracked funds
57
57
  * from a fresh chain snapshot
58
58
  * 26. _tryTrustChainFreeHeal(mgr, driftValidation) - Attempt a trust-chain-free heal
59
+ * 27. _getBtsFeeSchedule() - Resolve the BTS fee schedule (create/update/cancel + maker refund %)
59
60
  *
60
61
  * ===============================================================================
61
62
  * FUND STRUCTURE (managed by Accountant)
@@ -131,9 +132,13 @@ declare class Accountant {
131
132
  constructor(manager: OrderManagerLike);
132
133
  _logThrottled(key: string, message: string, level?: string, intervalMs?: number): boolean;
133
134
  /**
134
- * Apply a list of balance adjustments.
135
- * @param {Array<{orderType: string, delta: number, operation: string}>} balanceAdjustments
136
- * @returns {void}
135
+ * Apply balance adjustments ALL-OR-NOTHING.
136
+ *
137
+ * A throw from the middle of the list used to leave the earlier deltas
138
+ * applied. Since P2 releases the dedup claim on failure (so the fill can be
139
+ * retried), a partial application would then be applied twice on the retry.
140
+ * The credit is now atomic: an applied prefix is reversed before the error
141
+ * propagates, so "not credited" is true whenever the claim was released.
137
142
  */
138
143
  _applyBalanceAdjustments(balanceAdjustments: Array<{
139
144
  orderType: string | null | undefined;
@@ -6,7 +6,7 @@
6
6
  * Exports a single Accountant class that manages all fund accounting operations.
7
7
  *
8
8
  * ===============================================================================
9
- * TABLE OF CONTENTS - Accountant Class (26 methods)
9
+ * TABLE OF CONTENTS - Accountant Class (27 methods)
10
10
  * ===============================================================================
11
11
  *
12
12
  * CORE INITIALIZATION & RECALCULATION (2 methods)
@@ -56,6 +56,7 @@
56
56
  * 25. _recalibrateTrackedFundsFromChain(mgr, openOrders) - Recalibrate tracked funds
57
57
  * from a fresh chain snapshot
58
58
  * 26. _tryTrustChainFreeHeal(mgr, driftValidation) - Attempt a trust-chain-free heal
59
+ * 27. _getBtsFeeSchedule() - Resolve the BTS fee schedule (create/update/cancel + maker refund %)
59
60
  *
60
61
  * ===============================================================================
61
62
  * FUND STRUCTURE (managed by Accountant)
@@ -144,13 +145,30 @@ class Accountant {
144
145
  return false;
145
146
  }
146
147
  /**
147
- * Apply a list of balance adjustments.
148
- * @param {Array<{orderType: string, delta: number, operation: string}>} balanceAdjustments
149
- * @returns {void}
148
+ * Apply balance adjustments ALL-OR-NOTHING.
149
+ *
150
+ * A throw from the middle of the list used to leave the earlier deltas
151
+ * applied. Since P2 releases the dedup claim on failure (so the fill can be
152
+ * retried), a partial application would then be applied twice on the retry.
153
+ * The credit is now atomic: an applied prefix is reversed before the error
154
+ * propagates, so "not credited" is true whenever the claim was released.
150
155
  */
151
156
  async _applyBalanceAdjustments(balanceAdjustments) {
152
- for (const adjustment of balanceAdjustments) {
153
- await this.adjustTotalBalance(adjustment.orderType, adjustment.delta, adjustment.operation);
157
+ const applied = [];
158
+ try {
159
+ for (const adjustment of balanceAdjustments) {
160
+ await this.adjustTotalBalance(adjustment.orderType, adjustment.delta, adjustment.operation);
161
+ applied.push(adjustment);
162
+ }
163
+ }
164
+ catch (err) {
165
+ for (const adjustment of applied.reverse()) {
166
+ try {
167
+ await this.adjustTotalBalance(adjustment.orderType, -adjustment.delta, 'rollback-' + adjustment.operation);
168
+ }
169
+ catch { /* keep the original failure */ }
170
+ }
171
+ throw err;
154
172
  }
155
173
  }
156
174
  _getBtsOrderType() {
@@ -1707,6 +1725,15 @@ class Accountant {
1707
1725
  }
1708
1726
  }
1709
1727
  const processedFillStore = this.manager.processedFillStore;
1728
+ // The claim, the duplicate gate and the rollback must all touch ONE map.
1729
+ // In a wired bot `processedFillTracker` IS `processedFillStore.tracker`
1730
+ // (dexbot_fill_runtime assigns the store map to the manager), but a
1731
+ // split fixture or a host that wiring never reached would otherwise
1732
+ // claim a key the ingest check cannot see. Prefer the store's map when
1733
+ // it exists; the in-memory tracker is the fallback.
1734
+ const claimTracker = processedFillStore?.tracker instanceof Map
1735
+ ? processedFillStore.tracker
1736
+ : tracker;
1710
1737
  // Queue the dedup key before applying balance adjustments. This ensures
1711
1738
  // persist failures are caught before any balance mutation. The queue entry
1712
1739
  // is flushed only after balance adjustments succeed below.
@@ -1720,24 +1747,59 @@ class Accountant {
1720
1747
  return false;
1721
1748
  }
1722
1749
  }
1723
- // Consume the pass-1 marker only now that this fill is not a
1724
- // duplicate and its dedup key is queued. Partial consumption: pass 1
1725
- // may have absorbed only part of this fill (A+B observed, fill A
1726
- // drained now); the transition subtracts only the remainder.
1727
- const consumeApplied = mgr.consumeChainSizeAppliedFillAmount;
1728
- if (Number.isFinite(filledBaseInt) && typeof consumeApplied === 'function') {
1729
- appliedInt = Math.max(0, Math.min(Math.round(Number(consumeApplied.call(mgr, String(fillOp.order_id), filledBaseInt)) || 0), Math.round(filledBaseInt)));
1750
+ // CLAIM THE KEY AT CREDIT TIME (docs/FILL_PIPELINE.md stage 2).
1751
+ // The store is the dedupe authority, so the key must be visible to the
1752
+ // duplicate check before any balance moves — not after the flush. Without
1753
+ // this, a second fill with the same key can pass the check while the
1754
+ // first is still in flight and reach the transition a second time; the
1755
+ // claim lease in the bot only covers that when its window has not
1756
+ // expired. Rolled back on every failure path below, so the invariant is
1757
+ // "booked ⇒ tracker has the key" with no half-claimed keys.
1758
+ //
1759
+ // The check and the set are ONE synchronous step: the duplicate check
1760
+ // above happens before `persist()` awaits, so two concurrent callers can
1761
+ // both pass it and then both credit. Re-checking here (no await in
1762
+ // between) makes the claim the actual single-winner gate. The loser must
1763
+ // NOT discard the queued write: the pending entry is keyed by fill key
1764
+ // and belongs to the winner's booking.
1765
+ if (fillKey) {
1766
+ if (claimTracker.has(fillKey))
1767
+ return false;
1768
+ claimTracker.set(fillKey, processedAt || Date.now());
1730
1769
  }
1731
- if (appliedInt > 0) {
1732
- fillOp.__chainSizeAlreadyApplied = true;
1733
- fillOp.__chainSizeAppliedInt = appliedInt;
1734
- mgr?.logger?.log?.(`[FILL-DEDUP] Fill ${fillKey || fillOp.order_id}: ${appliedInt}/${Math.round(filledBaseInt)} base units already absorbed by sync pass 1; the transition will not shrink them again`, 'debug');
1770
+ try {
1771
+ // Consume the pass-1 marker only now that this fill is not a
1772
+ // duplicate and its dedup key is queued. Partial consumption: pass 1
1773
+ // may have absorbed only part of this fill (A+B observed, fill A
1774
+ // drained now); the transition subtracts only the remainder.
1775
+ // Inside the try: the claim above must be released if the marker
1776
+ // accessor throws, or the fill could never be retried.
1777
+ const consumeApplied = mgr.consumeChainSizeAppliedFillAmount;
1778
+ if (Number.isFinite(filledBaseInt) && typeof consumeApplied === 'function') {
1779
+ appliedInt = Math.max(0, Math.min(Math.round(Number(consumeApplied.call(mgr, String(fillOp.order_id), filledBaseInt)) || 0), Math.round(filledBaseInt)));
1780
+ }
1781
+ if (appliedInt > 0) {
1782
+ fillOp.__chainSizeAppliedInt = appliedInt;
1783
+ mgr?.logger?.log?.(`[FILL-DEDUP] Fill ${fillKey || fillOp.order_id}: ${appliedInt}/${Math.round(filledBaseInt)} base units already absorbed by sync pass 1; the transition will not shrink them again`, 'debug');
1784
+ }
1785
+ else {
1786
+ delete fillOp.__chainSizeAppliedInt;
1787
+ }
1788
+ await this._applyBalanceAdjustments(balanceAdjustments);
1735
1789
  }
1736
- else {
1737
- delete fillOp.__chainSizeAlreadyApplied;
1738
- delete fillOp.__chainSizeAppliedInt;
1790
+ catch (err) {
1791
+ // The claim was ours (the duplicate check above returned early for an
1792
+ // existing key) and no credit was committed, so release it — otherwise
1793
+ // the fill could never be retried.
1794
+ if (fillKey) {
1795
+ claimTracker.delete(fillKey);
1796
+ processedFillStore?.discard(fillKey, processedAt || Date.now());
1797
+ }
1798
+ if (appliedInt > 0 && typeof mgr.noteChainSizeAppliedFill === 'function') {
1799
+ mgr.noteChainSizeAppliedFill(String(fillOp.order_id), appliedInt);
1800
+ }
1801
+ throw err;
1739
1802
  }
1740
- await this._applyBalanceAdjustments(balanceAdjustments);
1741
1803
  // Flush the queued dedup key now that balance adjustments succeeded.
1742
1804
  // For IMMEDIATE mode, this persists durably. For BATCHED mode, the
1743
1805
  // key remains queued for the caller's batch flush.
@@ -1754,6 +1816,7 @@ class Accountant {
1754
1816
  await this.adjustTotalBalance(adj.orderType, -adj.delta, 'rollback-' + adj.operation);
1755
1817
  }
1756
1818
  processedFillStore.discard(fillKey, processedAt || Date.now());
1819
+ claimTracker.delete(fillKey);
1757
1820
  // The marker was consumed for this attempt; the rolled-back
1758
1821
  // fill must be able to skip the pass-1 size release on retry.
1759
1822
  if (appliedInt > 0 && typeof mgr.noteChainSizeAppliedFill === 'function') {
@@ -1763,13 +1826,13 @@ class Accountant {
1763
1826
  }
1764
1827
  }
1765
1828
  if (fillKey) {
1766
- tracker.set(fillKey, processedAt || Date.now());
1767
- // Prune entries beyond the retention horizon to prevent unbounded growth.
1768
- if (tracker.size > 500) {
1829
+ // Already claimed before the credit; prune beyond the retention
1830
+ // horizon so the tracker cannot grow without bound.
1831
+ if (claimTracker.size > 500) {
1769
1832
  const cutoff = (processedAt || Date.now()) - TIMING.FILL_RECORD_RETENTION_MS;
1770
- for (const [k, ts] of tracker) {
1833
+ for (const [k, ts] of claimTracker) {
1771
1834
  if (ts < cutoff)
1772
- tracker.delete(k);
1835
+ claimTracker.delete(k);
1773
1836
  }
1774
1837
  }
1775
1838
  }
@@ -2,7 +2,9 @@
2
2
  * modules/order/async_lock.ts - AsyncLock Engine
3
3
  *
4
4
  * Distributed mutual exclusion for async operations.
5
- * Exports a single AsyncLock class that prevents concurrent execution of critical sections.
5
+ * Exports the AsyncLock class (the lock itself) plus the `acquireIfNotHeld()`
6
+ * re-entrancy guard that call sites delegate through instead of inlining the
7
+ * `isReentrant()` check-and-acquire.
6
8
  *
7
9
  * Solves the Time-of-Check vs Time-of-Use (TOCTOU) race condition
8
10
  * where checking a flag and setting it are not atomic operations.
@@ -47,6 +49,10 @@
47
49
  * 8. forceRelease() - Force-release the lock, rejecting every queued waiter
48
50
  * (used by shutdown/cleanup paths; returns whether it was held)
49
51
  *
52
+ * MODULE-LEVEL EXPORT:
53
+ * acquireIfNotHeld(lock, fn) - Run `fn` under `lock` unless the current async
54
+ * context already holds it (canonical re-entrancy guard)
55
+ *
50
56
  * ===============================================================================
51
57
  *
52
58
  * RACE CONDITION PREVENTION:
@@ -2,7 +2,9 @@
2
2
  * modules/order/async_lock.ts - AsyncLock Engine
3
3
  *
4
4
  * Distributed mutual exclusion for async operations.
5
- * Exports a single AsyncLock class that prevents concurrent execution of critical sections.
5
+ * Exports the AsyncLock class (the lock itself) plus the `acquireIfNotHeld()`
6
+ * re-entrancy guard that call sites delegate through instead of inlining the
7
+ * `isReentrant()` check-and-acquire.
6
8
  *
7
9
  * Solves the Time-of-Check vs Time-of-Use (TOCTOU) race condition
8
10
  * where checking a flag and setting it are not atomic operations.
@@ -47,6 +49,10 @@
47
49
  * 8. forceRelease() - Force-release the lock, rejecting every queued waiter
48
50
  * (used by shutdown/cleanup paths; returns whether it was held)
49
51
  *
52
+ * MODULE-LEVEL EXPORT:
53
+ * acquireIfNotHeld(lock, fn) - Run `fn` under `lock` unless the current async
54
+ * context already holds it (canonical re-entrancy guard)
55
+ *
50
56
  * ===============================================================================
51
57
  *
52
58
  * RACE CONDITION PREVENTION:
@@ -74,11 +74,12 @@ import { getStorage } from '../storage/index.js';
74
74
  import { createRequire } from 'node:module';
75
75
  import { path } from '../path_api.js';
76
76
  import * as Format from './format.js';
77
- import { TIMING, DEFAULT_CONFIG } from '../constants.js';
77
+ import { TIMING, DEFAULT_CONFIG, ORDER_TYPES } from '../constants.js';
78
78
  import { PATHS } from '../paths.js';
79
79
  import Logger from '../order/logger.js';
80
80
  import { getErrorMessage } from '../utils/errors.js';
81
81
  import { nowIso } from './utils/system.js';
82
+ import { resolveTradedSide } from './fill_ledger.js';
82
83
  const _require = createRequire(import.meta.url);
83
84
  const storage = getStorage();
84
85
  let _readline = null;
@@ -181,30 +182,36 @@ function deriveTradeFromFillBlock(block, ctx) {
181
182
  if (block.paysRaw == null || block.receivesRaw == null)
182
183
  return null;
183
184
  let hypothesis = null;
185
+ const isOwnAsset = (id) => id === ctx.assetA.id || id === ctx.assetB.id;
184
186
  if (block.paysAssetId && block.receivesAssetId) {
185
- const sellOrientation = block.paysAssetId === ctx.assetA.id && block.receivesAssetId === ctx.assetB.id;
186
- const buyOrientation = block.paysAssetId === ctx.assetB.id && block.receivesAssetId === ctx.assetA.id;
187
- if (!sellOrientation && !buyOrientation)
188
- return null; // foreign-market fill, not ours
189
- hypothesis = buildOrientationHypothesis(block.paysRaw, block.receivesRaw, sellOrientation, ctx);
187
+ // Both sides must be this pair: a block that paid our asset and received
188
+ // a third one is a foreign-market fill, not ours.
189
+ if (!isOwnAsset(block.paysAssetId) || !isOwnAsset(block.receivesAssetId))
190
+ return null;
191
+ if (block.paysAssetId === block.receivesAssetId)
192
+ return null;
193
+ // Side comes from the ledger's one mapping (paid asset => side), never a
194
+ // local copy of it.
195
+ const tradedSide = resolveTradedSide(block.paysAssetId, ctx, null);
196
+ if (tradedSide == null)
197
+ return null;
198
+ hypothesis = buildOrientationHypothesis(block.paysRaw, block.receivesRaw, tradedSide === ORDER_TYPES.SELL, ctx);
190
199
  }
191
200
  else if (block.paysAssetId || block.receivesAssetId) {
192
201
  // Half-present block (truncated log line): exactly one side survived.
193
202
  // Pays present orients directly; receives present inverts
194
203
  // (receives A => pays B => BUY; receives B => pays A => SELL).
195
204
  // A present side matching neither local asset is a foreign-market fill.
196
- let paysIsA;
197
- if (block.paysAssetId) {
198
- if (block.paysAssetId !== ctx.assetA.id && block.paysAssetId !== ctx.assetB.id)
199
- return null;
200
- paysIsA = block.paysAssetId === ctx.assetA.id;
201
- }
202
- else {
203
- if (block.receivesAssetId !== ctx.assetA.id && block.receivesAssetId !== ctx.assetB.id)
204
- return null;
205
- paysIsA = block.receivesAssetId === ctx.assetB.id;
206
- }
207
- hypothesis = buildOrientationHypothesis(block.paysRaw, block.receivesRaw, paysIsA, ctx);
205
+ const present = block.paysAssetId || block.receivesAssetId;
206
+ if (!isOwnAsset(present))
207
+ return null;
208
+ const paidAssetId = block.paysAssetId
209
+ ? block.paysAssetId
210
+ : (block.receivesAssetId === ctx.assetA.id ? ctx.assetB.id : ctx.assetA.id);
211
+ const tradedSide = resolveTradedSide(paidAssetId, ctx, null);
212
+ if (tradedSide == null)
213
+ return null;
214
+ hypothesis = buildOrientationHypothesis(block.paysRaw, block.receivesRaw, tradedSide === ORDER_TYPES.SELL, ctx);
208
215
  }
209
216
  else {
210
217
  // Bare pre-#22 block: no asset orientation logged.
@@ -0,0 +1,99 @@
1
+ /**
2
+ * modules/order/fill_ledger.ts
3
+ *
4
+ * Fill identity, traded-side resolution and booked-fill membership.
5
+ *
6
+ * WHY THIS MODULE EXISTS
7
+ * ----------------------
8
+ * A fill used to be identified, sided and de-duplicated in three places:
9
+ * - `buildFillKey` / `buildOrphanFillFallbackKey` in `dexbot_fill_runtime.ts`,
10
+ * - the pays-asset side mapping copied into `SyncEngine._computeFillContext`,
11
+ * `attributeUnmatchedFillToGrid` (`order/utils/order.ts`) and the queued
12
+ * pivot refresh (`dexbot_cow_runtime.ts`),
13
+ * - the booked-fill check split between `_isNewFillKey` (bot level) and
14
+ * `OrderManager.processedFillStore` (the persisted authority).
15
+ *
16
+ * The copies drifted: `6afa0c4b` had to patch the same "undefined pays asset"
17
+ * collision in three sites at once, and `cb1041b6` had to fix a side that the
18
+ * slot label had laundered. This module is the single owner of the two pure
19
+ * questions ("which fill is this?" and "which side did it trade?") so a fourth
20
+ * copy is a review failure rather than a silent divergence.
21
+ *
22
+ * WHAT IT DOES NOT OWN
23
+ * --------------------
24
+ * - Duplicate *booking* stays with `OrderManager.processedFillStore`; this
25
+ * module only exposes its membership test (`isFillBooked`).
26
+ * - The SPREAD price fallback policy stays with the caller that has the
27
+ * genesis price (`resolveSpreadOrderSide`); `resolveTradedSide` takes the
28
+ * already-resolved fallback side as an argument instead of re-deriving it.
29
+ * - Rails: `slot.type` is the ACCOUNTING side after a partial fill retags it
30
+ * (`sync_engine` PARTIAL transition, see docs/COW_INVARIANTS.md INV-SYNC-008
31
+ * and `cb1041b6`). Rail identity is geometry and is never derived here.
32
+ *
33
+ * Browser-safe: no imports beyond the constants, no `process`/`fs` usage.
34
+ */
35
+ /** Minimal shape the key builder reads (a chain fill op, a history row, or a queue entry). */
36
+ export interface FillKeySource {
37
+ op?: unknown[];
38
+ orderId?: string;
39
+ block_num?: number;
40
+ blockNum?: number;
41
+ id?: string;
42
+ historyId?: string;
43
+ }
44
+ /** Minimal asset-pair shape needed to map a paid asset onto a side. */
45
+ export interface FillSideAssets {
46
+ assetA?: {
47
+ id?: unknown;
48
+ } | null;
49
+ assetB?: {
50
+ id?: unknown;
51
+ } | null;
52
+ }
53
+ /** Persisted dedupe store shape (`OrderManager.processedFillStore`). */
54
+ export interface FillBookedStore {
55
+ tracker?: Map<string, number> | null;
56
+ }
57
+ /**
58
+ * The chain identity of a fill: `orderId:blockNum:historyId`.
59
+ *
60
+ * All three parts are required. A fill without them cannot be de-duplicated
61
+ * across restarts, so callers treat `null` as "no identity" (the fill runtime
62
+ * then tries its orphan fallback key) rather than inventing one.
63
+ */
64
+ declare function fillKeyOf(fillOrParts: FillKeySource | null | undefined): string | null;
65
+ /**
66
+ * The side a fill actually traded, resolved from the asset that was PAID.
67
+ *
68
+ * Paying the quote asset (assetB) buys the base; paying the base (assetA)
69
+ * sells it. This is chain truth and must not be replaced by the slot label:
70
+ * a slot can be retyped (BUY<->SELL) before its resting order is corrected,
71
+ * and the slot type is the ACCOUNTING side after a partial fill (`6afa0c4b`,
72
+ * `cb1041b6`).
73
+ *
74
+ * `fallbackType` is used only when the fill event carries no usable pays
75
+ * asset (legacy/malformed fill). The caller supplies it — the matched slot's
76
+ * type, or a SPREAD slot's price-vs-startPrice resolution
77
+ * (`resolveSpreadOrderSide`) — so the SPREAD policy stays with the site that
78
+ * has the price ladder. A fallback that is not BUY/SELL yields `null`: the
79
+ * side is never guessed from a price here.
80
+ *
81
+ * @param paysAssetId - Asset the fill paid (chain `pays.asset_id`)
82
+ * @param assets - Asset pair (ids only; precisions are not needed)
83
+ * @param fallbackType - Side to use when no pays asset identifies one
84
+ * @returns 'buy' | 'sell' | null
85
+ */
86
+ declare function resolveTradedSide(paysAssetId: unknown, assets: FillSideAssets | null | undefined, fallbackType?: unknown): string | null;
87
+ /**
88
+ * Is this fill already booked?
89
+ *
90
+ * Reads the persisted dedupe authority (`ProcessedFillStore.tracker`) without
91
+ * mutating it. `_isNewFillKey` (bot level) still owns the *claim* — this is
92
+ * the membership question the accounting path asks before it books a credit.
93
+ * An unreadable store is reported as `false` (not booked) deliberately: the
94
+ * caller keeps its existing claim path, and a missing tracker cannot be turned
95
+ * into a silent double credit by this helper.
96
+ */
97
+ declare function isFillBooked(store: FillBookedStore | null | undefined, fillKey: string | null | undefined): boolean;
98
+ export { fillKeyOf, resolveTradedSide, isFillBooked };
99
+ //# sourceMappingURL=fill_ledger.d.ts.map
@@ -0,0 +1,103 @@
1
+ /**
2
+ * modules/order/fill_ledger.ts
3
+ *
4
+ * Fill identity, traded-side resolution and booked-fill membership.
5
+ *
6
+ * WHY THIS MODULE EXISTS
7
+ * ----------------------
8
+ * A fill used to be identified, sided and de-duplicated in three places:
9
+ * - `buildFillKey` / `buildOrphanFillFallbackKey` in `dexbot_fill_runtime.ts`,
10
+ * - the pays-asset side mapping copied into `SyncEngine._computeFillContext`,
11
+ * `attributeUnmatchedFillToGrid` (`order/utils/order.ts`) and the queued
12
+ * pivot refresh (`dexbot_cow_runtime.ts`),
13
+ * - the booked-fill check split between `_isNewFillKey` (bot level) and
14
+ * `OrderManager.processedFillStore` (the persisted authority).
15
+ *
16
+ * The copies drifted: `6afa0c4b` had to patch the same "undefined pays asset"
17
+ * collision in three sites at once, and `cb1041b6` had to fix a side that the
18
+ * slot label had laundered. This module is the single owner of the two pure
19
+ * questions ("which fill is this?" and "which side did it trade?") so a fourth
20
+ * copy is a review failure rather than a silent divergence.
21
+ *
22
+ * WHAT IT DOES NOT OWN
23
+ * --------------------
24
+ * - Duplicate *booking* stays with `OrderManager.processedFillStore`; this
25
+ * module only exposes its membership test (`isFillBooked`).
26
+ * - The SPREAD price fallback policy stays with the caller that has the
27
+ * genesis price (`resolveSpreadOrderSide`); `resolveTradedSide` takes the
28
+ * already-resolved fallback side as an argument instead of re-deriving it.
29
+ * - Rails: `slot.type` is the ACCOUNTING side after a partial fill retags it
30
+ * (`sync_engine` PARTIAL transition, see docs/COW_INVARIANTS.md INV-SYNC-008
31
+ * and `cb1041b6`). Rail identity is geometry and is never derived here.
32
+ *
33
+ * Browser-safe: no imports beyond the constants, no `process`/`fs` usage.
34
+ */
35
+ import { ORDER_TYPES } from '../constants.js';
36
+ /**
37
+ * The chain identity of a fill: `orderId:blockNum:historyId`.
38
+ *
39
+ * All three parts are required. A fill without them cannot be de-duplicated
40
+ * across restarts, so callers treat `null` as "no identity" (the fill runtime
41
+ * then tries its orphan fallback key) rather than inventing one.
42
+ */
43
+ function fillKeyOf(fillOrParts) {
44
+ const fillOp = fillOrParts?.op?.[1];
45
+ const orderId = fillOp?.order_id ?? fillOrParts?.orderId;
46
+ const blockNum = fillOrParts?.block_num ?? fillOrParts?.blockNum;
47
+ const historyId = fillOrParts?.id ?? fillOrParts?.historyId;
48
+ if (!orderId || blockNum == null || !historyId)
49
+ return null;
50
+ return `${orderId}:${blockNum}:${historyId}`;
51
+ }
52
+ /**
53
+ * The side a fill actually traded, resolved from the asset that was PAID.
54
+ *
55
+ * Paying the quote asset (assetB) buys the base; paying the base (assetA)
56
+ * sells it. This is chain truth and must not be replaced by the slot label:
57
+ * a slot can be retyped (BUY<->SELL) before its resting order is corrected,
58
+ * and the slot type is the ACCOUNTING side after a partial fill (`6afa0c4b`,
59
+ * `cb1041b6`).
60
+ *
61
+ * `fallbackType` is used only when the fill event carries no usable pays
62
+ * asset (legacy/malformed fill). The caller supplies it — the matched slot's
63
+ * type, or a SPREAD slot's price-vs-startPrice resolution
64
+ * (`resolveSpreadOrderSide`) — so the SPREAD policy stays with the site that
65
+ * has the price ladder. A fallback that is not BUY/SELL yields `null`: the
66
+ * side is never guessed from a price here.
67
+ *
68
+ * @param paysAssetId - Asset the fill paid (chain `pays.asset_id`)
69
+ * @param assets - Asset pair (ids only; precisions are not needed)
70
+ * @param fallbackType - Side to use when no pays asset identifies one
71
+ * @returns 'buy' | 'sell' | null
72
+ */
73
+ function resolveTradedSide(paysAssetId, assets, fallbackType) {
74
+ const a = assets?.assetA?.id;
75
+ const b = assets?.assetB?.id;
76
+ if (paysAssetId != null && b != null && paysAssetId === b)
77
+ return ORDER_TYPES.BUY;
78
+ if (paysAssetId != null && a != null && paysAssetId === a)
79
+ return ORDER_TYPES.SELL;
80
+ if (fallbackType === ORDER_TYPES.BUY || fallbackType === ORDER_TYPES.SELL)
81
+ return fallbackType;
82
+ return null;
83
+ }
84
+ /**
85
+ * Is this fill already booked?
86
+ *
87
+ * Reads the persisted dedupe authority (`ProcessedFillStore.tracker`) without
88
+ * mutating it. `_isNewFillKey` (bot level) still owns the *claim* — this is
89
+ * the membership question the accounting path asks before it books a credit.
90
+ * An unreadable store is reported as `false` (not booked) deliberately: the
91
+ * caller keeps its existing claim path, and a missing tracker cannot be turned
92
+ * into a silent double credit by this helper.
93
+ */
94
+ function isFillBooked(store, fillKey) {
95
+ if (!fillKey)
96
+ return false;
97
+ const tracker = store?.tracker;
98
+ if (!(tracker instanceof Map))
99
+ return false;
100
+ return tracker.has(fillKey);
101
+ }
102
+ export { fillKeyOf, resolveTradedSide, isFillBooked };
103
+ //# sourceMappingURL=fill_ledger.js.map