dexbot 1.7.0 → 1.7.1

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 (105) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +3 -3
  3. package/analysis/README.md +33 -13
  4. package/claw/package.json +1 -1
  5. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  7. package/dist/analysis/account_resolver.js +5 -6
  8. package/dist/analysis/analyze_liquidity.js +15 -4
  9. package/dist/analysis/bot_key_utils.d.ts +44 -1
  10. package/dist/analysis/bot_key_utils.js +76 -7
  11. package/dist/analysis/fills_cache.js +2 -1
  12. package/dist/analysis/grid_correction_check.d.ts +1 -19
  13. package/dist/analysis/grid_correction_check.js +12 -30
  14. package/dist/analysis/liquidity/liquidity_chart_generator.js +190 -20
  15. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +41 -16
  16. package/dist/analysis/liquidity/liquidity_depth_model.js +49 -21
  17. package/dist/analysis/liquidity/liquidity_view.d.ts +15 -0
  18. package/dist/analysis/liquidity/liquidity_view.js +11 -0
  19. package/dist/analysis/resolve_bot_accounts.js +7 -6
  20. package/dist/analysis/trade_profitability.js +2 -1
  21. package/dist/credential-daemon.js +13 -2
  22. package/dist/dexbot.js +4 -4
  23. package/dist/modules/account_bots.d.ts +11 -1
  24. package/dist/modules/account_orders.d.ts +12 -0
  25. package/dist/modules/account_orders.js +30 -0
  26. package/dist/modules/bitshares-native/transport.js +24 -6
  27. package/dist/modules/bitshares_client.d.ts +24 -6
  28. package/dist/modules/bitshares_client.js +44 -7
  29. package/dist/modules/bot_settings.d.ts +2 -0
  30. package/dist/modules/constants.d.ts +26 -3
  31. package/dist/modules/constants.js +63 -8
  32. package/dist/modules/dexbot_class.d.ts +1 -6
  33. package/dist/modules/dexbot_class.js +14 -0
  34. package/dist/modules/dexbot_cow_runtime.d.ts +97 -7
  35. package/dist/modules/dexbot_cow_runtime.js +620 -132
  36. package/dist/modules/dexbot_fill_runtime.js +124 -35
  37. package/dist/modules/dexbot_maintenance_runtime.js +226 -73
  38. package/dist/modules/dexbot_startup_runtime.js +32 -20
  39. package/dist/modules/dexbot_state_recovery.d.ts +33 -1
  40. package/dist/modules/dexbot_state_recovery.js +167 -5
  41. package/dist/modules/node_connect_policy.d.ts +8 -1
  42. package/dist/modules/node_connect_policy.js +18 -2
  43. package/dist/modules/node_flap_score.d.ts +87 -0
  44. package/dist/modules/node_flap_score.js +124 -0
  45. package/dist/modules/node_health_cache.d.ts +40 -3
  46. package/dist/modules/node_health_cache.js +66 -20
  47. package/dist/modules/node_manager.d.ts +101 -19
  48. package/dist/modules/node_manager.js +255 -65
  49. package/dist/modules/order/accounting.js +56 -7
  50. package/dist/modules/order/format.d.ts +24 -10
  51. package/dist/modules/order/format.js +30 -10
  52. package/dist/modules/order/grid.js +82 -11
  53. package/dist/modules/order/grid_reconcile.d.ts +5 -1
  54. package/dist/modules/order/grid_reconcile.js +333 -210
  55. package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
  56. package/dist/modules/order/grid_reconcile_internal.js +207 -87
  57. package/dist/modules/order/index.d.ts +4 -0
  58. package/dist/modules/order/lifecycle.d.ts +353 -0
  59. package/dist/modules/order/lifecycle.js +1109 -0
  60. package/dist/modules/order/manager.d.ts +271 -5
  61. package/dist/modules/order/manager.js +651 -48
  62. package/dist/modules/order/placement_lock.d.ts +102 -0
  63. package/dist/modules/order/placement_lock.js +222 -0
  64. package/dist/modules/order/strategy.js +13 -1
  65. package/dist/modules/order/sync_engine.d.ts +13 -1
  66. package/dist/modules/order/sync_engine.js +153 -53
  67. package/dist/modules/order/utils/math.d.ts +22 -1
  68. package/dist/modules/order/utils/math.js +54 -1
  69. package/dist/modules/order/utils/order.d.ts +75 -5
  70. package/dist/modules/order/utils/order.js +158 -9
  71. package/dist/modules/order/utils/system.d.ts +18 -0
  72. package/dist/modules/order/utils/system.js +84 -8
  73. package/dist/modules/order/utils/validate.d.ts +7 -1
  74. package/dist/modules/order/utils/validate.js +48 -2
  75. package/dist/modules/outcome.d.ts +54 -0
  76. package/dist/modules/outcome.js +51 -0
  77. package/dist/modules/settings_merge.d.ts +4 -0
  78. package/dist/modules/settings_merge.js +9 -0
  79. package/dist/modules/timing_policy.d.ts +82 -0
  80. package/dist/modules/timing_policy.js +244 -0
  81. package/dist/modules/types.d.ts +132 -0
  82. package/dist/scripts/analyze-credit.js +54 -17
  83. package/dist/scripts/analyze-orders.d.ts +4 -2
  84. package/dist/scripts/analyze-orders.js +113 -34
  85. package/dist/scripts/chart_targets.js +11 -15
  86. package/dist/scripts/test-credit-renewal.js +12 -5
  87. package/docs/COW_INVARIANTS.md +67 -8
  88. package/docs/DEXBOT_COMPARISON.md +6 -6
  89. package/docs/EVOLUTION.md +9 -8
  90. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  91. package/docs/GRID_PRICE_INVARIANT.md +1 -1
  92. package/docs/GRID_RECONCILE.md +17 -12
  93. package/docs/LOGGING.md +25 -1
  94. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +175 -26
  95. package/docs/README.md +23 -2
  96. package/docs/WORKFLOW.md +9 -3
  97. package/docs/architecture.md +42 -5
  98. package/docs/developer_guide.md +25 -8
  99. package/modules/README.md +3 -0
  100. package/package.json +1 -1
  101. package/scripts/README.md +16 -0
  102. package/scripts/pdev.sh +14 -1
  103. package/scripts/pmain.sh +23 -8
  104. package/scripts/ptest.sh +7 -0
  105. package/tests/README.md +30 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,48 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.7.1] - 2026-11-04 - One Existence Record per Slot, Placement-Region Hardening, Forced-Retreat Gap Evacuation, Fee-Adjusted Pool Depth, Stability-Ranked Nodes
6
+
7
+ ### 2026-11-04
8
+
9
+ - **Feat(order)**: unify chain existence behind one lifecycle registry — "does this order exist on chain, and how sure are we?" was answered from seven structures with seven different clocks (`_pendingBroadcasts`, `createUncertain`, `_committedOrderIds` + its built-at stamp, `_orderIdAssignedAt`, `_placedAt`, `_chainSizeAppliedFills`, `_lastUnmatchedChainOrders`), and four read sites each consulted a different subset, which is why every fix resurfaced in a new path. `modules/order/lifecycle.ts` now owns ONE record per slot (intent → chain id → partial → gone) and the legacy structures become live Map/Set views onto it, projected in through `_applyOrderUpdate`, so no site has to remember which structure to touch. Behaviour that falls out of having one answer: sync pass 1 no longer reads an unparseable chain entry as absent (a live-but-undecodable order used to be virtualized and re-CREATEd on top of itself); an ABANDONED pending CREATE records `unknown` instead of a clean hole (a lost receipt turning into a duplicate order); a filled or virtualized id loses protection; the placement stamp lands on the slot record (300 rotations across 5 slots previously leaked 300 unreachable order-keyed records and reported every order as not-freshly-placed); a create-uncertain slot reads `unknown` without writing; and an unrelated slot mutation cannot downgrade unresolved evidence to `intent`. Risk: a consumer that relied on a narrower guard defers cleanup one cycle instead of virtualizing — the fail-safe direction, bounded by 2x the pending-broadcast TTL. Docs: new `docs/ORDER_LIFECYCLE.md`. Covered by new `tests/test_order_lifecycle.ts` plus `recon_fuzz`.
10
+
11
+ - **Feat(order)**: make broadcast uncertainty a typed three-valued outcome — an unknown batch result was encoded as an ad-hoc `uncertain: true` beside a second ad-hoc flag (`ambiguousRead`), set by hand at four sites, so the two could disagree and nothing forced a consumer to handle "we do not know" at all. `modules/outcome.ts` is now the only place those results are constructed (`unknownCowOutcome(cause)` derives both flags from one cause and refuses to let a caller field override them), and the four COW return sites name their cause explicitly (`ambiguous-read`, `unavailable`, `lost-receipt`). Behavioral impact: the same fields are returned with the same values, but they can no longer be set inconsistently. Covered by new `tests/test_outcome_contract.ts` and the extended `test_uncertain_broadcast`.
12
+
13
+ - **Feat(order)**: classify every timing window and gate its growth — the engine carried 84 timing knobs, a number that grew because every "the state was briefly wrong" bug was fixed by adding a wait, and nothing ever removed one. `modules/timing_policy.ts` classifies every window as `external` (how long the outside world takes), `bound` (a leak/GC cap that cannot produce a wrong decision), `policy` (a deliberate product choice) or `self-healing` (compensates for our own lost state — a REMOVAL TARGET that must name the replacing evidence), with the two timings computed from other timings declared as derived. Current split: 33 external, 19 bound, 26 policy, 6 self-healing. `tests/test_timing_policy.ts` fails on an unclassified window, so the inventory can only shrink by decision, and pins the derived relationships under override. The six removal targets are deliberately not deleted here: each changes live trading behaviour and needs live validation. Docs: new `docs/TIMING_INVENTORY.md`. Risk: none behavioural — no value changed and no window removed; only new failure mode is a build failure when an unexplained window is added.
14
+
15
+ - **Test(order)**: add an interleaving fuzzer for the reconciliation engine — the engine's failure modes are interleavings (a fill that lands before the snapshot that would have matched it, a read that lags a confirmed broadcast, a truncated snapshot that looks exactly like "the account is empty"), which example-based tests cannot enumerate. `tests/recon_fuzz.ts` drives the REAL `SyncEngine` against a deterministic scripted chain with nine adversarial operations (land, vanish, partial fill, full fill, orphan, duplicate-level, un-adoptable stray, lagging read, unparseable read) and asserts eight policy-free invariants after EVERY event: one slot per chain id, one order per (type, price) level, lifecycle agreement, structural soundness, fund sanity, and "every parseable chain order is accounted for — tracked, reported unmatched, or queued for cancel". It deliberately asserts no policy ("clean after exactly N cycles" would encode one grace and reject correct alternatives), shrinks a failing sequence to a seed + step count replayable with `RECON_FUZZ_SEED`/`RECON_FUZZ_STEPS`, and fails on vacuous runs via coverage floors. Verified by mutation: dropping a duplicate-level orphan report shrinks to a five-step reproduction. Deliberately not `test_*.ts`, so `npm test` stays pass/fail.
16
+
17
+ - **Fix(order)**: one writer per life-cycle clock, one guard per absence decision — a review of the new lifecycle/placement arc found every finding to be the same shape: one question answered in more than one place. (1) `_commitWorkingGrid` swaps the master map wholesale and bypassed the write funnel, so a COW-placed order got no `assignedAt`/`placedAt` at all — the 15-minute surplus-cancel grace was inert on the PRIMARY placement path; every committed slot is now projected through `_syncLifecycleFromMutation` first. (2) `_applyOrderUpdate` wrote both stamps a second time on top of the funnel; one writer now. (3) `timingWindowMs()` replaces five copy-pasted `Number(TIMING.X) > 0 ? … : <literal>` fallbacks, and the reconcile reads gap geometry and the `createUncertain` marker through `resolveGapSlots`/`isSlotCreateUncertain` instead of raw fields it could disagree with. (4) sync pass 1 asked a SUBSET of the absence guard while the startup reconcile and the recovery sweep asked `isInFlight()`, so an order whose CREATE receipt was merely lost could be virtualized and re-created — all three sites now ask `isInFlight()` through `readSlotLifecycle`. (5) Evidence is now ranked and monotonic within a phase (a local re-assertion cannot overwrite a `chain-snapshot`, and pass-2 adoption records `adoption` evidence), so `observedAt` means "when the chain last told us" again. (6) `observe`/`markIntent`/`setPending` cleared `pending` but left the fingerprint index, so `pendingSize()`/`getPending()` disagreed with the engine's facade. (7) The unresolved bound was refreshable for free (the funnel re-asserts `unknown` on every mutation); `recordedAt` now advances only on a phase change or chain-backed evidence, `markIntentIfResolved` resolves an expired unknown, `prune` can evict past-bound records, and a synthesized record is no longer stamped fresh on every read. Covered by new sections in `tests/test_order_lifecycle.ts` plus `ageChainIdAssignment()` in the order test helpers.
18
+
19
+ - **Fix(order)**: serialize the placement paths and re-verify their lease before broadcasting — a trigger-file grid rebuild could run while a fill-driven COW rebalance was mid-plan: the rebuild marked the working grid stale, the bounded stale-plan handler re-planned from a master with no chain ids, that re-plan emitted CREATEs at levels the startup reconcile was concurrently re-pricing via UPDATE, and the startup surplus sweep cancelled only what its lagging read could see — 25 duplicate-price orders on chain in a production incident. `modules/order/placement_lock.ts` introduces a token-based exclusive placement region (bounded wait, shutdown force-release, `isPlacementLeaseCurrent()` via a token WeakMap), `manager.withPlacement()` is the single acquire/release contract with `allowDuringRebuild` for a rebuild's own reconcile, the COW body and the reconcile now re-check their own lease immediately before `startBroadcasting`/Phase 2 and abort (`PLACEMENT_LEASE_LOST`) or discard the plan instead of shipping from a region the watchdog already released, a stale plan caused by a structural rebuild is aborted instead of re-planned create-only (dropping its pending-broadcast entries), the startup surplus sweep skips on a lagging read or live pending broadcasts, `_clearStalePlacementRegion()` is the single teardown authority (it refuses while a younger pipeline counter proves progress and clears the region's stale broadcast refcount atomically), and `endStructuralRebuild()` notifies region end so "never wake into a live broadcast region" has one spelling. Cancel-only holders stay exempt (a cancel carries its own id and cannot duplicate a CREATE). Docs: `INV-BROADCAST-005`, INV-MAINT-001 correction, placement-region section in architecture/developer guide, new `[PLACEMENT]` LOGGING rows. Covered by new `tests/test_placement_lock.ts`, `tests/test_structural_rebuild_guard.ts`, `tests/test_startup_dust_policy.ts`, plus COW-GUARD-REPLAN-006 and Regression 9i.
20
+
21
+ - **Fix(order)**: close the follow-up gaps in placement and fill-marker handling — an audit of the placement arc found one-directional watchdog cross-checks, a fill-marker flag that could mask a partial applied amount, a reconcile CREATE guard that only matched slot ids, an unrestored per-batch anchor budget, and one liveness policy duplicated three times. Fill accounting: the legacy `alreadyAppliedChainSize` boolean is a FALLBACK, not a floor (a group where one entry was marked no longer skips the unapplied remainder of its siblings), and the zero-remainder brake runs after residual verification so a clamped-to-zero fill is virtualized while the chain residual it leaves is still cancelled. Planner/guards: `getLivePendingBroadcasts()` is the single pending-broadcast liveness policy (used by the COW guard, crossing candidates, the reconcile surplus sweep, the maintenance sync gate and the reconcile CREATE path, replacing two hand-rolled TTLs and a no-TTL raw-map read), reconcile CREATEs are refused on a pending-broadcast level match as well as a slot-id match, and a stale-plan re-plan hands back the abandoned plan's absolute re-anchor so an abandoned plan cannot consume the batch's one anchor. Placement: the maintenance tick no longer tears placement down and clears the refcount in separate steps, and the nested correction drain verifies its inherited lease instead of the always-true `isPlacementActive()`. Covered by extended fill-transition, placement-lock, price-collision and COW re-plan suites.
22
+
23
+ - **Fix(order)**: make pass-1 fill markers accumulate and persist, and revalidate pending CREATEs on startup — the pass-1 size markers were single-shot, in-memory only, and double-released the trade's drum (`3.6604 → 3.3046 → 2.9488`), because the duplicate was the second size release rather than the trade. Markers now accumulate and partially consume, persist with the grid snapshot, and keep the trade's pays/receives in fill accounting; corrupt-snapshot rejection is gated on a settled pipeline (empty fill queue, no fill batch, no deferred rebalance/owed crawls); pending uncertain CREATEs join the CREATE collision set with a 30-minute TTL; PARTIAL update targets are planned at the booked remainder; dust chain-count subtraction uses the actually queued cancel count. Also: the COW placement lease is released on every pre-broadcast exit (the `try/finally` now starts at claim time), a placement stale-region watchdog exists, placement-backed regions defer fills past the broadcast bound instead of falling through into a live region, and the fill queue wakes on pipeline force-clear. Covered by `tests/test_fill_transition_idempotency.ts` and `tests/test_snapshot_reject_gate.ts`.
24
+
25
+ - **Fix(gap-evac)**: let forced retreats evacuate, then re-plan the committed band — a live market-pair bot lost its fixed spread: a fill inside the band crawled the boundary down and stranded the live orders above it, the plan's evacuation rotations were refused as stale by LAST-FILL-GUARD (re-proven against the PRE-COMMIT geometry where those slots are still rail members), the batch committed the retreat with the stranded orders still live, and plans are fill-driven — so on a quiet market nothing ever re-planned and the 2.0% band sat at 1.21% for hours while every plan reported success. `liveRailsConflictWithGap` now identifies the no-consistent-boundary case (`maxBuy > minSell - gap - 1`) and `forcedRetreatJustifiesEvacuation` is the single decision point for all three stale-stamp sites, refusing to override a stamp whose source/dest ids are unparseable; the unstamped branch still re-proves direction and size live, and every other stale stamp still fails closed (the 2026-10-30 bid-edge non-regression is pinned). A committed-geometry sweep (`scheduleGapEvacRepair`, hooked after a successful commit and on every maintenance tick) detects live orders inside the COMMITTED band, re-derives the streak ledger and schedules a fill-less re-plan, with the cancel-only teeth as fallback only (never in the same tick), rate-limited to one repair per bot per minute, and unknown geometry treated as unknown. Docs: `INV-COW-011`, LOGGING rows. Covered by new `tests/test_gap_evac_spread_collapse.ts`.
26
+
27
+ - **Fix(gap-evac)**: don't let the cancel teeth destroy the rotation that evacuates — the first live run of the committed-geometry sweep repaired the band through the wrong path: the sweep ticked the streak ledger a second time for the same observation (a restored streak of 1 reached the cancel threshold of 3 in one cycle), and the cancel-only teeth queued cancels for the two chain orders the plan was rotating, so the pre-batch correction drain executed them first, the UPDATE batch found its own sources gone, and the grid fell back to a structural resync plus full reload. `updateGapEvacuationStreaks` gains `increment: false` (re-derive: prune resolved ids, report readiness) and the sweep uses it, and `splitEvacuationCancelsSupersededByRotations` holds any cancel-only evacuation whose chain order this batch rotates out of the drain (restoring it afterwards, so it is dropped as stale once the slot no longer owns the order) while unrelated corrections keep draining. Behavioral impact: a stranded-band repair is now one batch of in-place price updates — no cancels, no "target(s) missing on chain" rejection, no reload. Docs: `[COW] Holding N gap-evacuation cancel(s)` line and corrected tick/hold semantics.
28
+
29
+ - **Fix(geometry)**: stop reading unknown gap geometry as gap 0 — an absent gap band classified the slot just above the boundary as a SELL rail member, mis-classifying in-band orphan adoption (sync engine, fill runtime) and booking SPREAD-placeholder size on the wrong side (accounting), i.e. it could hide or double-count exactly the orders GAP-EVAC exists to evacuate. `resolveGapSlots` is now the fallback in all four sites. The same "absent reads as 0" pattern made restore telemetry lie: `loadGrid` called `_restoreBoundary` before publishing `_gapSlots`, and `_logBoundaryDebug` read the raw field with a `0` fallback, so every restart printed `gapSlots=0 sellStart=boundary+1 spreadCount=0` — indistinguishable from a genuinely collapsed band (this is what produced the "bot lost its fixed spread, only one slot is used" report on a healthy 4-slot band). `_gapSlots` is published before the restore gate, the debug line resolves through `resolveGapSlots` and prints `spreadCount=?` until measured (new `_spreadCountKnown`, so a measured EMPTY band still prints 0). Behavioral impact: adoption/accounting are unchanged whenever the gap is set (the normal case); only the unknown fallback and the restore line change.
30
+
31
+ - **Fix(order)**: repair stranded boundaries without re-arming on replays — the boundary could teleport on a replayed fill and then stay stranded: the orphan sweep re-attributed already-booked fills (re-arming the pivot and owed crawls from a stale execution price), the refill hold pinned a fill-driven retreat to the old boundary, and both boundary writers refused a move that reduced — but did not eliminate — in-band orders. Fill attribution now runs only when the processed ledger did not report `duplicate`; the refill hold is scoped to the promotion direction (BUY up / SELL down) and resolves its side from the plan/master grid; the re-anchor and the rail clamp share one rule (accept a move only when it strands strictly fewer placed orders than the committed boundary; equal counts and structural refusals stay closed); and spread promotion steps over a same-side placed band edge (absorbing it as a rail member) instead of stopping there, with depth counting both so reserve/stranding caps still bound the slide. Docs: `COW_INVARIANTS`, `GRID_RECONCILE`, architecture, `LOGGING`.
32
+
33
+ - **Fix(analyze)**: classify grid slots by type in `dexbot order` — the report bucketed BUY/SELL slots with `i <= boundaryIdx` slicing, so a live order stranded inside the spread band was dropped from every bucket: the counts summed to fewer slots than the grid holds and the "real" spread was measured from the geometry edge (2.02% reported against 1.21% on chain, with two live buys hidden inside a 4-slot band), which made a collapsed spread invisible to operators exactly when they needed to see it. Buckets and rail lists are now type-based, matching the runtime's `getGridBestPrices`/`calculateSpreadFromOrders`; the new `gapBand.inBandPlaced` names every live order resting strictly inside the band and the report prints a "Spread band occupied" warning; the band width comes from the snapshot's frozen genesis and then the live config, staying unknown when geometry is unknown. Behavioral impact: the reported spread changes for snapshots carrying in-band live orders — that is the point; clean snapshots report exactly as before.
34
+
35
+ - **Fix(analysis)**: use the live last-fill predicate in the offline checker — `analysis/grid_correction_check.ts` carried its own copy of `isLastFillGuardBlocked` labelled "mirrors `modules/order/utils/system.ts` 1:1", which had already drifted (it still returned the removed `halfInc` band term). The checker now imports the predicate from the runtime module, so the offline verdict is the runtime binding rather than a re-derivation; the direction verdicts are unchanged, and the rule's release in the header and `--help` is corrected from v1.6.16+ to v1.6.17+.
36
+
37
+ - **Fix(node)**: rank nodes by connection stability, not ping alone — a live run showed all 52 abnormal socket closes landing on the three CDN-fronted public endpoints while the endpoints that were never selected dropped none, and the bot spent 46% of its connected time on the flapping ones: selection sorted on raw latency, and live-transport strikes were erased by a successful health probe, so the blacklist threshold was almost unreachable at a 4h probe interval. New `modules/node_flap_score.ts` (pure, browser-safe, time-decayed churn scoring: effective latency = latency + Σ 0.5^(age/halfLife) · perDrop over a capped 24h window) feeds `node_manager`'s ranking, strikes now decay over `FAILURE_STRIKE_DECAY_MS` instead of being wiped (ledger reseeded so count and ledger stay in step), churn is persisted through `node_health_cache` (and removing a node no longer erases a sibling's history), `restartBitsharesConnection` keeps a healthy socket when the active node is already valid (~88 needless reconnects/re-subscribes in 18 days), the connect policy keeps the connected node in the candidate list, the credential daemon no longer evicts it, and failure reports name the node the operation actually ran on instead of `getBestNode()`. `FAILURE_STRIKE_DECAY_MS` and the `FLAP_*` defaults are surfaced as `NODES.healthCheck.{strikeDecayMs,flapHalfLifeMs,flapPenaltyMsPerDrop,flapPenaltyMaxMs}`. Behavioral impact: a flapping node is demoted for up to a day and can finally be blacklisted; a stable node still wins on ping when nothing flaps, and `preferredNode` still overrides ranking.
38
+
39
+ - **Feat(cli)**: accept a chain account as the `<bot>` target for `credit`/`order` — `dexbot credit [<bot>]` matched only a bot name/key, so passing an account name or `1.2.x` id (the grouping chain positions actually use) reported "no credit bot found" although `dexbot pnl` accepts `<bot|account>`. The matching rule set had also been duplicated five ways with subtly different semantics, so it now lives in `analysis/bot_key_utils` as `matchBotEntryTarget` (name/key), `matchBotAccountTarget` (`preferredAccount` name or typed `1.2.x` id, or the `accountId` stamped by `account_resolver.ts`) and `matchBotTargetIn` (every match, tagged `matchedBy`), letting each caller choose the spellings it accepts; an account target selects every bot entry on it. Diagnostics now separate "no such bot/account", "matched only inactive entries" and "no enabled entry has `debtPolicy.lending`", listing matched entries instead of asserting nothing matched. Two more copies folded away: the `1.2.x` regex is `isAccountIdRef()` and `analyze-orders` calls `computeBotKey` instead of its own verbatim copy. `tv`/`dw`/`liquid` stay bot-only (one account can back several bots). Read-only surface; bot runtime untouched. Docs: README cheat sheet, `docs/WORKFLOW.md`, `analysis/README.md`, `scripts/README.md`, help/examples. Covered by new `tests/test_credit_cli_target.ts` and `tests/test_bot_key_utils.ts`.
40
+
41
+ - **Feat(liquidity)**: price the pool curve net of the AMM fee and show both spreads — the depth chart plotted the raw `x*y = k` curve, so the pool's two sides met at the reserve price even though a taker always pays the pool fee: the pool looked like a zero-spread venue and the fee existed only as a badge. The curve is now parameterized by the fee-adjusted effective price (the chain takes the fee off the output side and keeps it), so bid and ask depth stop at `(1-f)·p0` and `p0/(1-f)` — the fee band a taker must cross — while cumulative depth keeps its local slope and still satisfies `x*y = k` for the fee-free reserves; `f = 0` collapses onto the previous curve. The chart shades the order-book spread next to the pool fee band, the readout lists each percentage with its absolute edges and tags the tighter one, and both follow an inverted price. The guide labels moved out of the band into one aligned block drawn at a device-pixel-ratio-correct size (uPlot leaves the 2D context unscaled, so the fixed 11px font rendered at half size on HiDPI). Percentages share one rule through `formatPercentLabel` (2 decimals below 100%, 1 from 100%, none from 1000%, fixed-point so SI suffixes cannot leak into a spread). Display-only: no bot, adapter or order-engine path touched. Covered by `tests/test_liquidity_depth.ts` and `tests/test_format_percent.ts`.
42
+
43
+ - **Fix(scripts)**: abort branch promotion before it moves anything and make `pmain` atomic — the force-push promotion scripts could move a ref before discovering that the remote was unreachable (a live SSH outage left a half-synced `dev`/`main`). A read-only preflight probe now runs before any ref moves: a dead remote, a missing remote or an unset remote aborts with a clear message before `test`/`dev` and `dev`/`main` diverge, and `pmain` mirrors both refs through one atomic push so it can no longer half-sync. The probe honours a skip env for CI and is documented as point-in-time: a flapping auth path can still fail at the push, where the atomic mirror bounds the damage to "neither". Docs: `scripts/README.md`, `docs/WORKFLOW.md`. Verified with `bash -n` on all four scripts and against the live outage (5/6 probes aborted, every ref unchanged).
44
+
45
+ - **Docs**: record the lifecycle and timing invariants and reconcile the retrospective — new `INV-LIFE-001..005` (unknown is never gone; one record per slot; one definition per guard — absence uses `isInFlight`, the committed guard uses `isRecentlyCommitted`, the fresh-id guard uses `isRecentlyAssigned`; unresolved records are never evicted or downgraded; an unparseable chain entry makes absence unknown, not absent) and `INV-TIME-001` (every timing window is classified, and a self-healing window must name the evidence that replaces it) join the stable theory contract, so a change that reintroduces the old ambiguity is a review failure rather than a judgement call. `ORDER_ENGINE_POST_1.0_RETROSPECTIVE` is rescoped from v1.6.14 to v1.7.0 plus the unreleased arc (§9.10 marked released in v1.6.18, new §9.11 on fill identity/the pivot as a row/one existence record/violation-reducing repair, three new bug families in R2, four "what fixed it" entries in R4, lessons 12-14, a dead cited hash corrected), `COW_INVARIANTS` states the real duplicate rule (`chainPriceOnSameLevel`, not `calculatePriceTolerance`) and renumbers/extends the life-cycle invariants, `GRID_PRICE_INVARIANT` moves its review baseline to v1.7.0, and `modules/README.md` lists `order/lifecycle.ts` and `order/placement_lock.ts`. Full suite: 353/353 files (`npm test`, 14 live tests skipped); `typecheck`, `typecheck:analysis`, `check:any` and `verify:browser-bundle` clean.
46
+
5
47
  ## [1.7.0] - 2026-11-02 - Liquidity Depth Chart & `dexbot liquid`, Asset Distribution Shortcut, Pool-Ref Chart Targets, Case-Insensitive Asset Lookup, Orphan-Fill Attribution & Stale-Grid Re-Buy Discipline
6
48
 
7
49
  ### 2026-11-02
package/README.md CHANGED
@@ -337,7 +337,7 @@ dexbot reset {all|<bot>} # Regenerate grid
337
337
  dexbot disable {all|<bot>} # Disable bot in config
338
338
  dexbot enable {all|<bot>} # Enable bot in config
339
339
 
340
- dexbot order [<bot>] # Grid state: spread, increment, funds (--export → HTML)
340
+ dexbot order [<bot|account>] # Grid state: spread, increment, funds (--export → HTML)
341
341
  dexbot export <bot> # Trades + settings → CSV/JSON for analysis/
342
342
 
343
343
  dexbot tv <bot|pool|A/B> # TradingView 1h chart with AMA overlay (default: 3 months)
@@ -345,14 +345,14 @@ dexbot dw <bot|pool|A/B> # Dynamic-weight research chart (same targets/flag
345
345
  dexbot liquid <bot|pool|A/B> # Liquidity depth: order book + AMM pool (aliases: liq, liqu)
346
346
 
347
347
  dexbot pnl <bot|account> # HTML PnL report (--month N, optional --pair A/B)
348
- dexbot credit [<bot>] # Live summed MPA + borrowed-credit positions
348
+ dexbot credit [<bot|account>] # Live summed MPA + borrowed-credit positions
349
349
  dexbot asset <bts|symbol> # Supply distribution + HTML report (short: dexbot a bts)
350
350
  dexbot rich <asset...> # Top holders per asset
351
351
 
352
352
  dexbot update # Update DEXBot2
353
353
  dexbot clear # Delete log files in <profiles>/logs
354
354
  dexbot default # Reset settings to defaults
355
- dexbot help # Grouped command reference (runtime, trading, config, analysis, files)
355
+ dexbot help # Grouped command reference
356
356
  ```
357
357
 
358
358
  ## 🎯 PM2 Process Management
@@ -259,7 +259,7 @@ All amounts use the shared 4-significant-figure formatter (compact `K`/`M`, sign
259
259
 
260
260
  ### LAST-FILL-GUARD Check (`grid_correction_check.ts`)
261
261
 
262
- Validates LAST-FILL-GUARD discipline from the same Kibana fill pipeline as `trade_profitability.ts`. The rule is **direction only** (v1.6.16+): with the previous fill at price `p`, the next order must satisfy `BUY < p` and `SELL > p` (equal price is blocked — a re-place at the just-filled level). There is no increment band: the older `pivot ± i/2` rule blocked a BUY below a SELL fill and a SELL one tick above our cost, i.e. it flagged the tightening placements the engine legitimately makes. A violation is a buy fill at/above its pivot or a sell fill at/below it.
262
+ Validates LAST-FILL-GUARD discipline from the same Kibana fill pipeline as `trade_profitability.ts`. The rule is **direction only** (v1.6.17+) and comes from the runtime's own `isLastFillGuardBlocked` — the tool imports it instead of re-implementing it, so the offline verdict cannot drift from the live guard. With the previous fill at price `p`, the next order must satisfy `BUY < p` and `SELL > p` (equal price is blocked — a re-place at the just-filled level). There is no increment band: the older `pivot ± i/2` rule blocked a BUY below a SELL fill and a SELL one tick above our cost, i.e. it flagged the tightening placements the engine legitimately makes. A violation is a buy fill at/above its pivot or a sell fill at/below it.
263
263
 
264
264
  **Offline limits:** the tool reconstructs pivots from consecutive fills, so it cannot see the runtime's edge-pinned-fill exclusion (no slot identity per fill) nor the spread-correction bypass — expect rare false positives on wick/insurance fills.
265
265
 
@@ -321,28 +321,48 @@ to the book mid, and how far the two diverge.
321
321
  also swaps bid/ask roles and flips the depth asset to the new quote, so the
322
322
  chart stays a valid book view rather than a mirrored picture with the wrong sides
323
323
  - **Bids**: order-book bids (`quote` of every bid at price >= p) drawn next to
324
- the pool's `quoteReserve * (1 - sqrt(p / p0))` curve
324
+ the pool's fee-adjusted bid curve, which starts at `(1 - f) * p0` and nets
325
+ `(1 - f) * quoteReserve * (1 - sqrt(p / ((1 - f) * p0)))`
325
326
  - **Asks**: order-book asks (`quote` of every ask at price <= p) drawn next to
326
- the pool's `quoteReserve * (sqrt(p / p0) - 1)` curve
327
+ the pool's fee-adjusted ask curve, which starts at `p0 / (1 - f)` and is
328
+ `quoteReserve * (sqrt(p * (1 - f) / p0) - 1)`
329
+ - **Spread bands**: the order-book spread (best bid .. best ask, amber) and the
330
+ pool fee band (violet, between the fee-adjusted edges) are both shaded, so the
331
+ two spreads a taker could cross are directly comparable. The overlay lists
332
+ each percentage with its absolute edges and tags the tighter one; clicking the
333
+ x-axis to invert flips both bands with the rest of the view
327
334
 
328
335
  The window is symmetric around the pool price (book mid when there is no pool),
329
336
  so the whole `0.5x .. 1.5x` range is visible by default. The chain's
330
337
  `get_order_book` side convention is handled by the tool. Pool depth is the exact
331
- constant-product solution (verified against the `x*y = k` swap invariant); the
332
- AMM taker fee is **not** applied to the curve — matching PoolTool — and is shown
333
- in the header as metadata only. PoolTool's `depthchart.py` plots the same curves
334
- with the reciprocal price convention (`amount_y * (sqrt(p_pool/p) - 1)` for buys
335
- and `amount_y * (1 - sqrt(p_pool/p))` for sells).
338
+ constant-product solution (verified against the `x*y = k` swap invariant) and is
339
+ **net of the AMM taker fee** `f` (`taker_fee_percent / 100`): the chain charges
340
+ it on the output side and keeps it in the pool, so a swap's effective price is
341
+ `(1 - f) * p` when selling into the pool and `p / (1 - f)` when buying. The
342
+ curve is parameterized by that effective price, so the two pool curves no
343
+ longer meet at the pool price — they stop at their own edges, `(1 - f) * p0` and
344
+ `p0 / (1 - f)`, and the shaded band between them (`~2f` wide) is the AMM spread
345
+ a taker has to cross. That band is drawn in the chart next to the book spread,
346
+ reported in the readout (`BOOK` / `POOL` rows, with the tighter one tagged) and
347
+ in the header (`BOOK SPREAD`, `FEE … · POOL SPREAD …`), and mirrored in the
348
+ console summary (`pool edge bid/ask`). With `f = 0` the two sides collapse onto
349
+ the pool price and the curves match PoolTool's depth chart exactly. PoolTool's
350
+ `depthchart.py` plots the same fee-free curves with the reciprocal price
351
+ convention (`amount_y * (sqrt(p_pool/p) - 1)` for buys and
352
+ `amount_y * (1 - sqrt(p_pool/p))` for sells).
336
353
 
337
354
  Order-book depth prefers `get_limit_orders` (up to ~300 levels per side) over
338
355
  `get_order_book`, which many nodes cap at 50 — otherwise thin far levels are
339
356
  silently missing from the curves. If the wider call is unavailable the tool
340
357
  falls back to the classic 50-level endpoint.
341
358
 
342
- All displayed numbers use DEXBot's existing 4-active-digit formatters —
343
- `formatCurrency` for prices/percentages and `formatFundsValue` for amounts
344
- (`modules/order/format.ts`) — embedded into the generated page so it renders
345
- identically offline.
359
+ All displayed numbers use DEXBot's shared formatters (`modules/order/format.ts`)
360
+ embedded into the generated page so it renders identically offline:
361
+ `formatCurrency` for prices (4 active digits), `formatFundsValue` for amounts,
362
+ and `formatPercentLabel` for every percentage — 2 decimals below 100%
363
+ (`2.27%`, `0.40%`, `18.18%`), 1 from 100% (`100.0%`) and none from 1000%
364
+ (`1235%`), fixed-point so a small percentage never picks up the SI suffixes
365
+ `formatCurrency` produces.
346
366
 
347
367
  ```bash
348
368
  # Default example pair
@@ -613,7 +633,7 @@ Details: [bot_fitting/README.md](bot_fitting/README.md)
613
633
  | `chart_css.ts` | Shared uPlot CSS fragments for generated charts |
614
634
  | `chart_ui.ts` | Shared browser-side uPlot helpers (cursor, hover, zoom-reset, sizing) |
615
635
  | `math_utils.ts` | Shared math utilities |
616
- | `bot_key_utils.ts` | Bot-key resolution, candle file lookup, `accountId` persistence (`persistBotAccountId`) |
636
+ | `bot_key_utils.ts` | Bot-key resolution, `<bot|account>` target matching (`matchBotEntryTarget` / `matchBotAccountTarget` / `matchBotTargetIn` — shared by `credit`, `order`, `pnl` and the chart commands), candle file lookup, `accountId` persistence (`persistBotAccountId`) |
617
637
  | `account_resolver.ts` | Account resolution for all tools: `preferredAccount` / `--account` → `1.2.x`, stamping the result into `profiles/bots.json` |
618
638
  | `chain_pool.ts` | Ephemeral read-only chain client over the built-in node pool (account + asset lookups) |
619
639
  | `fills_source.ts` | Shared `fill_order` Kibana fetch/query and the static asset-precision table + on-chain cache |
package/claw/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dexbot2-claw",
3
- "version": "1.7.0",
3
+ "version": "1.7.1",
4
4
  "private": true,
5
5
  "description": "Claw bridge and runtime integration layer for BitShares and DEXBot2.",
6
6
  "type": "module",
@@ -2,7 +2,7 @@
2
2
  "id": "bitshares-claw",
3
3
  "name": "BitShares Claw",
4
4
  "description": "Native BitShares and DEXBot2 tools from the DEXBot2 claw integration",
5
- "version": "1.7.0",
5
+ "version": "1.7.1",
6
6
  "skills": [
7
7
  "skills"
8
8
  ],
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bitshares-claw-openclaw-plugin",
3
3
  "private": true,
4
- "version": "1.7.0",
4
+ "version": "1.7.1",
5
5
  "type": "module",
6
6
  "main": "index.js"
7
7
  }
@@ -11,9 +11,8 @@
11
11
  * handling — all of it lives here now.
12
12
  */
13
13
  import { getErrorMessage } from '../modules/utils/errors.js';
14
- import { findBotKeyByAccountRef, loadBotMeta, persistBotAccountId, resolveBotKey } from './bot_key_utils.js';
14
+ import { findBotKeyByAccountRef, isAccountIdRef, loadBotMeta, persistBotAccountId, resolveBotKey } from './bot_key_utils.js';
15
15
  import { withReadOnlyClient } from './chain_pool.js';
16
- const ACCOUNT_ID_RE = /^1\.2\.\d+$/;
17
16
  /** Default lookup: ephemeral read-only client over the built-in node pool. */
18
17
  async function lookupNameOnChain(name) {
19
18
  try {
@@ -62,7 +61,7 @@ async function resolveBotAccount(botKey, options = {}) {
62
61
  // An explicit override always wins and is never persisted.
63
62
  const override = overrideAccount != null ? String(overrideAccount).trim() : '';
64
63
  if (override) {
65
- if (ACCOUNT_ID_RE.test(override)) {
64
+ if (isAccountIdRef(override)) {
66
65
  return { accountId: override, botKey, botMeta, source: 'override-id', reason: null };
67
66
  }
68
67
  if (!quiet)
@@ -79,10 +78,10 @@ async function resolveBotAccount(botKey, options = {}) {
79
78
  const prefRaw = botMeta.preferredAccount != null ? String(botMeta.preferredAccount).trim() : '';
80
79
  if (!prefRaw)
81
80
  return { accountId: null, botKey, botMeta, source: null, reason: 'no-preferred-account' };
82
- const stored = ACCOUNT_ID_RE.test(String(botMeta.accountId ?? '')) ? String(botMeta.accountId) : null;
81
+ const stored = isAccountIdRef(String(botMeta.accountId ?? '')) ? String(botMeta.accountId) : null;
83
82
  // A typed 1.2.x preferredAccount is authoritative — the stored accountId is
84
83
  // a derived cache and must never override it. Self-heal the cache.
85
- if (ACCOUNT_ID_RE.test(prefRaw)) {
84
+ if (isAccountIdRef(prefRaw)) {
86
85
  if (stored !== prefRaw)
87
86
  persistResolvedAccountId(botKey, prefRaw, stored, quiet, botsFile);
88
87
  return { accountId: prefRaw, botKey, botMeta, source: 'preferred-id', reason: null };
@@ -110,7 +109,7 @@ async function resolveBotAccount(botKey, options = {}) {
110
109
  */
111
110
  async function resolveAccountRef(accountRef, options = {}) {
112
111
  const ref = String(accountRef ?? '').trim();
113
- if (ACCOUNT_ID_RE.test(ref)) {
112
+ if (isAccountIdRef(ref)) {
114
113
  return { accountId: ref, botKey: null, botMeta: null, source: 'typed-id', reason: null };
115
114
  }
116
115
  // Local profile first: a bot whose profile name/key matches the reference
@@ -23,7 +23,7 @@ import path from 'node:path';
23
23
  import { pathToFileURL } from 'node:url';
24
24
  import { PATHS } from '../modules/paths.js';
25
25
  import { getErrorMessage } from '../modules/utils/errors.js';
26
- import { formatCurrency, formatFundsValue } from '../modules/order/format.js';
26
+ import { formatCurrency, formatFundsValue, formatPercentLabel } from '../modules/order/format.js';
27
27
  import { muteChainLogs } from '../modules/utils/chain_logs.js';
28
28
  import { withReadOnlyClient } from './chain_pool.js';
29
29
  import { computeBookStats, computePoolPrice, resolvePriceWindow, buildDepthSeries, DEFAULT_STEPS, } from './liquidity/liquidity_depth_model.js';
@@ -55,7 +55,9 @@ function usage() {
55
55
  ' --help show this help',
56
56
  '',
57
57
  'Conventions: price is quote per base (e.g. QUOTE per BASE); depth is',
58
- 'cumulative quote liquidity (QUOTE) at or better than that price.',
58
+ 'cumulative quote liquidity (QUOTE) at or better than that price. Pool',
59
+ 'depth is net of the AMM taker fee, so the pool bid/ask curves are',
60
+ 'separated by the fee-band spread a taker has to cross.',
59
61
  ].join('\n');
60
62
  }
61
63
  function parsePositiveNumber(raw, flag) {
@@ -234,12 +236,21 @@ function printSummary(snapshot, seriesResult, chartFile, config) {
234
236
  const priceLabel = `${quote.symbol} per ${base.symbol}`;
235
237
  console.log(`[Liquidity] ${base.symbol}/${quote.symbol} (price: ${priceLabel}, depth: ${quote.symbol})`);
236
238
  if (pool) {
237
- console.log(` pool ${pool.id ?? 'unknown'} price=${fmtPrice(poolPrice)} reserves=${fmtAmount(pool.baseReserve)} ${base.symbol} / ${fmtAmount(pool.quoteReserve)} ${quote.symbol}${pool.feePercent != null ? ` fee=${fmtPrice(pool.feePercent)}%` : ''}`);
239
+ const feeText = pool.feePercent != null ? ` fee=${formatPercentLabel(pool.feePercent)}` : '';
240
+ console.log(` pool ${pool.id ?? 'unknown'} price=${fmtPrice(poolPrice)}${feeText} reserves=${fmtAmount(pool.baseReserve)} ${base.symbol} / ${fmtAmount(pool.quoteReserve)} ${quote.symbol}`);
241
+ // Fee-adjusted edges: the pool curves stop there, so the gap between
242
+ // them is the AMM spread a taker has to cross before the curve starts.
243
+ const bidEdge = seriesResult.poolBidPrice;
244
+ const askEdge = seriesResult.poolAskPrice;
245
+ if (bidEdge != null && askEdge != null) {
246
+ const feeSpread = ((askEdge - bidEdge) / askEdge) * 100;
247
+ console.log(` pool edge bid=${fmtPrice(bidEdge)} ask=${fmtPrice(askEdge)} spread=${formatPercentLabel(feeSpread)} (fee-adjusted, net of taker fee)`);
248
+ }
238
249
  }
239
250
  else {
240
251
  console.log(' pool none');
241
252
  }
242
- console.log(` book ${stats.bidOrders} bids / ${stats.askOrders} asks best bid=${fmtPrice(stats.bestBid)} best ask=${fmtPrice(stats.bestAsk)} mid=${fmtPrice(stats.mid)} spread=${fmtPrice(stats.spreadPercent)}%`);
253
+ console.log(` book ${stats.bidOrders} bids / ${stats.askOrders} asks best bid=${fmtPrice(stats.bestBid)} best ask=${fmtPrice(stats.bestAsk)} mid=${fmtPrice(stats.mid)} spread=${stats.spreadPercent != null ? formatPercentLabel(stats.spreadPercent) : '-'}`);
243
254
  console.log(` window ${fmtPrice(window.min)} .. ${fmtPrice(window.max)} (${seriesResult.priceCount} samples, range=${config.range})`);
244
255
  // The sampled series is wider than the displayed window so the inverted
245
256
  // (1/p) view can stay centered; report depth at the actual window edges.
@@ -30,6 +30,12 @@ declare function persistBotAccountId(botKey: unknown, accountId: string, filePat
30
30
  * never silently reuse a stale ID.
31
31
  */
32
32
  declare function getStoredBotAccountId(botKey: unknown, expectedRef?: string | null, filePath?: string): string | null;
33
+ /**
34
+ * Chain account id (`1.2.x`) test — the single spelling rule for account ids.
35
+ * Analysis tools used to carry a private copy of this regex (`account_resolver`,
36
+ * `trade_profitability`, `fills_cache`, `resolve_bot_accounts`).
37
+ */
38
+ declare function isAccountIdRef(ref: unknown): boolean;
33
39
  /**
34
40
  * Find the bot entry whose preferredAccount matches a raw account reference
35
41
  * (case-insensitive). Used by tools that accept a bare account name to locate
@@ -40,7 +46,44 @@ declare function findBotKeyByAccountRef(ref: unknown, filePath?: string): {
40
46
  botKey: string;
41
47
  meta: BotEntry;
42
48
  } | null;
49
+ /**
50
+ * Which spelling of a `<bot|account>` CLI target matched a bot entry.
51
+ * `name`/`key` identify one bot; `account` identifies the chain account and
52
+ * therefore every entry that trades from it.
53
+ */
54
+ type BotTargetKind = 'name' | 'key' | 'account';
55
+ interface BotTargetMatch {
56
+ botKey: string;
57
+ meta: BotEntry;
58
+ matchedBy: BotTargetKind;
59
+ }
60
+ /**
61
+ * Match one bot entry against a `<bot>` target: display name (the same
62
+ * case/space-insensitive rule `resolveBotKey` uses) or bot key. `botKey` is a
63
+ * parameter because callers that key entries by a stored file name
64
+ * (`analyze-orders` reads `profiles/orders/<botKey>.json`) know the key without
65
+ * an entry, and a key must still match when the config entry is missing.
66
+ */
67
+ declare function matchBotEntryTarget(entry: BotEntry | null | undefined, target: unknown, botKey?: unknown): BotTargetKind | null;
68
+ /**
69
+ * Does the target name the chain account behind this bot? Covers both stored
70
+ * spellings: `preferredAccount` (name or typed 1.2.x id) and the `accountId`
71
+ * `account_resolver.ts` stamps next to it. Matched case-insensitively — chain
72
+ * account names are lowercase, but operators type them any way they like.
73
+ */
74
+ declare function matchBotAccountTarget(entry: BotEntry | null | undefined, target: unknown): boolean;
75
+ /**
76
+ * Canonical `<bot|account>` target resolution: every entry matching the target
77
+ * as a bot name, a bot key, or the chain account it trades from. This is the
78
+ * one rule set behind `dexbot credit`, `dexbot order` and the chart commands —
79
+ * they previously each carried a slightly different copy (some name-only, some
80
+ * key-only, `credit` a third variant). Each caller picks the spellings it
81
+ * accepts from `matchedBy`: a chart command takes the first `name`/`key` match
82
+ * (an account is ambiguous there), while `credit` reports every match.
83
+ */
84
+ declare function matchBotTargetIn(entries: Array<BotEntry | null | undefined> | null | undefined, target: unknown): BotTargetMatch[];
43
85
  declare function resolveAmaConfig(botKey: unknown): AmaConfig;
44
86
  declare function resolveAmaKey(botKey: unknown): string;
45
- export { loadBotSettings, sanitizeKey, computeBotKey, resolveBotKey, candleFileForBot, resolveCandleFile, loadBotMeta, getStoredBotAccountId, findBotKeyByAccountRef, persistBotAccountId, resolveAmaConfig, resolveAmaKey };
87
+ export { loadBotSettings, sanitizeKey, computeBotKey, resolveBotKey, candleFileForBot, resolveCandleFile, loadBotMeta, getStoredBotAccountId, findBotKeyByAccountRef, persistBotAccountId, resolveAmaConfig, resolveAmaKey, isAccountIdRef, matchBotEntryTarget, matchBotAccountTarget, matchBotTargetIn };
88
+ export type { BotTargetKind, BotTargetMatch };
46
89
  //# sourceMappingURL=bot_key_utils.d.ts.map
@@ -7,7 +7,7 @@ const { readJSON, writeJSON } = getStorage();
7
7
  import { parseJsonWithComments } from '../modules/order/utils/system.js';
8
8
  import { MARKET_ADAPTER } from '../modules/constants.js';
9
9
  import { loadMarketProfiles } from './tradingview/tradingview_uplot_chart_generator.js';
10
- import { sanitizeKey } from '../modules/utils/sanitize_key.js';
10
+ import { isSameBotName, sanitizeKey } from '../modules/utils/sanitize_key.js';
11
11
  import { isSameAssetSymbol, canonicalizeBotAssetSymbols } from '../modules/utils/asset_symbols.js';
12
12
  // Single source of truth for bot keys (named AND unnamed bots) so analysis
13
13
  // tools resolve the same files production writes.
@@ -378,7 +378,7 @@ function patchAccountIdInRaw(filePath, entryIndex, accountId) {
378
378
  * the file was updated.
379
379
  */
380
380
  function persistBotAccountId(botKey, accountId, filePath = PATHS.PROFILES.BOTS_JSON) {
381
- if (!botKey || !/^1\.2\.\d+$/.test(String(accountId)))
381
+ if (!botKey || !isAccountIdRef(accountId))
382
382
  return false;
383
383
  let settings = null;
384
384
  try {
@@ -427,13 +427,21 @@ function getStoredBotAccountId(botKey, expectedRef, filePath = PATHS.PROFILES.BO
427
427
  if (!meta)
428
428
  return null;
429
429
  const accountIdRaw = String(meta.accountId ?? '');
430
- const stored = /^1\.2\.\d+$/.test(accountIdRaw) ? accountIdRaw : null;
430
+ const stored = isAccountIdRef(accountIdRaw) ? accountIdRaw : null;
431
431
  if (!stored)
432
432
  return null;
433
433
  if (expectedRef != null && String(meta.preferredAccount ?? '').toLowerCase() !== String(expectedRef).toLowerCase())
434
434
  return null;
435
435
  return stored;
436
436
  }
437
+ /**
438
+ * Chain account id (`1.2.x`) test — the single spelling rule for account ids.
439
+ * Analysis tools used to carry a private copy of this regex (`account_resolver`,
440
+ * `trade_profitability`, `fills_cache`, `resolve_bot_accounts`).
441
+ */
442
+ function isAccountIdRef(ref) {
443
+ return /^1\.2\.\d+$/.test(String(ref ?? '').trim());
444
+ }
437
445
  /**
438
446
  * Find the bot entry whose preferredAccount matches a raw account reference
439
447
  * (case-insensitive). Used by tools that accept a bare account name to locate
@@ -441,7 +449,7 @@ function getStoredBotAccountId(botKey, expectedRef, filePath = PATHS.PROFILES.BO
441
449
  * or when no bot claims the name.
442
450
  */
443
451
  function findBotKeyByAccountRef(ref, filePath = PATHS.PROFILES.BOTS_JSON) {
444
- if (!ref || /^1\.2\.\d+$/.test(String(ref)))
452
+ if (!ref || isAccountIdRef(ref))
445
453
  return null;
446
454
  let settings = null;
447
455
  try {
@@ -451,15 +459,76 @@ function findBotKeyByAccountRef(ref, filePath = PATHS.PROFILES.BOTS_JSON) {
451
459
  return null;
452
460
  }
453
461
  const entries = Array.isArray(settings?.bots) ? settings.bots : [];
454
- const want = String(ref).toLowerCase();
455
462
  for (let i = 0; i < entries.length; i++) {
456
463
  const entry = entries[i];
457
- if (entry && String(entry.preferredAccount ?? '').toLowerCase() === want) {
464
+ if (entry && matchBotAccountTarget(entry, ref)) {
458
465
  return { botKey: computeBotKey(entry, i), meta: entry };
459
466
  }
460
467
  }
461
468
  return null;
462
469
  }
470
+ /** Trimmed target or '' — the positional is user input, so never assume a string. */
471
+ function normalizeBotTarget(target) {
472
+ return typeof target === 'string' ? target.trim() : '';
473
+ }
474
+ /**
475
+ * Match one bot entry against a `<bot>` target: display name (the same
476
+ * case/space-insensitive rule `resolveBotKey` uses) or bot key. `botKey` is a
477
+ * parameter because callers that key entries by a stored file name
478
+ * (`analyze-orders` reads `profiles/orders/<botKey>.json`) know the key without
479
+ * an entry, and a key must still match when the config entry is missing.
480
+ */
481
+ function matchBotEntryTarget(entry, target, botKey) {
482
+ const raw = normalizeBotTarget(target);
483
+ if (!raw)
484
+ return null;
485
+ if (entry && isSameBotName(entry.name, raw))
486
+ return 'name';
487
+ const key = String(botKey ?? '').trim();
488
+ if (!key)
489
+ return null;
490
+ return key.toLowerCase() === raw.toLowerCase() || sanitizeKey(key) === sanitizeKey(raw) ? 'key' : null;
491
+ }
492
+ /**
493
+ * Does the target name the chain account behind this bot? Covers both stored
494
+ * spellings: `preferredAccount` (name or typed 1.2.x id) and the `accountId`
495
+ * `account_resolver.ts` stamps next to it. Matched case-insensitively — chain
496
+ * account names are lowercase, but operators type them any way they like.
497
+ */
498
+ function matchBotAccountTarget(entry, target) {
499
+ const raw = normalizeBotTarget(target).toLowerCase();
500
+ if (!entry || !raw)
501
+ return false;
502
+ const account = String(entry.preferredAccount ?? '').trim().toLowerCase();
503
+ if (account && account === raw)
504
+ return true;
505
+ const accountId = String(entry.accountId ?? '').trim().toLowerCase();
506
+ return Boolean(accountId) && accountId === raw;
507
+ }
508
+ /**
509
+ * Canonical `<bot|account>` target resolution: every entry matching the target
510
+ * as a bot name, a bot key, or the chain account it trades from. This is the
511
+ * one rule set behind `dexbot credit`, `dexbot order` and the chart commands —
512
+ * they previously each carried a slightly different copy (some name-only, some
513
+ * key-only, `credit` a third variant). Each caller picks the spellings it
514
+ * accepts from `matchedBy`: a chart command takes the first `name`/`key` match
515
+ * (an account is ambiguous there), while `credit` reports every match.
516
+ */
517
+ function matchBotTargetIn(entries, target) {
518
+ const out = [];
519
+ const list = Array.isArray(entries) ? entries : [];
520
+ for (let index = 0; index < list.length; index++) {
521
+ const entry = list[index];
522
+ if (!entry)
523
+ continue;
524
+ const botKey = computeBotKey(entry, index);
525
+ const matchedBy = matchBotEntryTarget(entry, target, botKey)
526
+ ?? (matchBotAccountTarget(entry, target) ? 'account' : null);
527
+ if (matchedBy)
528
+ out.push({ botKey, meta: entry, matchedBy });
529
+ }
530
+ return out;
531
+ }
463
532
  function resolveAmaConfig(botKey) {
464
533
  const botMeta = loadBotMeta(botKey);
465
534
  if (!botMeta)
@@ -539,5 +608,5 @@ function resolveAmaKey(botKey) {
539
608
  }
540
609
  return 'AMA3';
541
610
  }
542
- export { loadBotSettings, sanitizeKey, computeBotKey, resolveBotKey, candleFileForBot, resolveCandleFile, loadBotMeta, getStoredBotAccountId, findBotKeyByAccountRef, persistBotAccountId, resolveAmaConfig, resolveAmaKey };
611
+ export { loadBotSettings, sanitizeKey, computeBotKey, resolveBotKey, candleFileForBot, resolveCandleFile, loadBotMeta, getStoredBotAccountId, findBotKeyByAccountRef, persistBotAccountId, resolveAmaConfig, resolveAmaKey, isAccountIdRef, matchBotEntryTarget, matchBotAccountTarget, matchBotTargetIn };
543
612
  //# sourceMappingURL=bot_key_utils.js.map
@@ -26,6 +26,7 @@
26
26
  import path from 'node:path';
27
27
  import { getStorage } from '../modules/storage/index.js';
28
28
  import { PATHS } from '../modules/paths.js';
29
+ import { isAccountIdRef } from './bot_key_utils.js';
29
30
  import { writeJsonAtomic } from '../market_adapter/utils/atomic_write.js';
30
31
  import { shardKeyForTimestamp, shardBoundsForKey, shardKeysForRange, shardPathFor, unionQueriedRanges, compactCoverage, mergeSpans, subtractRanges, } from '../market_adapter/utils/month_shards.js';
31
32
  import { fetchAllFills } from './fills_source.js';
@@ -38,7 +39,7 @@ const MAX_COVERAGE_SPANS = 64;
38
39
  const SHARD_EXT = '.json';
39
40
  function accountFileBase(accountId) {
40
41
  const s = String(accountId ?? '').trim();
41
- if (/^1\.2\.\d+$/.test(s))
42
+ if (isAccountIdRef(s))
42
43
  return s;
43
44
  return s.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || 'account';
44
45
  }
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { isLastFillGuardBlocked } from '../modules/order/utils/system.js';
2
3
  import { FillRecord } from './fills_source.js';
3
4
  interface TradeFill {
4
5
  time: string;
@@ -27,25 +28,6 @@ interface Violation {
27
28
  /** The pivot itself (BUY must be below / SELL above it). */
28
29
  threshold: number;
29
30
  }
30
- /**
31
- * LAST-FILL-GUARD helper — DIRECTION ONLY relative to the last fill price.
32
- * BUY blocked if price >= pivot
33
- * SELL blocked if price <= pivot
34
- * e.g. pivot 1000 => BUY must be < 1000, SELL must be > 1000
35
- * Cold (pivot null or lastType null) => disabled. Equal price stays blocked
36
- * (a re-place at the just-filled level).
37
- * @param {number} price - Target order price
38
- * @param {string} type - buy/sell
39
- * @param {number|null} lastPrice - Most recent fill price
40
- * @param {string|null} lastType - Most recent fill side (buy/sell)
41
- * @returns {{blocked: boolean, pivot: number|null, halfInc: number, threshold: number|null}}
42
- */
43
- declare function isLastFillGuardBlocked(price: unknown, type: unknown, lastPrice: unknown, lastType: unknown): {
44
- blocked: boolean;
45
- pivot: number | null;
46
- halfInc?: number;
47
- threshold?: number | null;
48
- };
49
31
  declare function classifyFills(fills: FillRecord[]): {
50
32
  trades: TradeFill[];
51
33
  skipped: number;