dexbot 1.6.3 → 1.6.4

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 (204) hide show
  1. package/CHANGELOG.md +38 -2
  2. package/README.md +11 -7
  3. package/analysis/README.md +18 -12
  4. package/analysis/account_resolver.ts +171 -0
  5. package/analysis/ama_fitting/analyze_lambda_vs_slow.ts +2 -5
  6. package/analysis/ama_fitting/package.json +1 -1
  7. package/analysis/bot_usage/discover_bot_accounts.ts +20 -27
  8. package/analysis/chain_pool.ts +47 -0
  9. package/analysis/chart_utils.ts +33 -20
  10. package/analysis/derivative_chart_generator.ts +2 -3
  11. package/analysis/fills_source.ts +234 -0
  12. package/analysis/grid_correction_check.ts +38 -251
  13. package/analysis/trade_profitability.ts +169 -304
  14. package/analysis/tradingview/README.md +2 -2
  15. package/analysis/tradingview/tradingview_uplot_chart_generator.ts +3 -4
  16. package/analysis/trend_detection/dynamic_weight_chart_generator.ts +2 -3
  17. package/analysis/trend_detection/kalman_chart_generator.ts +2 -3
  18. package/analysis/trend_detection/package.json +1 -1
  19. package/analysis/trend_detection/regime_chart_generator.ts +2 -3
  20. package/analysis/trend_detection/volatility_chart_generator.ts +2 -3
  21. package/claw/package.json +1 -1
  22. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  23. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  24. package/claw/tests/test_claw_mcp_transport.ts +2 -2
  25. package/dist/analysis/account_resolver.d.ts +43 -0
  26. package/dist/analysis/account_resolver.d.ts.map +1 -0
  27. package/dist/analysis/account_resolver.js +137 -0
  28. package/dist/analysis/account_resolver.js.map +1 -0
  29. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts.map +1 -1
  30. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -4
  31. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +1 -1
  32. package/dist/analysis/bot_usage/discover_bot_accounts.js +20 -28
  33. package/dist/analysis/bot_usage/discover_bot_accounts.js.map +1 -1
  34. package/dist/analysis/chain_pool.d.ts +10 -0
  35. package/dist/analysis/chain_pool.d.ts.map +1 -0
  36. package/dist/analysis/chain_pool.js +47 -0
  37. package/dist/analysis/chain_pool.js.map +1 -0
  38. package/dist/analysis/chart_utils.d.ts +14 -1
  39. package/dist/analysis/chart_utils.d.ts.map +1 -1
  40. package/dist/analysis/chart_utils.js +32 -22
  41. package/dist/analysis/chart_utils.js.map +1 -1
  42. package/dist/analysis/derivative_chart_generator.d.ts.map +1 -1
  43. package/dist/analysis/derivative_chart_generator.js +2 -3
  44. package/dist/analysis/derivative_chart_generator.js.map +1 -1
  45. package/dist/analysis/fills_source.d.ts +79 -0
  46. package/dist/analysis/fills_source.d.ts.map +1 -0
  47. package/dist/analysis/fills_source.js +186 -0
  48. package/dist/analysis/fills_source.js.map +1 -0
  49. package/dist/analysis/grid_correction_check.d.ts +1 -21
  50. package/dist/analysis/grid_correction_check.d.ts.map +1 -1
  51. package/dist/analysis/grid_correction_check.js +30 -257
  52. package/dist/analysis/grid_correction_check.js.map +1 -1
  53. package/dist/analysis/trade_profitability.d.ts +18 -19
  54. package/dist/analysis/trade_profitability.d.ts.map +1 -1
  55. package/dist/analysis/trade_profitability.js +136 -280
  56. package/dist/analysis/trade_profitability.js.map +1 -1
  57. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts.map +1 -1
  58. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +3 -4
  59. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js.map +1 -1
  60. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +1 -1
  61. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +2 -3
  62. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +1 -1
  63. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts.map +1 -1
  64. package/dist/analysis/trend_detection/kalman_chart_generator.js +2 -3
  65. package/dist/analysis/trend_detection/kalman_chart_generator.js.map +1 -1
  66. package/dist/analysis/trend_detection/regime_chart_generator.d.ts.map +1 -1
  67. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -3
  68. package/dist/analysis/trend_detection/regime_chart_generator.js.map +1 -1
  69. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts.map +1 -1
  70. package/dist/analysis/trend_detection/volatility_chart_generator.js +2 -3
  71. package/dist/analysis/trend_detection/volatility_chart_generator.js.map +1 -1
  72. package/dist/market_adapter/lp_chart_core.d.ts.map +1 -1
  73. package/dist/market_adapter/lp_chart_core.js +2 -3
  74. package/dist/market_adapter/lp_chart_core.js.map +1 -1
  75. package/dist/modules/account_bots.d.ts +1 -18
  76. package/dist/modules/account_bots.d.ts.map +1 -1
  77. package/dist/modules/account_bots.js +1 -1
  78. package/dist/modules/account_bots.js.map +1 -1
  79. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -84
  80. package/dist/modules/bitshares-native/serial/operations.d.ts.map +1 -1
  81. package/dist/modules/bitshares-native/serial/operations.js +1 -38
  82. package/dist/modules/bitshares-native/serial/operations.js.map +1 -1
  83. package/dist/modules/cli_colors.d.ts +0 -1
  84. package/dist/modules/cli_colors.d.ts.map +1 -1
  85. package/dist/modules/constants.js +5 -5
  86. package/dist/modules/constants.js.map +1 -1
  87. package/dist/modules/credential_policy.d.ts +1 -25
  88. package/dist/modules/credential_policy.d.ts.map +1 -1
  89. package/dist/modules/credential_policy.js +1 -1
  90. package/dist/modules/credential_policy.js.map +1 -1
  91. package/dist/modules/credential_runtime.d.ts +1 -6
  92. package/dist/modules/credential_runtime.d.ts.map +1 -1
  93. package/dist/modules/credential_runtime.js +1 -1
  94. package/dist/modules/credential_runtime.js.map +1 -1
  95. package/dist/modules/credential_session_cache.d.ts +1 -5
  96. package/dist/modules/credential_session_cache.d.ts.map +1 -1
  97. package/dist/modules/credential_session_cache.js +1 -1
  98. package/dist/modules/credential_session_cache.js.map +1 -1
  99. package/dist/modules/crypto/pure_secp256k1.d.ts +1 -2
  100. package/dist/modules/crypto/pure_secp256k1.d.ts.map +1 -1
  101. package/dist/modules/crypto/pure_secp256k1.js +1 -1
  102. package/dist/modules/crypto/pure_secp256k1.js.map +1 -1
  103. package/dist/modules/dexbot_class.d.ts +8 -7
  104. package/dist/modules/dexbot_class.d.ts.map +1 -1
  105. package/dist/modules/dexbot_class.js +9 -8
  106. package/dist/modules/dexbot_class.js.map +1 -1
  107. package/dist/modules/dexbot_cow_runtime.d.ts +7 -6
  108. package/dist/modules/dexbot_cow_runtime.d.ts.map +1 -1
  109. package/dist/modules/dexbot_cow_runtime.js +8 -7
  110. package/dist/modules/dexbot_cow_runtime.js.map +1 -1
  111. package/dist/modules/dexbot_fill_runtime.d.ts +1 -17
  112. package/dist/modules/dexbot_fill_runtime.d.ts.map +1 -1
  113. package/dist/modules/dexbot_fill_runtime.js +1 -1
  114. package/dist/modules/dexbot_fill_runtime.js.map +1 -1
  115. package/dist/modules/dexbot_maintenance_runtime.d.ts +1 -1
  116. package/dist/modules/dexbot_maintenance_runtime.d.ts.map +1 -1
  117. package/dist/modules/dexbot_maintenance_runtime.js +15 -4
  118. package/dist/modules/dexbot_maintenance_runtime.js.map +1 -1
  119. package/dist/modules/dexbot_state_recovery.d.ts +1 -7
  120. package/dist/modules/dexbot_state_recovery.d.ts.map +1 -1
  121. package/dist/modules/dexbot_state_recovery.js +1 -1
  122. package/dist/modules/dexbot_state_recovery.js.map +1 -1
  123. package/dist/modules/launcher/adapter_requirement.d.ts +1 -5
  124. package/dist/modules/launcher/adapter_requirement.d.ts.map +1 -1
  125. package/dist/modules/launcher/adapter_requirement.js +1 -1
  126. package/dist/modules/launcher/adapter_requirement.js.map +1 -1
  127. package/dist/modules/launcher/bot_supervisor.d.ts +1 -6
  128. package/dist/modules/launcher/bot_supervisor.d.ts.map +1 -1
  129. package/dist/modules/launcher/bot_supervisor.js +1 -1
  130. package/dist/modules/launcher/bot_supervisor.js.map +1 -1
  131. package/dist/modules/launcher/foreign_cred_daemon.d.ts +1 -3
  132. package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +1 -1
  133. package/dist/modules/launcher/foreign_cred_daemon.js +1 -1
  134. package/dist/modules/launcher/foreign_cred_daemon.js.map +1 -1
  135. package/dist/modules/launcher/launch_modes.d.ts +1 -2
  136. package/dist/modules/launcher/launch_modes.d.ts.map +1 -1
  137. package/dist/modules/launcher/launch_modes.js +1 -1
  138. package/dist/modules/launcher/launch_modes.js.map +1 -1
  139. package/dist/modules/launcher/market_adapter_runtime.d.ts +1 -3
  140. package/dist/modules/launcher/market_adapter_runtime.d.ts.map +1 -1
  141. package/dist/modules/launcher/market_adapter_runtime.js +1 -1
  142. package/dist/modules/launcher/market_adapter_runtime.js.map +1 -1
  143. package/dist/modules/launcher/monolithic_runtime.d.ts +1 -5
  144. package/dist/modules/launcher/monolithic_runtime.d.ts.map +1 -1
  145. package/dist/modules/launcher/monolithic_runtime.js +1 -1
  146. package/dist/modules/launcher/monolithic_runtime.js.map +1 -1
  147. package/dist/modules/launcher/status_reporting.d.ts +1 -2
  148. package/dist/modules/launcher/status_reporting.d.ts.map +1 -1
  149. package/dist/modules/launcher/status_reporting.js +1 -1
  150. package/dist/modules/launcher/status_reporting.js.map +1 -1
  151. package/dist/modules/order/export.d.ts +1 -8
  152. package/dist/modules/order/export.d.ts.map +1 -1
  153. package/dist/modules/order/export.js +1 -1
  154. package/dist/modules/order/export.js.map +1 -1
  155. package/dist/modules/order/grid.d.ts +7 -0
  156. package/dist/modules/order/grid.d.ts.map +1 -1
  157. package/dist/modules/order/grid.js +52 -98
  158. package/dist/modules/order/grid.js.map +1 -1
  159. package/dist/modules/order/grid_reconcile_internal.d.ts +1 -10
  160. package/dist/modules/order/grid_reconcile_internal.d.ts.map +1 -1
  161. package/dist/modules/order/grid_reconcile_internal.js +2 -2
  162. package/dist/modules/order/grid_reconcile_internal.js.map +1 -1
  163. package/dist/modules/order/manager.d.ts +10 -2
  164. package/dist/modules/order/manager.d.ts.map +1 -1
  165. package/dist/modules/order/manager.js +17 -6
  166. package/dist/modules/order/manager.js.map +1 -1
  167. package/dist/modules/order/sync_engine.d.ts.map +1 -1
  168. package/dist/modules/order/sync_engine.js +8 -15
  169. package/dist/modules/order/sync_engine.js.map +1 -1
  170. package/dist/modules/order/utils/math.d.ts +1 -10
  171. package/dist/modules/order/utils/math.d.ts.map +1 -1
  172. package/dist/modules/order/utils/math.js +1 -1
  173. package/dist/modules/order/utils/math.js.map +1 -1
  174. package/dist/modules/order/utils/system.d.ts +0 -15
  175. package/dist/modules/order/utils/system.d.ts.map +1 -1
  176. package/dist/modules/order/utils/system.js +2 -2
  177. package/dist/modules/order/utils/system.js.map +1 -1
  178. package/dist/modules/process_discovery.d.ts +0 -3
  179. package/dist/modules/process_discovery.d.ts.map +1 -1
  180. package/dist/modules/process_discovery.js +1 -1
  181. package/dist/modules/process_discovery.js.map +1 -1
  182. package/dist/modules/utils/chain_logs.d.ts +1 -2
  183. package/dist/modules/utils/chain_logs.d.ts.map +1 -1
  184. package/dist/modules/utils/chain_logs.js +1 -1
  185. package/dist/modules/utils/chain_logs.js.map +1 -1
  186. package/dist/scripts/analyze-git.js +2 -2
  187. package/dist/scripts/analyze-git.js.map +1 -1
  188. package/dist/scripts/update.js +46 -31
  189. package/dist/scripts/update.js.map +1 -1
  190. package/docs/BITSHARES_ONBOARDING.md +110 -40
  191. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +10 -207
  192. package/docs/COW_INVARIANTS.md +16 -10
  193. package/docs/DEXBOT_COMPARISON.md +3 -3
  194. package/docs/EVOLUTION.md +75 -30
  195. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +6 -6
  196. package/docs/GRID_RECALCULATION.md +14 -6
  197. package/docs/GRID_RECONCILE.md +28 -25
  198. package/docs/LIFECYCLE.md +12 -11
  199. package/docs/README.md +48 -42
  200. package/docs/architecture.md +19 -30
  201. package/docs/developer_guide.md +3 -3
  202. package/package.json +1 -1
  203. package/scripts/git-viewer.sh +1 -1
  204. package/tests/README.md +10 -1
@@ -13,7 +13,7 @@ Reconciliation aligns the bot's model with on-chain reality. It runs at startup
13
13
 
14
14
  ### Why Not Cancel Everything
15
15
 
16
- - No atomic cancel+create on BitShares — `cancel_order` cancels the full order; there is no partial size reduction
16
+ - No atomic cancel+create on BitShares — `limit_order_cancel` cancels the full order; there is no partial size reduction
17
17
  - A full teardown leaves the bot unable to trade during the rebuild window
18
18
 
19
19
  ---
@@ -132,8 +132,8 @@ If Phase 2 partially succeeds (some cancels, some creates fail), there is no rol
132
132
  ### Timeouts and Read Coverage
133
133
 
134
134
  - **No per-attempt race** around the reconcile itself — the 1.4.8 change removed it to avoid orphaning mid-batch broadcasts (see the [`recalculateGrid`](../modules/order/grid.ts) call site in `modules/order/grid.ts`).
135
- - The whole resync is bounded by a **10-minute total timeout** (`PIPELINE_TIMING.TIMEOUT_MS * 2` at `grid.ts:1184`), applied via `Promise.race` at `grid.ts:1279`.
136
- - Every internal chain read goes through `readOpenOrdersGuarded` (`chain_orders.ts:610`) with the 30s / 3-retry / node-failover standard, and empty/truncated reads are treated as **ambiguous** — never as authoritative absence.
135
+ - The whole resync is bounded by a **10-minute total timeout** (`PIPELINE_TIMING.TIMEOUT_MS * 2` at `grid.ts:1511`), applied via `Promise.race` at `grid.ts:1617`.
136
+ - Every internal chain read goes through `readOpenOrdersGuarded` (`chain_orders.ts:608`) with the 30s / 3-retry / node-failover standard, and empty/truncated reads are treated as **ambiguous** — never as authoritative absence.
137
137
 
138
138
  ---
139
139
 
@@ -141,7 +141,7 @@ If Phase 2 partially succeeds (some cancels, some creates fail), there is no rol
141
141
 
142
142
  ### Fresh Grid Guard (`matchedOnGrid > 0`)
143
143
 
144
- **`grid_reconcile_internal.ts:1600`**
144
+ **`grid_reconcile_internal.ts:1738`**
145
145
 
146
146
  When a brand-new grid is generated, every slot is VIRTUAL — `matchedOnGrid = 0`. Without a guard, every on-chain order appears "unmatched" and would be cancelled as excess:
147
147
 
@@ -155,27 +155,27 @@ When `matchedOnGrid === 0` AND scaling up (`neededSlots > 0`), excess cancellati
155
155
 
156
156
  ### Grid-Edge Lock
157
157
 
158
- **`grid_reconcile_internal.ts:244`** — `_isGridEdgeFullyActive` detects when the grid boundary is fully active (all slots on-chain) before cancelling excess orders.
158
+ **`grid_reconcile_internal.ts:355`** — `_isGridEdgeFullyActive` detects when the grid boundary is fully active (all slots on-chain) before cancelling excess orders.
159
159
 
160
- When all outermost orders of a side are ACTIVE with `orderId`, all balance is committed to the edges. Cancel the **largest** order among the update candidates (`_cancelLargestOrder`, line 314) to free maximum funds with minimum operations, since the DEX does not expose partial-reduce in one operation. The cancelled slot gets a replacement create.
160
+ When all outermost orders of a side are ACTIVE with `orderId`, all balance is committed to the edges. Cancel the **largest** order among the update candidates (`_cancelLargestOrder`, line 425) to free maximum funds with minimum operations, since the DEX does not expose partial-reduce in one operation. The cancelled slot gets a replacement create.
161
161
 
162
- Detection (`_isGridEdgeFullyActive`, line 244): sort orders by price (BUY descending, SELL ascending), and check the outermost ones are all `isOrderPlaced()`.
162
+ Detection (`_isGridEdgeFullyActive`, line 355): sort orders by price (BUY descending, SELL ascending), and check the outermost ones are all `isOrderPlaced()`.
163
163
 
164
- ### Duplicate Tolerance (5× Multiplier)
164
+ ### Duplicate Cancellation
165
165
 
166
- **`grid_reconcile.ts:246-311`**
166
+ **`grid_reconcile.ts:278`**
167
167
 
168
- `SUSPECTED_DUPLICATE_TOLERANCE_MULTIPLIER = 5`. An unmatched chain order within 5× price tolerance of an active same-type grid slot is a suspected duplicate → queued for Phase 2 cancellation (not cancelled under lock). The base tolerance comes from `calculatePriceTolerance`, which estimates the maximum acceptable price deviation for the order's size and the grid's price step.
168
+ An unmatched chain order whose price equals an active same-type grid slot's price — exact slot-price equality via `priceSlotEqual` at the asset precision — is a **suspected duplicate** → queued for Phase 2 cancellation (not cancelled under lock). Non-equal neighbours are only logged with nearest-same-side diagnostics, never cancelled here. The earlier fuzzy `SUSPECTED_DUPLICATE_TOLERANCE_MULTIPLIER` (5× `calculatePriceTolerance`) was removed.
169
169
 
170
170
  ### Batch Update Failure Recovery
171
171
 
172
- **`grid_reconcile.ts:393-465`**
172
+ **`grid_reconcile.ts:436`**
173
173
 
174
174
  Up to 3 batch attempts. Each failure triggers a recovery sync + plan refresh. If all plans are empty → resolved early. After 3× → sequential fallback with per-plan recovery (each individual failure triggers a recovery sync + queue refresh).
175
175
 
176
176
  ### Phantom Orders via Reconcile
177
177
 
178
- **`grid_reconcile.ts:211-244`** — Reconcile's role in the defense-in-depth: during Phase 1, any ACTIVE/PARTIAL order whose `orderId` is not found on-chain is reset to VIRTUAL with `skipAccounting`. The freshly-assigned deferral protects in-flight broadcasts, and the ghost heuristic lets known fills pass. See [`developer_guide.md`](developer_guide.md#phantom-orders-prevention-defense-in-depth) for the full 3-layer defense.
178
+ **`grid_reconcile.ts:227-253`** — Reconcile's role in the defense-in-depth: during Phase 1, any ACTIVE/PARTIAL order whose `orderId` is not found on-chain is reset to VIRTUAL with `skipAccounting`. The freshly-assigned deferral protects in-flight broadcasts, and the ghost heuristic lets known fills pass. See [`developer_guide.md`](developer_guide.md#phantom-orders-prevention-defense-in-depth) for the full 3-layer defense.
179
179
 
180
180
  ### Shelf Orders (Fork-Kept Manual Orders)
181
181
 
@@ -189,13 +189,17 @@ Live on-chain orders with non-slot-N ids below the rail (e.g. `deep-*` manuals k
189
189
 
190
190
  Reconcile Phase 1 runs under `_gridLock` with no side effects on the frozen master Map. The working grid is not involved — reconcile is a startup operation that runs before the COW pipeline is active. See [`COPY_ON_WRITE_MASTER_PLAN.md`](COPY_ON_WRITE_MASTER_PLAN.md#safety-guardrails) and [`COW_INVARIANTS.md`](COW_INVARIANTS.md#reconcile-grid_reconcilemd) for COW rules.
191
191
 
192
+ ### Slot-Price Invariant at the Reconcile Emission Sites
193
+
194
+ Three of the six guarded emission sites are reconcile sites (`RECONCILE-CREATE`, `RECONCILE-UPDATE`, `STARTUP-CREATE` in `grid_reconcile_internal.ts`): every op reconcile emits is checked against the slot's genesis level and an off-grid emission is skipped, not broadcast — see [`GRID_PRICE_INVARIANT.md`](GRID_PRICE_INVARIANT.md). The coupling is bidirectional: the invariant guard's persistent-rejection escalation and the deferred-hold escalation both exit through the same structural resync (debounced reload → full reset) described here, and a full reset's update-first reconcile emits the rail's genesis level, so the guard does not block its own resolution.
195
+
192
196
  ### Truncated-Read Ambiguity (since 1.4.8)
193
197
 
194
- Every chain read feeding an absence/surplus decision goes through `readOpenOrdersGuarded` (`chain_orders.ts:610`) and treats an empty or truncated snapshot as **unreadable** — never as "nothing landed" or "nothing to cancel":
198
+ Every chain read feeding an absence/surplus decision goes through `readOpenOrdersGuarded` (`chain_orders.ts:608`) and treats an empty or truncated snapshot as **unreadable** — never as "nothing landed" or "nothing to cancel":
195
199
 
196
- - `_recoverSyncFromChain` (`grid_reconcile_internal.ts:592`) — plus its three recovery sites in `_createOrderFromGrid` / `_cancelChainOrder` — defers on empty/truncated reads (`deferEmpty: true`). A pass-1 phantom cleanup would otherwise virtualize live slots from a partial window.
197
- - `_adoptPossiblyLandedCreate` (`grid_reconcile_internal.ts:932`) defers to an uncertain outcome on truncated reads, and the startup group batch uncertain verification follows the same rule.
198
- - Phase 3 final refresh (`grid_reconcile.ts:512`) skips adoption/surplus-cancel on a truncated read, keeping the pre-phase-2 counts for the summary log.
200
+ - `_recoverSyncFromChain` (`grid_reconcile_internal.ts:726`) — plus its three recovery sites in `_createOrderFromGrid` / `_cancelChainOrder` — defers on empty/truncated reads (`deferEmpty: true`). A pass-1 phantom cleanup would otherwise virtualize live slots from a partial window.
201
+ - `_adoptPossiblyLandedCreate` (`grid_reconcile_internal.ts:1112`) defers to an uncertain outcome on truncated reads, and the startup group batch uncertain verification follows the same rule.
202
+ - Phase 3 final refresh (`grid_reconcile.ts:533`) skips adoption/surplus-cancel on a truncated read, keeping the pre-phase-2 counts for the summary log.
199
203
  - Adoption paths (`_adoptPossiblyLandedCreate`, grouping path, reconcile adoption loop) apply the create-fee deduction via `_applySync` for accounting parity.
200
204
 
201
205
  The underlying rule is `INV-BROADCAST-004`: a capped `get_full_accounts` window omits the freshest orders (fresh creates sort last), so absence can never be authoritative on a truncated read.
@@ -204,7 +208,7 @@ The underlying rule is `INV-BROADCAST-004`: a capped `get_full_accounts` window
204
208
 
205
209
  ## Lock Hierarchy
206
210
 
207
- **`manager.ts:474-489`** — canonical reference in [`developer_guide.md`](developer_guide.md#lock-ordering-for-deadlock-prevention).
211
+ **`manager.ts:593-597`** — canonical reference in [`developer_guide.md`](developer_guide.md#lock-ordering-for-deadlock-prevention).
208
212
 
209
213
  ```
210
214
  Level 0: _fillProcessingLock Level 1: _divergenceLock
@@ -230,11 +234,10 @@ Commit `e64db685` replaced 6 single-value boolean state fields with refcounts/st
230
234
 
231
235
  | Constant | Value | File | Role |
232
236
  |----------|-------|------|------|
233
- | `SUSPECTED_DUPLICATE_TOLERANCE_MULTIPLIER` | `5` | `grid_reconcile.ts:20` | Amplifies base tolerance for duplicate detection |
234
- | `maxBatchAttempts` | `3` | `grid_reconcile.ts:415` | Update-batch retry limit |
235
- | `PRICE_TOLERANCE_MAX_PERCENT` | `0.01` (1%) | `constants.ts:452` | Cap on price tolerance |
236
- | `PRICE_TOLERANCE_MIN_ABSOLUTE` | `0.0001` | `constants.ts:456` | Floor for price tolerance |
237
- | `PIPELINE_TIMING.TIMEOUT_MS` | `300000` (5min) | `constants.ts:800` | Base pipeline timing; resync uses 2× (10 min) |
237
+ | `maxBatchAttempts` | `3` | `grid_reconcile.ts:436` | Update-batch retry limit |
238
+ | `PRICE_TOLERANCE_MAX_PERCENT` | `0.01` (1%) | `constants.ts:566` | Cap on price tolerance |
239
+ | `PRICE_TOLERANCE_MIN_ABSOLUTE` | `0.0001` | `constants.ts:570` | Floor for price tolerance |
240
+ | `PIPELINE_TIMING.TIMEOUT_MS` | `300000` (5min) | `constants.ts:973` | Base pipeline timing; resync uses 2× (10 min) |
238
241
 
239
242
  ---
240
243
 
@@ -260,10 +263,10 @@ Commit `e64db685` replaced 6 single-value boolean state fields with refcounts/st
260
263
 
261
264
  | File | Role |
262
265
  |------|------|
263
- | `modules/order/grid_reconcile.ts` | Public API + 3-phase orchestrator (642 lines) |
264
- | `modules/order/grid_reconcile_internal.ts` | Internal helpers — `_reconcileStartupSide`, grid detection, recovery, uncertainty (1675 lines) |
266
+ | `modules/order/grid_reconcile.ts` | Public API + 3-phase orchestrator (670 lines) |
267
+ | `modules/order/grid_reconcile_internal.ts` | Internal helpers — `_reconcileStartupSide`, grid detection, recovery, uncertainty (2132 lines) |
265
268
  | `modules/order/manager.ts` | Lock hierarchy definition, `_applyOrderUpdate`, phantom guard, `reconcileGrid` entry, COW integration |
266
- | `modules/order/async_lock.ts` | AsyncLock engine with ALS re-entrancy (424 lines) |
269
+ | `modules/order/async_lock.ts` | AsyncLock engine with ALS re-entrancy (435 lines) |
267
270
  | `modules/order/sync_engine.ts` | Blockchain sync pipeline |
268
271
  | `modules/order/grid.ts` | Grid creation, `recalculateGrid` (full resync) calls reconcile |
269
272
  | `modules/chain_orders.ts` | `readOpenOrdersGuarded` / guarded read infrastructure |
package/docs/LIFECYCLE.md CHANGED
@@ -90,7 +90,7 @@ sequenceDiagram
90
90
  participant CO as chain_orders (broadcast)
91
91
  participant STORE as Storage
92
92
 
93
- CH->>Q: enqueue fill(s) (dexbot_fill_runtime.ts:325)
93
+ CH->>Q: enqueue fill(s) (dexbot_fill_runtime.ts:414)
94
94
  FR->>FR: drain queue -> _processFillsWithBatching
95
95
  FR->>OM: processFilledOrders() (manager.ts)
96
96
  OM->>AC: processFillAccounting() (single call, batch)
@@ -105,7 +105,7 @@ sequenceDiagram
105
105
  ```
106
106
 
107
107
  Why it matters:
108
- - **Gap-slot batching** (batch size = grid gap-slot count, `DEXBot._getGapSlotBatchSize`) keeps bursts
108
+ - **Gap-slot batching** (batch size = grid gap-slot count + 1, `DEXBot._getGapSlotBatchSize`) keeps bursts
109
109
  deterministic — see `docs/architecture.md` §"Fill Processing Pipeline".
110
110
  - **Single rebalance cycle**: all fills in a batch share one broadcast, so proceeds
111
111
  are immediately available for replacement sizing (no split-across-cycles delay).
@@ -134,10 +134,10 @@ sequenceDiagram
134
134
  participant STORE as Storage
135
135
 
136
136
  MA->>CL: AMA center snapshot updated
137
- CL->>CL: _performPeriodicGridChecks() (dexbot_class.ts:1694)
138
- CL->>RT: performPeriodicGridChecks() (dexbot_maintenance_runtime.ts:1043)
139
- RT->>RT: runGridMaintenance(bot,'periodic') (dexbot_maintenance_runtime.ts:1845)
140
- RT->>RT: executeMaintenanceLogic() (dexbot_maintenance_runtime.ts:1452)
137
+ CL->>CL: _performPeriodicGridChecks() (dexbot_class.ts:1673)
138
+ CL->>RT: performPeriodicGridChecks() (dexbot_maintenance_runtime.ts:1554)
139
+ RT->>RT: runGridMaintenance(bot,'periodic') (dexbot_maintenance_runtime.ts:2770)
140
+ RT->>RT: executeMaintenanceLogic() (dexbot_maintenance_runtime.ts:2270)
141
141
  RT->>AC: recalculate funds from balances
142
142
  RT->>GD: promote AMA center -> grid center
143
143
  RT->>GD: recalculateGrid() (grid.ts)
@@ -157,12 +157,12 @@ The AMA signal stack (AMA/Kalman/Hurst/PE) is *research-tuned* in `analysis/` an
157
157
  the parameters.
158
158
 
159
159
  > Note: `runMaintenance()` is a **different** subsystem — the credit/MPA debt
160
- > runtime (`modules/credit_runtime.ts:3041`, reached via
161
- > `_runCreditRuntimeMaintenance` at `dexbot_class.ts:1794`). The grid maintenance
160
+ > runtime (`modules/credit_runtime.ts:3019`, reached via
161
+ > `_runCreditRuntimeMaintenance` at `dexbot_class.ts:1790`). The grid maintenance
162
162
  > chain above is the one that matters for order/price upkeep.
163
163
 
164
- References: `modules/dexbot_class.ts:1694` (`_performPeriodicGridChecks`) →
165
- `modules/dexbot_maintenance_runtime.ts:1043` (`performPeriodicGridChecks`) →
164
+ References: `modules/dexbot_class.ts:1673` (`_performPeriodicGridChecks`) →
165
+ `modules/dexbot_maintenance_runtime.ts:1554` (`performPeriodicGridChecks`) →
166
166
  `:1845` (`runGridMaintenance`) → `:1452` (`executeMaintenanceLogic`),
167
167
  `docs/GRID_RECALCULATION.md`, `docs/GRID_RECONCILE.md`.
168
168
 
@@ -179,6 +179,7 @@ enforced*, not compiler-enforced — learn them or you will introduce fund bugs.
179
179
  | **Fund SSOT** | `Accounting` owns every fund number. Nothing else computes available funds. | `docs/architecture.md` §"Fund Flow Architecture" |
180
180
  | **Replay-safe fills** | A fill is credited exactly once via processed-fill keys; retries are idempotent. | `modules/dexbot_fill_runtime.ts` |
181
181
  | **Single broadcast per cycle** | One `updateOrdersOnChainBatch` per rebalance — never scatter writes. | `docs/architecture.md` §"Fill Processing Pipeline" |
182
+ | **Slot price = genesis level** | Every emitted order's price must equal `priceForSlot(idx, genesis)` for its slot — range guards cannot substitute for grid membership; off-grid emissions are blocked. | `docs/GRID_PRICE_INVARIANT.md` |
182
183
  | **Browser/Node split** | Heavy runtime is Node-only; never import it from a browser bundle. | `AGENTS.md` "Browser-Safe Surface", `package.json` "browser" field |
183
184
  | **Lock ordering** | Fill drain and maintenance must not run a rebalance concurrently. | `docs/developer_guide.md` §"Startup Sequence & Lock Ordering" |
184
185
 
@@ -191,7 +192,7 @@ enforced*, not compiler-enforced — learn them or you will introduce fund bugs.
191
192
  | How a fill becomes orders | `modules/dexbot_fill_runtime.ts` → `modules/order/manager.ts` |
192
193
  | Grid math / recalculation | `modules/order/grid.ts`, `docs/GRID_RECALCULATION.md` |
193
194
  | Funds & accounting | `modules/order/accounting.ts`, `docs/FUND_MOVEMENT_AND_ACCOUNTING.md` |
194
- | Periodic loop & AMA hook | `modules/dexbot_maintenance_runtime.ts`, `modules/dexbot_class.ts:1694` |
195
+ | Periodic loop & AMA hook | `modules/dexbot_maintenance_runtime.ts`, `modules/dexbot_class.ts:1673` |
195
196
  | Market signal source | `market_adapter/market_adapter.ts`, `analysis/README.md` |
196
197
  | Startup & orchestration | `modules/dexbot_class.ts`, `docs/developer_guide.md` §"Startup Sequence" |
197
198
  | Why COW exists | `docs/architecture.md` §"Copy-on-Write (COW) Grid Pattern", `docs/COW_INVARIANTS.md` |
package/docs/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  This directory contains the comprehensive technical documentation for the DEXBot2 trading bot. It is designed to guide developers from high-level architecture down to the nuances of fund accounting and state management.
4
4
 
5
- **Version context:** v1.6.3 (released).
5
+ **Version context:** v1.6.4 (released).
6
6
 
7
7
  ---
8
8
 
@@ -116,6 +116,38 @@ This directory contains the comprehensive technical documentation for the DEXBot
116
116
  - **Lifecycle B (Maintenance / AMA-Driven)**: Periodic path from `_performPeriodicGridChecks` → `executeMaintenanceLogic`.
117
117
  - **Cross-Cutting Invariants**: COW boundary, fund SSOT, replay-safe fills, lock ordering.
118
118
 
119
+ ### 🧩 [Copy-on-Write Master Plan](COPY_ON_WRITE_MASTER_PLAN.md)
120
+ *COW design, phases, and state machine details.*
121
+ - **Architecture**: Master-grid projection model and rebalance flow
122
+ - **Lifecycle**: Implementation phases, commit boundaries, and test coverage
123
+ - **Safety**: Invariants and guardrails for concurrent updates
124
+
125
+ ### 🔒 [COW Invariants](COW_INVARIANTS.md)
126
+ *Stable theory contract for COW pipeline.*
127
+ - **Non-negotiable invariants**: Master immutability, commit atomicity, projection rules, accounting separation
128
+ - **Test mapping**: Links each invariant to regression tests
129
+ - **Review checklist**: Quick-use verification for COW/accounting changes
130
+
131
+ ### 📐 [Grid-Price Invariant](GRID_PRICE_INVARIANT.md)
132
+ *Why a slot's emitted price must equal its genesis level — and how that failed.*
133
+ - **The invariant**: `order.price === priceForSlot(idx, genesis)`, and why range guards cannot substitute for it
134
+ - **Failure mechanism**: Chain price overwriting slot identity, pre-broadcast substitution, untrusted fill-guard pivot
135
+ - **Enforcement**: The six emission sites, the blocking rejection of off-grid emissions, the final pre-broadcast pivot gate, and the fail-open policy on unjudgeable inputs
136
+ - **Out-of-bounds policy**: Hold and surface; refill in-grid slots at their genesis price
137
+ - **Status**: Landed enforcement map, key constants, and why the removed 5% sanity gate must not be naively re-landed
138
+
139
+ ### 💰 [Fund Movement & Accounting](FUND_MOVEMENT_AND_ACCOUNTING.md)
140
+ *The most critical part of the bot: safe capital management.*
141
+ - **Single Source of Truth**: How the bot avoids double-spending and out-of-sync balances.
142
+ - **Optimistic ChainFree**: The mechanism that allows the bot to trade with fill proceeds before they are finalized on-chain.
143
+ - **Fill Batch Processing**: Fixed-cap batching for efficient fill processing (`<=4` unified, `>4` chunked)
144
+ - **Partial Order Consolidation**: Simplified, direct consolidation through grid rebuilding (no merge/split mechanics)
145
+ - **Dust Detection & Management**: Partials below the dust threshold are cancelled on-chain immediately on detection (no delay, no timer)
146
+ - **BTS Fee Object Structure**: `netProceeds` field for accounting precision
147
+ - **BUY Side Sizing & Fee Accounting**: Correct fee application by order side
148
+ - **Mixed Order Fund Validation**: Separate validation for BUY vs SELL order fund checks
149
+ - **Fee Management**: Detailed logic for BTS fee reservations and market fee deductions.
150
+
119
151
  ### 📖 [Developer Guide](developer_guide.md)
120
152
  *Your daily companion for coding.*
121
153
  - **Quick Start**: How to get the development environment running.
@@ -136,57 +168,31 @@ This directory contains the comprehensive technical documentation for the DEXBot
136
168
  - **Branching Strategy**: Explanation of the `test` → `dev` → `main` lifecycle.
137
169
  - **CI/CD Patterns**: Standards for merging and ensuring code quality across branches.
138
170
 
139
- ### 🧮 [DEXBot vs DEXBot2 Comparison](DEXBOT_COMPARISON.md)
140
- *Architectural, functional, and operational comparison with the original Python DEXBot.*
141
- - **Scope**: Full side-by-side of technology stack, architecture, trading strategies, order management, configuration, blockchain integration, fund accounting, and concurrency safety
142
- - **Audience**: Developers and operators evaluating or migrating between the two projects
171
+ ### 🧪 [Test Suite](../tests/README.md)
172
+ *Test organization, categories, and key architectural patterns tested.*
173
+ - **Test Layout**: Directory structure, helpers, and quick-start commands
174
+ - **Categories**: Core infrastructure, order management, COW rebalancing, fees/accounting, integration, edge cases, and more
175
+ - **Architectural Patterns**: COW rebalancing, RMS divergence, and fund invariants with doc cross-references
143
176
 
144
177
  ### 🧭 [Evolution Report](EVOLUTION.md)
145
178
  *Project timeline and major architecture phases.*
146
179
  - **Coverage**: Historical milestones from bootstrap through the current stable release; per-release detail lives in [CHANGELOG.md](../CHANGELOG.md)
147
180
  - **Focus**: Architecture evolution, release history, and test growth
148
181
 
182
+ ### ⏪ [Order Engine Retrospective](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md)
183
+ *Why the post-1.0.0 order engine kept misbehaving — synthesis plus the incident/fix ledger.*
184
+ - **Part I — Synthesis**: root cause (uncertain broadcast), recurring bug families, meta-patterns, what actually fixed it, lessons
185
+ - **Part II — Incident & Fix Ledger**: preserved gap-band / ladder-recenter / orphan-fill / price-first plans with `LANDED`/`REVERTED`/`SUPERSEDED` status and commit hashes
186
+ - **Regression gate**: `npm run analysis:grid-check` (see [analysis/README.md](../analysis/README.md))
187
+
149
188
  ### 🗒️ [Changelog](../CHANGELOG.md)
150
189
  *Release notes and documentation history.*
151
190
  - **Scope**: Versioned notes per release
152
191
 
153
- ### 🧩 [Copy-on-Write Master Plan](COPY_ON_WRITE_MASTER_PLAN.md)
154
- *COW design, phases, and state machine details.*
155
- - **Architecture**: Master-grid projection model and rebalance flow
156
- - **Lifecycle**: Implementation phases, commit boundaries, and test coverage
157
- - **Safety**: Invariants and guardrails for concurrent updates
158
-
159
- ### 🔒 [COW Invariants](COW_INVARIANTS.md)
160
- *Stable theory contract for COW pipeline.*
161
- - **Non-negotiable invariants**: Master immutability, commit atomicity, projection rules, accounting separation
162
- - **Test mapping**: Links each invariant to regression tests
163
- - **Review checklist**: Quick-use verification for COW/accounting changes
164
-
165
- ### 📐 [Grid-Price Invariant](GRID_PRICE_INVARIANT.md)
166
- *Why a slot's emitted price must equal its genesis level — and how that failed.*
167
- - **The invariant**: `order.price === priceForSlot(idx, genesis)`, and why range guards cannot substitute for it
168
- - **Failure mechanism**: Chain price overwriting slot identity, pre-broadcast substitution, untrusted fill-guard pivot
169
- - **Enforcement**: The six emission sites, the blocking rejection of off-grid emissions, and the fail-open policy on unjudgeable inputs
170
- - **Out-of-bounds policy**: Hold and surface; refill in-grid slots at their genesis price
171
- - **Status**: What is landed, what remains open, and why the removed 5% sanity gate must not be naively re-landed
172
-
173
- ### 🧪 [Test Suite](../tests/README.md)
174
- *Test organization, categories, and key architectural patterns tested.*
175
- - **Test Layout**: Directory structure, helpers, and quick-start commands
176
- - **Categories**: Core infrastructure, order management, COW rebalancing, fees/accounting, integration, edge cases, and more
177
- - **Architectural Patterns**: COW rebalancing, RMS divergence, and fund invariants with doc cross-references
178
-
179
- ### 💰 [Fund Movement & Accounting](FUND_MOVEMENT_AND_ACCOUNTING.md)
180
- *The most critical part of the bot: safe capital management.*
181
- - **Single Source of Truth**: How the bot avoids double-spending and out-of-sync balances.
182
- - **Optimistic ChainFree**: The mechanism that allows the bot to trade with fill proceeds before they are finalized on-chain.
183
- - **Fill Batch Processing**: Fixed-cap batching for efficient fill processing (`<=4` unified, `>4` chunked)
184
- - **Partial Order Consolidation**: Simplified, direct consolidation through grid rebuilding (no merge/split mechanics)
185
- - **Dust Detection & Management**: Partials below the dust threshold are cancelled on-chain immediately on detection (no delay, no timer)
186
- - **BTS Fee Object Structure**: `netProceeds` field for accounting precision
187
- - **BUY Side Sizing & Fee Accounting**: Correct fee application by order side
188
- - **Mixed Order Fund Validation**: Separate validation for BUY vs SELL order fund checks
189
- - **Fee Management**: Detailed logic for BTS fee reservations and market fee deductions.
192
+ ### 🧮 [DEXBot vs DEXBot2 Comparison](DEXBOT_COMPARISON.md)
193
+ *Architectural, functional, and operational comparison with the original Python DEXBot.*
194
+ - **Scope**: Full side-by-side of technology stack, architecture, trading strategies, order management, configuration, blockchain integration, fund accounting, and concurrency safety
195
+ - **Audience**: Developers and operators evaluating or migrating between the two projects
190
196
 
191
197
  ---
192
198
 
@@ -377,13 +377,13 @@ The fill pipeline handles incoming filled orders efficiently through fixed-cap b
377
377
  ↓
378
378
  ┌─────────────────────────────────────────────────────────────┐
379
379
  │ processFilledOrders() - Entry Point │
380
- │ Use gap-slot batch size for deterministic batching │
381
- │ Rules: <=gapSlots unified, >gapSlots chunked │
380
+ │ Use gap-slot batch size (gapSlots+1) for deterministic batching │
381
+ │ Rules: <=gapSlots+1 unified, >gapSlots+1 chunked │
382
382
  └─────────────────────┬───────────────────────────────────────┘
383
383
  ↓
384
384
  ┌─────────────────────────────────────────────────────────────┐
385
- │ Pop Batch (up to gapSlots) │
386
- │ Takes N fills from queue head (N = 1..gapSlots) │
385
+ │ Pop Batch (up to gapSlots+1) │
386
+ │ Takes N fills from queue head (N = 1..gapSlots+1) │
387
387
  │ Example: pops [fill1, fill2, fill3] for batch processing │
388
388
  └─────────────────────┬───────────────────────────────────────┘
389
389
  ↓
@@ -418,9 +418,9 @@ The fill pipeline handles incoming filled orders efficiently through fixed-cap b
418
418
 
419
419
  ### Key Properties
420
420
 
421
- - **Gap-Slot Batch Sizing**: Batch size is deterministic, derived from the grid gap-slot count (`DEXBot._getGapSlotBatchSize`)
422
- - 1..gapSlots awaiting: single unified batch (one rebalance/broadcast cycle)
423
- - more than gapSlots awaiting: repeated chunks of gapSlots (last chunk may be smaller)
421
+ - **Gap-Slot Batch Sizing**: Batch size is deterministic, derived from the grid gap-slot count + 1 (`DEXBot._getGapSlotBatchSize`)
422
+ - 1..gapSlots+1 awaiting: single unified batch (one rebalance/broadcast cycle)
423
+ - more than gapSlots+1 awaiting: repeated chunks of gapSlots+1 (last chunk may be smaller)
424
424
 
425
425
  - **Single Rebalance Cycle**: All fills in batch processed in ONE rebalance
426
426
  - No "split across cycles" delays
@@ -916,7 +916,7 @@ graph TB
916
916
  START[Grid Update Triggered] --> CALC[Calculate Ideal Grid<br/>Based on current funds]
917
917
  CALC --> RELOAD[Force Reload Persisted Grid<br/>Ensure fresh blockchain state]
918
918
  RELOAD --> COMPARE[Compare to Persisted Grid]
919
- COMPARE --> RMS[Calculate RMS Divergence<br/>For PARTIAL orders only]
919
+ COMPARE --> RMS[Calculate RMS Divergence<br/>ACTIVE + VIRTUAL orders per side]
920
920
 
921
921
  RMS --> CHECK{RMS > Threshold?}
922
922
  CHECK -->|Yes| UPDATE[Update Grid Sizes<br/>Trigger rebalance]
@@ -1043,28 +1043,17 @@ graph LR
1043
1043
 
1044
1044
  The system has been optimized to use a "memory-driven" model for order updates, eliminating redundant blockchain API calls during normal operation.
1045
1045
 
1046
- ### Key Changes
1047
-
1048
- **1. Raw Order Cache (`rawOnChain`)**
1049
- - Grid slots now store exact blockchain order representations (integers/satoshis) in a `rawOnChain` cache
1050
- - **Birth**: Cache populated immediately after successful order placement using broadcasted arguments
1051
- - **Partial Fills**: Cache updated in-place via integer subtraction (subtracting filled satoshis from `for_sale`)
1052
- - **Updates/Rotations**: Cache refreshed with adjusted integers returned by build process
1053
-
1054
- **2. Eliminated Redundant API Calls**
1055
- - Removed all `readOpenOrders()` calls from `_buildSizeUpdateOps()` and `_buildRotationOps()`
1056
- - Removed `computeVirtualOpenOrders()` logic that was redundantly fetching entire account state
1057
- - The bot now trusts its internal state, backed by real-time fill listener, to build transactions
1058
-
1059
- **3. Refactored `buildUpdateOrderOp()`**
1060
- - Updated to support optional `cachedOrder` parameter
1061
- - Allows callers to bypass blockchain queries if they have raw state in memory
1062
- - Returns `finalInts` along with operation data for local tracking
1063
-
1064
- **4. Self-Healing Resilience**
1065
- - Maintains "State Recovery Sync" fallback
1066
- - If a memory-driven transaction fails, bot catches error and performs a full refresh
1067
- - Ensures internal ledger stays synchronized with BitShares blockchain
1046
+ ### How it works
1047
+
1048
+ - **Raw order cache (`rawOnChain`):** each grid slot stores the exact blockchain order integers
1049
+ (satoshis) — seeded from broadcast arguments on placement, updated in place on partial fills,
1050
+ and refreshed on updates/rotations.
1051
+ - **Chain-free planning:** size updates and rotations build their operations from the cache;
1052
+ only placements and recovery syncs query the blockchain.
1053
+ - **`buildUpdateOrderOp(cachedOrder?)`:** accepts an optional cached order and returns
1054
+ `finalInts` alongside the operation for local tracking.
1055
+ - **Self-healing:** a failed memory-driven transaction triggers a full state-recovery sync so the
1056
+ internal ledger stays consistent with the chain.
1068
1057
 
1069
1058
  ### Benefits
1070
1059
  - **Faster reaction time**: No waiting for blockchain queries during order updates
@@ -79,7 +79,7 @@ A **phantom order** is an order in ACTIVE/PARTIAL state WITHOUT a valid `orderId
79
79
 
80
80
  | Term | Meaning |
81
81
  |------|---------|
82
- | **Gap-Slot Batch Fill Processing** | Groups fills using the grid gap-slot count as batch size (`DEXBot._getGapSlotBatchSize`): `<= gapSlots` uses one unified batch; `> gapSlots` chunks at gapSlots. In the documented 29-fill Feb 7 crash scenario, this reduces the estimated divergence window from ~90s to ~24s; see [`FUND_MOVEMENT_AND_ACCOUNTING.md`](FUND_MOVEMENT_AND_ACCOUNTING.md#15-fill-batch-processing--timeline). |
82
+ | **Gap-Slot Batch Fill Processing** | Groups fills using the grid gap-slot count + 1 as batch size (`DEXBot._getGapSlotBatchSize`): `<= gapSlots + 1` uses one unified batch; `> gapSlots + 1` chunks at `gapSlots + 1`. In the documented 29-fill Feb 7 crash scenario, this reduces the estimated divergence window from ~90s to ~24s; see [`FUND_MOVEMENT_AND_ACCOUNTING.md`](FUND_MOVEMENT_AND_ACCOUNTING.md#15-fill-batch-processing--timeline). |
83
83
  | **Recovery Retry System** | Count+time-based retry mechanism with periodic reset. Replaces one-shot `_recoveryAttempted` flag. Max 5 attempts per episode with 60s minimum interval between retries. |
84
84
  | **Orphan-Fill Deduplication** | Map+TTL-based tracking of stale-cleaned order IDs to prevent double-crediting. Delayed orphan fill events are still blocked by checking `_staleCleanedOrderIds`. |
85
85
 
@@ -171,8 +171,8 @@ A **phantom order** is an order in ACTIVE/PARTIAL state WITHOUT a valid `orderId
171
171
  | **Atomic Check-and-Deduct** | Verify funds + deduct in single operation |
172
172
  | **Divergence Detection** | Comparing ideal grid vs. persisted grid |
173
173
  | **Invariant Verification** | Checking fund accounting consistency |
174
- | **Batch Processing** | Grouping multiple fills into a single rebalance cycle instead of one-at-a-time. Gap-slot sizing: `<= gapSlots` unified, otherwise chunked at gapSlots. |
175
- | **Gap-Slot Batch Sizing** | Deterministic chunking model with the grid gap-slot count as the per-broadcast bound. Keeps throughput high while avoiding tier-lookup complexity. |
174
+ | **Batch Processing** | Grouping multiple fills into a single rebalance cycle instead of one-at-a-time. Gap-slot sizing: `<= gapSlots + 1` unified, otherwise chunked at `gapSlots + 1`. |
175
+ | **Gap-Slot Batch Sizing** | Deterministic chunking model with the grid gap-slot count + 1 as the per-broadcast bound. Keeps throughput high while avoiding tier-lookup complexity. |
176
176
  | **Stale-Order Recovery** | Fast-path recovery for single-operation batches that encounter stale orders on-chain. Executes cleanup without full state sync. |
177
177
  | **Orphan-Fill Prevention** | Deduplication mechanism that prevents double-crediting fills from stale-cleaned orders using timestamp-based ID tracking (TTL pruning). |
178
178
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dexbot",
3
- "version": "1.6.3",
3
+ "version": "1.6.4",
4
4
  "description": "The first open source trading bot with zero runtime dependencies and a fully adaptive market making strategy.",
5
5
  "main": "dist/modules/dexbot_class.js",
6
6
  "exports": {
@@ -44,7 +44,7 @@ check_dependencies() {
44
44
  elif command -v dnf &> /dev/null; then
45
45
  sudo dnf install -y "${missing_packages[@]}"
46
46
  elif command -v pacman &> /dev/null; then
47
- sudo pacman -S --noconfirm "${missing_packages[@]}"
47
+ sudo pacman -Syu --noconfirm "${missing_packages[@]}"
48
48
  else
49
49
  echo "Warning: Could not detect package manager. Please install manually: ${missing_packages[@]}"
50
50
  echo " apt-get: sudo apt-get install ${missing_packages[*]}"
package/tests/README.md CHANGED
@@ -88,7 +88,7 @@ Interactive tools and performance benchmarks (not part of CI).
88
88
 
89
89
  ### Edge Cases & Regression
90
90
  Tests targeting specific bugs, race conditions, and failure modes.
91
- *Examples:* `test_critical_bug_fixes.ts`, `test_race_condition_fixes_batch1.ts`, `test_patch17_invariants.ts`, `test_shutdown_reentrancy.ts`, `test_multifill_opposite_partial.ts`
91
+ *Examples:* `test_critical_bug_fixes.ts`, `test_race_condition_fixes_batch1.ts`, `test_patch17_invariants.ts`, `test_shutdown_reentrancy.ts`, `test_multifill_opposite_partial.ts`, `test_correction_queue_staleness.ts`, `test_spread_pure_fund_driven.ts`, `test_sync_lock_id_verification.ts`
92
92
 
93
93
  ### Utilities & Helpers
94
94
  Shared utility functions, precision handling, chain helpers.
@@ -120,6 +120,15 @@ Shared utility functions, precision handling, chain helpers.
120
120
 
121
121
  **Reference:** [docs/FUND_MOVEMENT_AND_ACCOUNTING.md](../docs/FUND_MOVEMENT_AND_ACCOUNTING.md)
122
122
 
123
+ ### Grid-Price Invariant & Hold Guards
124
+ - Every emitted order's price must equal its slot's genesis level (`priceForSlot(idx, genesis)`); off-grid emissions are blocked, not counted
125
+ - The guard itself plus the live batch wiring, escalation thresholds, and per-order stranded-hold clocks are each pinned and mutation-tested
126
+ - Adoption keeps the slot's own level; `loadGrid` repairs a pre-existing off-grid slot price
127
+
128
+ **Reference:** [docs/GRID_PRICE_INVARIANT.md](../docs/GRID_PRICE_INVARIANT.md)
129
+
130
+ **Examples:** `test_grid_price_invariant_guard.ts`, `test_grid_price_invariant_wiring.ts`, `test_grid_price_slot_invariant.ts`, `test_final_pivot_gate.ts`, `test_hold_and_center_guards.ts`, `test_sync_out_of_grid_defer.ts`
131
+
123
132
  ---
124
133
 
125
134
  ## Documentation References