dexbot 1.6.14 → 1.6.16

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 (134) hide show
  1. package/CHANGELOG.md +60 -4
  2. package/README.md +4 -4
  3. package/analysis/README.md +6 -6
  4. package/analysis/tradingview/README.md +2 -1
  5. package/claw/README.md +7 -7
  6. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
  7. package/claw/modules/chain_queries.ts +3 -3
  8. package/claw/package.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/dist/analysis/ama_fitting/fetch_lp_candles.js +8 -1
  12. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
  13. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
  14. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
  15. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
  16. package/dist/analysis/bot_key_utils.js +9 -7
  17. package/dist/analysis/chart_utils.d.ts +9 -2
  18. package/dist/analysis/chart_utils.js +51 -1
  19. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
  20. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +99 -11
  21. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +57 -4
  22. package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
  23. package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
  24. package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
  25. package/dist/dexbot.js +112 -141
  26. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
  27. package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
  28. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
  29. package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
  30. package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
  31. package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
  32. package/dist/market_adapter/inputs/window_cache.js +53 -17
  33. package/dist/market_adapter/lp_chart_core.js +1 -0
  34. package/dist/market_adapter/utils/chain.js +4 -3
  35. package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
  36. package/dist/market_adapter/utils/pair_orientation.js +142 -0
  37. package/dist/modules/account_bots.d.ts +40 -3
  38. package/dist/modules/account_bots.js +80 -37
  39. package/dist/modules/account_orders.d.ts +4 -1
  40. package/dist/modules/account_orders.js +4 -1
  41. package/dist/modules/bitshares-native/resolvers.js +3 -3
  42. package/dist/modules/bitshares-native/subscriptions.js +1 -1
  43. package/dist/modules/bitshares_client.d.ts +12 -10
  44. package/dist/modules/bitshares_client.js +12 -10
  45. package/dist/modules/bot_defaults.d.ts +13 -2
  46. package/dist/modules/bot_defaults.js +31 -2
  47. package/dist/modules/bot_settings.js +6 -3
  48. package/dist/modules/chain_keys.d.ts +5 -1
  49. package/dist/modules/chain_keys.js +5 -1
  50. package/dist/modules/chain_orders.d.ts +6 -2
  51. package/dist/modules/chain_orders.js +6 -2
  52. package/dist/modules/constants.d.ts +11 -0
  53. package/dist/modules/constants.js +31 -1
  54. package/dist/modules/credit_runtime.d.ts +35 -5
  55. package/dist/modules/credit_runtime.js +219 -38
  56. package/dist/modules/dexbot_class.d.ts +22 -2
  57. package/dist/modules/dexbot_class.js +61 -21
  58. package/dist/modules/dexbot_cow_runtime.js +19 -18
  59. package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
  60. package/dist/modules/dexbot_fill_runtime.js +4 -7
  61. package/dist/modules/dexbot_maintenance_runtime.d.ts +7 -2
  62. package/dist/modules/dexbot_maintenance_runtime.js +52 -7
  63. package/dist/modules/dexbot_startup_runtime.js +3 -2
  64. package/dist/modules/dexbot_state_recovery.js +1 -1
  65. package/dist/modules/graceful_shutdown.d.ts +6 -2
  66. package/dist/modules/graceful_shutdown.js +6 -2
  67. package/dist/modules/launcher/bot_supervisor.js +4 -0
  68. package/dist/modules/launcher/launch_modes.js +6 -3
  69. package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
  70. package/dist/modules/launcher/monolithic_runtime.js +60 -1
  71. package/dist/modules/launcher/runtime_mode.d.ts +79 -0
  72. package/dist/modules/launcher/runtime_mode.js +223 -0
  73. package/dist/modules/market_adapter_whitelist.d.ts +8 -0
  74. package/dist/modules/market_adapter_whitelist.js +8 -0
  75. package/dist/modules/order/accounting.d.ts +15 -1
  76. package/dist/modules/order/accounting.js +15 -1
  77. package/dist/modules/order/async_lock.d.ts +9 -3
  78. package/dist/modules/order/async_lock.js +9 -3
  79. package/dist/modules/order/export.d.ts +0 -5
  80. package/dist/modules/order/export.js +2 -7
  81. package/dist/modules/order/format.d.ts +6 -4
  82. package/dist/modules/order/format.js +6 -4
  83. package/dist/modules/order/grid.d.ts +147 -19
  84. package/dist/modules/order/grid.js +321 -68
  85. package/dist/modules/order/grid_reconcile.js +4 -3
  86. package/dist/modules/order/grid_reconcile_internal.js +13 -18
  87. package/dist/modules/order/index.d.ts +4 -2
  88. package/dist/modules/order/index.js +1 -1
  89. package/dist/modules/order/logger_state.d.ts +1 -1
  90. package/dist/modules/order/logger_state.js +1 -1
  91. package/dist/modules/order/manager.d.ts +1 -0
  92. package/dist/modules/order/manager.js +5 -14
  93. package/dist/modules/order/sync_engine.d.ts +26 -11
  94. package/dist/modules/order/sync_engine.js +44 -20
  95. package/dist/modules/order/utils/math.d.ts +157 -47
  96. package/dist/modules/order/utils/math.js +236 -78
  97. package/dist/modules/order/utils/order.d.ts +64 -20
  98. package/dist/modules/order/utils/order.js +80 -24
  99. package/dist/modules/order/utils/system.d.ts +41 -11
  100. package/dist/modules/order/utils/system.js +43 -13
  101. package/dist/modules/order/utils/validate.d.ts +6 -3
  102. package/dist/modules/order/utils/validate.js +53 -60
  103. package/dist/modules/types.d.ts +7 -0
  104. package/dist/modules/utils/asset_symbols.d.ts +5 -5
  105. package/dist/modules/utils/asset_symbols.js +5 -5
  106. package/dist/modules/utils/errors.d.ts +2 -1
  107. package/dist/modules/utils/errors.js +2 -1
  108. package/dist/scripts/analyze-credit.js +44 -27
  109. package/dist/scripts/diagnose-pool-history.js +35 -30
  110. package/dist/scripts/pnl.js +1 -1
  111. package/dist/scripts/rich_list.d.ts +50 -0
  112. package/dist/scripts/rich_list.js +469 -0
  113. package/dist/scripts/run-tests.js +80 -4
  114. package/dist/unlock.d.ts +2 -1
  115. package/dist/unlock.js +53 -21
  116. package/docs/BITSHARES_ONBOARDING.md +7 -0
  117. package/docs/COW_INVARIANTS.md +7 -1
  118. package/docs/DEXBOT_COMPARISON.md +6 -6
  119. package/docs/EVOLUTION.md +11 -9
  120. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -3
  121. package/docs/GRID_RECALCULATION.md +18 -6
  122. package/docs/LIFECYCLE.md +8 -8
  123. package/docs/LOGGING.md +16 -1
  124. package/docs/MPA_CREDIT_USAGE.md +10 -5
  125. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +163 -13
  126. package/docs/README.md +1 -1
  127. package/docs/WORKFLOW.md +6 -5
  128. package/docs/architecture.md +56 -2
  129. package/docs/developer_guide.md +5 -1
  130. package/market_adapter/README.md +14 -7
  131. package/modules/README.md +1 -1
  132. package/package.json +4 -1
  133. package/scripts/README.md +59 -32
  134. package/tests/README.md +40 -2
@@ -0,0 +1,223 @@
1
+ 'use strict';
2
+ /**
3
+ * Single source of truth for "which DEXBot2 runtime is running?".
4
+ *
5
+ * Used by `dexbot status` (delegate to `unlock status` vs render the PM2
6
+ * table) and by `dexbot help`/usage output (describe controls in terms of the
7
+ * active runtime). Keeping detection plus the mode→instructions mapping here
8
+ * stops the two entry points from drifting.
9
+ *
10
+ * Unlock-mode liveness is read from pid files/socket (cheap). PM2 is only
11
+ * probed when no unlock runtime is up, so a running monolithic/isolated bot
12
+ * never pays for a `pm2` round-trip.
13
+ *
14
+ * Limitation: the isolated verdict is an `exists()` check on the supervisor
15
+ * socket, so a leftover socket from a crashed supervisor still reads as
16
+ * isolated. A live-connect probe would be more accurate but must stay off the
17
+ * help/status hot path.
18
+ */
19
+ import { execSync } from 'node:child_process';
20
+ import { homedir } from 'node:os';
21
+ import { join } from 'node:path';
22
+ import { getStorage } from '../storage/index.js';
23
+ import { PATHS } from '../paths.js';
24
+ import { Config } from '../config.js';
25
+ import { loadSettingsFile, resolveRawBotEntries } from '../bot_settings.js';
26
+ import { isSameBotName } from '../utils/sanitize_key.js';
27
+ import { normalizeControlTarget, readLiveMonolithicPid, botNotFoundMessage, statusIgnoresTargetMessage } from './monolithic_runtime.js';
28
+ const storage = getStorage();
29
+ /** PM2 app names owned by DEXBot2 (bot names are added from bots.json). */
30
+ const PM2_SERVICE_NAMES = new Set(['dexbot-cred', 'dexbot-adapter', 'dexbot-update']);
31
+ function configuredBotNames() {
32
+ const names = new Set();
33
+ try {
34
+ const { config } = loadSettingsFile(PATHS.PROFILES.BOTS_JSON);
35
+ for (const b of resolveRawBotEntries(config)) {
36
+ if (b?.name)
37
+ names.add(String(b.name));
38
+ }
39
+ }
40
+ catch (_) { }
41
+ return names;
42
+ }
43
+ /** True when `name` matches a configured bot (case-insensitive). */
44
+ export function isConfiguredBotName(name) {
45
+ for (const configured of configuredBotNames()) {
46
+ if (isSameBotName(configured, name))
47
+ return true;
48
+ }
49
+ return false;
50
+ }
51
+ /**
52
+ * Validate the optional bot name on `dexbot status`. status is whole-runtime
53
+ * on every surface, so a real name is announced-then-ignored and an unknown
54
+ * one is rejected — the same contract the unlock control path applies.
55
+ */
56
+ export function checkStatusTarget(target) {
57
+ const requested = normalizeControlTarget(target);
58
+ if (!requested)
59
+ return { error: null, notice: null };
60
+ if (!isConfiguredBotName(requested)) {
61
+ return { error: botNotFoundMessage(requested), notice: null };
62
+ }
63
+ return { error: null, notice: statusIgnoresTargetMessage(requested) };
64
+ }
65
+ /**
66
+ * Which branch `dexbot status` takes. PM2 wins when PM2 bots are running (even
67
+ * if a stray credential daemon lingers) so the report and the help banner name
68
+ * the same runtime; otherwise a live unlock process is shown by delegating to
69
+ * `unlock status`. The cred-daemon-only case stays on the unlock route so the
70
+ * daemon is still reported.
71
+ */
72
+ export function resolveStatusRoute(info) {
73
+ if (info.pm2Processes.length > 0)
74
+ return 'pm2';
75
+ if (info.unlockRunning)
76
+ return 'unlock';
77
+ return 'empty';
78
+ }
79
+ function isPidAlive(pid) {
80
+ if (!Number.isInteger(pid) || pid <= 0)
81
+ return false;
82
+ try {
83
+ process.kill(pid, 0);
84
+ return true;
85
+ }
86
+ catch (err) {
87
+ // A live process owned by another user still exists (EACCES).
88
+ return err?.code === 'EACCES';
89
+ }
90
+ }
91
+ /**
92
+ * Whether a PM2 daemon looks alive in this install. PM2 always writes
93
+ * `pm2.pid` under PM2_HOME (default `~/.pm2`), so its presence is a cheap
94
+ * fast-path that avoids spawning `pm2 jlist` at all when PM2 was never run.
95
+ */
96
+ function isPm2DaemonRunning() {
97
+ try {
98
+ const home = Config.PM2_HOME || process.env.PM2_HOME || join(homedir(), '.pm2');
99
+ return storage.exists(join(home, 'pm2.pid'));
100
+ }
101
+ catch (_) {
102
+ return false;
103
+ }
104
+ }
105
+ /**
106
+ * Parse `pm2 jlist` and keep only DEXBot2's own processes. Returns `[]` on any
107
+ * failure (pm2 missing, daemon down, malformed output) so callers can treat
108
+ * "no PM2" and "pm2 unavailable" the same way.
109
+ */
110
+ export function listDexbotPm2Processes() {
111
+ // Fast path: no daemon pid file means pm2 is not running here, so skip the
112
+ // subprocess. Keeps `dexbot help`/typo-usage output free of a pm2 probe.
113
+ if (!isPm2DaemonRunning())
114
+ return [];
115
+ let allProcs;
116
+ try {
117
+ const output = execSync('pm2 jlist 2>/dev/null', { encoding: 'utf8', timeout: 5000 }).toString().trim();
118
+ const jsonStart = output.indexOf('[');
119
+ if (jsonStart === -1)
120
+ return [];
121
+ const parsed = JSON.parse(output.slice(jsonStart));
122
+ if (!Array.isArray(parsed))
123
+ return [];
124
+ allProcs = parsed;
125
+ }
126
+ catch (_) {
127
+ return [];
128
+ }
129
+ const botNames = configuredBotNames();
130
+ return allProcs.filter((p) => {
131
+ const name = String(p?.name || '');
132
+ return PM2_SERVICE_NAMES.has(name) || botNames.has(name);
133
+ });
134
+ }
135
+ /**
136
+ * Detect the active runtime and the supporting state the callers need.
137
+ * Monolithic wins over isolated if both markers linger; PM2 is probed last.
138
+ */
139
+ export function detectRuntimeMode() {
140
+ const monolithicPid = readLiveMonolithicPid().pid;
141
+ const supervisorSocket = storage.exists(PATHS.PROFILES.SUPERVISOR_SOCK);
142
+ let credentialDaemonPid = 0;
143
+ try {
144
+ const pid = Number(storage.readFile(PATHS.PROFILES.MONOLITHIC_CRED_PID).trim());
145
+ if (Number.isInteger(pid) && pid > 0 && isPidAlive(pid))
146
+ credentialDaemonPid = pid;
147
+ }
148
+ catch (_) { }
149
+ const credentialDaemonAlive = credentialDaemonPid > 0;
150
+ const unlockRunning = monolithicPid > 0 || supervisorSocket || credentialDaemonAlive;
151
+ let pm2Processes = [];
152
+ let mode = 'none';
153
+ if (monolithicPid > 0) {
154
+ mode = 'monolithic';
155
+ }
156
+ else if (supervisorSocket) {
157
+ mode = 'isolated';
158
+ }
159
+ else {
160
+ pm2Processes = listDexbotPm2Processes();
161
+ if (pm2Processes.length > 0)
162
+ mode = 'pm2';
163
+ }
164
+ return { mode, monolithicPid, supervisorSocket, credentialDaemonAlive, credentialDaemonPid, unlockRunning, pm2Processes };
165
+ }
166
+ /** Human label for the active-runtime banner. */
167
+ export const RUNTIME_MODE_LABELS = {
168
+ monolithic: 'monolithic runtime (dexbot start)',
169
+ isolated: 'isolated supervisor (dexbot start --isolated)',
170
+ pm2: 'PM2 (dexbot pm2)',
171
+ none: 'none detected — standard monolithic runtime',
172
+ };
173
+ /**
174
+ * Banner label for a detection result. `none` with a live credential daemon
175
+ * is called out so the banner agrees with `dexbot status` (which reports the
176
+ * daemon that outlived a `stop`).
177
+ */
178
+ export function runtimeModeLabel(info) {
179
+ if (info.mode === 'none' && info.credentialDaemonAlive) {
180
+ return 'credential daemon only — no bot runtime';
181
+ }
182
+ return RUNTIME_MODE_LABELS[info.mode];
183
+ }
184
+ /**
185
+ * The Runtime command group, phrased for the runtime that is actually up.
186
+ * `none` shows the standard monolithic runtime (the `dexbot start` default)
187
+ * so the reference is always complete before anything is running.
188
+ */
189
+ export function runtimeControlHelp(mode) {
190
+ switch (mode) {
191
+ case 'isolated':
192
+ return [
193
+ { command: 'start [bot]', description: 'Start the runtime (flags below).' },
194
+ { command: 'stop [<bot>]', description: 'Stop one bot, or all bots when <bot> is omitted.' },
195
+ { command: 'reload [<bot>]', description: 'Reload one bot, or all bots, without re-unlocking keys.' },
196
+ { command: 'restart [<bot>]', description: 'Restart one bot, or all bots, and re-unlock keys.' },
197
+ { command: 'delete', description: 'Shut the supervisor down and clean up (all bots).' },
198
+ { command: 'status', description: 'Show runtime status (a <bot> is validated, then ignored).' },
199
+ { command: 'pm2 [<sub>]', description: 'Manage PM2 bots (see: dexbot pm2 help).' },
200
+ ];
201
+ case 'pm2':
202
+ return [
203
+ { command: 'pm2 [<bot>]', description: 'Start/replace the PM2 process set (unlocks the credential daemon).' },
204
+ { command: 'pm2 stop <bot|all>', description: 'Stop PM2 bot process(es).' },
205
+ { command: 'pm2 reload <bot|all>', description: 'Reload PM2 apps; dexbot-cred untouched.' },
206
+ { command: 'pm2 restart <bot|all|dexbot-cred>', description: 'Restart PM2 apps; dexbot-cred re-unlocks.' },
207
+ { command: 'pm2 delete <bot|all>', description: 'Delete PM2 bot process(es).' },
208
+ { command: 'status', description: 'Show runtime status (a <bot> is validated, then ignored).' },
209
+ ];
210
+ case 'monolithic':
211
+ default:
212
+ return [
213
+ { command: 'start [bot]', description: 'Start the runtime (flags below).' },
214
+ { command: 'stop [<bot>]', description: 'Stop all bots (a <bot> argument folds into the whole runtime).' },
215
+ { command: 'reload [<bot>]', description: 'Reload all bots without re-unlocking keys.' },
216
+ { command: 'restart [<bot>]', description: 'Restart all bots and re-unlock keys.' },
217
+ { command: 'delete', description: 'Stop and delete all runtime processes.' },
218
+ { command: 'status', description: 'Show runtime status (a <bot> is validated, then ignored).' },
219
+ { command: 'pm2 [<sub>]', description: 'Manage PM2 bots (see: dexbot pm2 help).' },
220
+ ];
221
+ }
222
+ }
223
+ //# sourceMappingURL=runtime_mode.js.map
@@ -26,6 +26,14 @@ declare function isBotAsymmetricBoundsWhitelisted(botKey: string): boolean;
26
26
  * Stores the market-adapter flags for a single bot key. This is the bot
27
27
  * editor's write-through path for section `6) Adapter` and writes the same
28
28
  * file/shape the market adapter reads back.
29
+ *
30
+ * Unlike renameWhitelistEntry this intentionally overwrites any existing entry
31
+ * for the key: it is the generic "set flags for this key" primitive used by
32
+ * new-bot, modify and copy, where claiming a stale/orphan entry is expected. A
33
+ * live key collision can not reach here because bots.json rejects duplicate
34
+ * botKeys before the editor's commit hook runs. The rename guard is stricter
35
+ * only because a move deletes the source, so refusing on an occupied target
36
+ * keeps both entries intact.
29
37
  * @param {string} botKey - Whitelist key (sanitized bot name).
30
38
  * @param {Partial<WhitelistFlags>} flags - Flags to apply; omitted keys keep
31
39
  * their current value.
@@ -162,6 +162,14 @@ function writeWhitelistDocument(doc, entries) {
162
162
  * Stores the market-adapter flags for a single bot key. This is the bot
163
163
  * editor's write-through path for section `6) Adapter` and writes the same
164
164
  * file/shape the market adapter reads back.
165
+ *
166
+ * Unlike renameWhitelistEntry this intentionally overwrites any existing entry
167
+ * for the key: it is the generic "set flags for this key" primitive used by
168
+ * new-bot, modify and copy, where claiming a stale/orphan entry is expected. A
169
+ * live key collision can not reach here because bots.json rejects duplicate
170
+ * botKeys before the editor's commit hook runs. The rename guard is stricter
171
+ * only because a move deletes the source, so refusing on an occupied target
172
+ * keeps both entries intact.
165
173
  * @param {string} botKey - Whitelist key (sanitized bot name).
166
174
  * @param {Partial<WhitelistFlags>} flags - Flags to apply; omitted keys keep
167
175
  * their current value.
@@ -6,7 +6,7 @@
6
6
  * Exports a single Accountant class that manages all fund accounting operations.
7
7
  *
8
8
  * ===============================================================================
9
- * TABLE OF CONTENTS - Accountant Class (17 methods)
9
+ * TABLE OF CONTENTS - Accountant Class (26 methods)
10
10
  * ===============================================================================
11
11
  *
12
12
  * CORE INITIALIZATION & RECALCULATION (2 methods)
@@ -43,6 +43,20 @@
43
43
  * RECOVERY & VALIDATION (1 method)
44
44
  * 17. resetRecoveryState() - Reset recovery backoff and state
45
45
  *
46
+ * INTERNAL FEE / BALANCE HELPERS (9 methods - internal)
47
+ * 18. _logThrottled(key, message, level, intervalMs) - Throttled logging helper
48
+ * 19. _applyBalanceAdjustments(list) - Apply a list of balance adjustments
49
+ * 20. _getBtsOrderType() - Resolve which side pays BTS fees
50
+ * 21. _normalizeBtsFeeState(order) - Normalize an order's deferred-BTS-fee state
51
+ * 22. _calculateUpdateDeferredCharge(oldDeferredFee, feeSchedule) - Deferred charge on update
52
+ * 23. _resolveBtsFeeLifecycle(oldOrder, newOrder, context, explicitFee) - Resolve the
53
+ * BTS fee lifecycle for an order transition
54
+ * 24. _buildBtsDeferredRefundAdjustment(orderId, isMaker) - Build the deferred refund
55
+ * adjustment for a fill
56
+ * 25. _recalibrateTrackedFundsFromChain(mgr, openOrders) - Recalibrate tracked funds
57
+ * from a fresh chain snapshot
58
+ * 26. _tryTrustChainFreeHeal(mgr, driftValidation) - Attempt a trust-chain-free heal
59
+ *
46
60
  * ===============================================================================
47
61
  * FUND STRUCTURE (managed by Accountant)
48
62
  * ===============================================================================
@@ -6,7 +6,7 @@
6
6
  * Exports a single Accountant class that manages all fund accounting operations.
7
7
  *
8
8
  * ===============================================================================
9
- * TABLE OF CONTENTS - Accountant Class (17 methods)
9
+ * TABLE OF CONTENTS - Accountant Class (26 methods)
10
10
  * ===============================================================================
11
11
  *
12
12
  * CORE INITIALIZATION & RECALCULATION (2 methods)
@@ -43,6 +43,20 @@
43
43
  * RECOVERY & VALIDATION (1 method)
44
44
  * 17. resetRecoveryState() - Reset recovery backoff and state
45
45
  *
46
+ * INTERNAL FEE / BALANCE HELPERS (9 methods - internal)
47
+ * 18. _logThrottled(key, message, level, intervalMs) - Throttled logging helper
48
+ * 19. _applyBalanceAdjustments(list) - Apply a list of balance adjustments
49
+ * 20. _getBtsOrderType() - Resolve which side pays BTS fees
50
+ * 21. _normalizeBtsFeeState(order) - Normalize an order's deferred-BTS-fee state
51
+ * 22. _calculateUpdateDeferredCharge(oldDeferredFee, feeSchedule) - Deferred charge on update
52
+ * 23. _resolveBtsFeeLifecycle(oldOrder, newOrder, context, explicitFee) - Resolve the
53
+ * BTS fee lifecycle for an order transition
54
+ * 24. _buildBtsDeferredRefundAdjustment(orderId, isMaker) - Build the deferred refund
55
+ * adjustment for a fill
56
+ * 25. _recalibrateTrackedFundsFromChain(mgr, openOrders) - Recalibrate tracked funds
57
+ * from a fresh chain snapshot
58
+ * 26. _tryTrustChainFreeHeal(mgr, driftValidation) - Attempt a trust-chain-free heal
59
+ *
46
60
  * ===============================================================================
47
61
  * FUND STRUCTURE (managed by Accountant)
48
62
  * ===============================================================================
@@ -21,7 +21,7 @@
21
21
  * });
22
22
  *
23
23
  * ===============================================================================
24
- * TABLE OF CONTENTS - AsyncLock Class (6 methods)
24
+ * TABLE OF CONTENTS - AsyncLock Class (8 methods)
25
25
  * ===============================================================================
26
26
  *
27
27
  * INITIALIZATION (1 method)
@@ -37,9 +37,15 @@
37
37
  * Marks as locked, executes callback, handles errors, unlocks, processes next
38
38
  * Recursive: processes next item after each callback completes
39
39
  *
40
- * STATUS QUERIES (2 methods)
40
+ * STATUS QUERIES (4 methods)
41
41
  * 4. isLocked() - Check if lock is currently acquired
42
- * 5. getQueueLength() - Get number of operations waiting for lock
42
+ * 5. heldForMs() - Milliseconds the lock has been held (0 when free)
43
+ * 6. isReentrant() - Whether the current async context already holds the lock
44
+ * 7. getQueueLength() - Get number of operations waiting for lock
45
+ *
46
+ * LOCK RELEASE (1 method)
47
+ * 8. forceRelease() - Force-release the lock, rejecting every queued waiter
48
+ * (used by shutdown/cleanup paths; returns whether it was held)
43
49
  *
44
50
  * ===============================================================================
45
51
  *
@@ -21,7 +21,7 @@
21
21
  * });
22
22
  *
23
23
  * ===============================================================================
24
- * TABLE OF CONTENTS - AsyncLock Class (6 methods)
24
+ * TABLE OF CONTENTS - AsyncLock Class (8 methods)
25
25
  * ===============================================================================
26
26
  *
27
27
  * INITIALIZATION (1 method)
@@ -37,9 +37,15 @@
37
37
  * Marks as locked, executes callback, handles errors, unlocks, processes next
38
38
  * Recursive: processes next item after each callback completes
39
39
  *
40
- * STATUS QUERIES (2 methods)
40
+ * STATUS QUERIES (4 methods)
41
41
  * 4. isLocked() - Check if lock is currently acquired
42
- * 5. getQueueLength() - Get number of operations waiting for lock
42
+ * 5. heldForMs() - Milliseconds the lock has been held (0 when free)
43
+ * 6. isReentrant() - Whether the current async context already holds the lock
44
+ * 7. getQueueLength() - Get number of operations waiting for lock
45
+ *
46
+ * LOCK RELEASE (1 method)
47
+ * 8. forceRelease() - Force-release the lock, rejecting every queued waiter
48
+ * (used by shutdown/cleanup paths; returns whether it was held)
43
49
  *
44
50
  * ===============================================================================
45
51
  *
@@ -44,11 +44,6 @@
44
44
  * blockchainToFloat that returns NaN instead of throwing; kept local so
45
45
  * the offline exporter avoids pulling in utils/math's dependency tree)
46
46
  * - buildOrientationHypothesis(...) - Trade fields for one pays-asset orientation
47
- * - deriveTradeFromFillBlock(block, assetContext) - Derive a trade from a
48
- * parsed FILL DETECTED block (side from pays-asset orientation, price from
49
- * human-scaled amounts). Bare pre-#22 blocks without asset IDs are
50
- * disambiguated via log-distance to the grid median price.
51
- * Returns: FillEntry or null (with reason logged by caller)
52
47
  * - resolveExportAssetContext(botKey, botConfig) - Resolve offline asset metadata
53
48
  * Reads profiles/orders/<botKey>.json for assetA/assetB ids+precisions and
54
49
  * grid price stats. No chain access (export stays offline/browser-safe).
@@ -44,11 +44,6 @@
44
44
  * blockchainToFloat that returns NaN instead of throwing; kept local so
45
45
  * the offline exporter avoids pulling in utils/math's dependency tree)
46
46
  * - buildOrientationHypothesis(...) - Trade fields for one pays-asset orientation
47
- * - deriveTradeFromFillBlock(block, assetContext) - Derive a trade from a
48
- * parsed FILL DETECTED block (side from pays-asset orientation, price from
49
- * human-scaled amounts). Bare pre-#22 blocks without asset IDs are
50
- * disambiguated via log-distance to the grid median price.
51
- * Returns: FillEntry or null (with reason logged by caller)
52
47
  * - resolveExportAssetContext(botKey, botConfig) - Resolve offline asset metadata
53
48
  * Reads profiles/orders/<botKey>.json for assetA/assetB ids+precisions and
54
49
  * grid price stats. No chain access (export stays offline/browser-safe).
@@ -516,8 +511,8 @@ async function exportBotTrades(botKey, botConfig, outputDir = './exports') {
516
511
  try {
517
512
  const logFiles = storage.readdir(logsDir);
518
513
  const want = String(botKey).toLowerCase();
519
- // Case-insensitive: log files use the display name (XRP-BTS.log)
520
- // while bot keys are lowercase (xrp-bts). Prefer the exact
514
+ // Case-insensitive: log files use the display name (<bot>.log)
515
+ // while bot keys are lowercase (e.g. <botKey>). Prefer the exact
521
516
  // "<key>.log" hit, fall back to any non-error log containing the key.
522
517
  const exactLog = logFiles.find((f) => f.toLowerCase() === `${want}.log`);
523
518
  const matchingLog = exactLog || logFiles.find((f) => f.toLowerCase().includes(want) && f.endsWith('.log') && !f.toLowerCase().includes('error'));
@@ -15,7 +15,7 @@
15
15
  * Time/Performance (ms, %): 1-2 decimals - readable metrics
16
16
  *
17
17
  * ===============================================================================
18
- * TABLE OF CONTENTS (15 exported functions)
18
+ * TABLE OF CONTENTS (17 exported functions)
19
19
  * ===============================================================================
20
20
  *
21
21
  * SECTION 1: ASSET FORMATTING (4 functions)
@@ -38,11 +38,13 @@
38
38
  * SECTION 4: RATIO/METRIC FORMATTING (1 function)
39
39
  * 12. formatMetric2(value) - Format to 2 decimals (timing, performance)
40
40
  *
41
- * SECTION 5: HELPER UTILITIES (4 functions)
41
+ * SECTION 5: HELPER UTILITIES (5 functions)
42
42
  * 13. isValidNumber(value) - Check if value is defined and finite
43
43
  * 14. toFiniteNumber(value, defaultValue) - Convert to finite number with fallback
44
- * 15. positiveOrNull(value) - Convert to a strictly-positive number, else null
45
- * 16. safeFormat(value, decimals, fallback) - Safely format with fallback
44
+ * 15. toKnownNumber(value, absentValue) - Convert to finite number, treating an
45
+ * explicitly absent value (null/undefined/empty) as the absent sentinel
46
+ * 16. positiveOrNull(value) - Convert to a strictly-positive number, else null
47
+ * 17. safeFormat(value, decimals, fallback) - Safely format with fallback
46
48
  *
47
49
  * ===============================================================================
48
50
  */
@@ -15,7 +15,7 @@
15
15
  * Time/Performance (ms, %): 1-2 decimals - readable metrics
16
16
  *
17
17
  * ===============================================================================
18
- * TABLE OF CONTENTS (15 exported functions)
18
+ * TABLE OF CONTENTS (17 exported functions)
19
19
  * ===============================================================================
20
20
  *
21
21
  * SECTION 1: ASSET FORMATTING (4 functions)
@@ -38,11 +38,13 @@
38
38
  * SECTION 4: RATIO/METRIC FORMATTING (1 function)
39
39
  * 12. formatMetric2(value) - Format to 2 decimals (timing, performance)
40
40
  *
41
- * SECTION 5: HELPER UTILITIES (4 functions)
41
+ * SECTION 5: HELPER UTILITIES (5 functions)
42
42
  * 13. isValidNumber(value) - Check if value is defined and finite
43
43
  * 14. toFiniteNumber(value, defaultValue) - Convert to finite number with fallback
44
- * 15. positiveOrNull(value) - Convert to a strictly-positive number, else null
45
- * 16. safeFormat(value, decimals, fallback) - Safely format with fallback
44
+ * 15. toKnownNumber(value, absentValue) - Convert to finite number, treating an
45
+ * explicitly absent value (null/undefined/empty) as the absent sentinel
46
+ * 16. positiveOrNull(value) - Convert to a strictly-positive number, else null
47
+ * 17. safeFormat(value, decimals, fallback) - Safely format with fallback
46
48
  *
47
49
  * ===============================================================================
48
50
  */