dexbot 1.6.15 → 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 (102) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +4 -4
  3. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
  4. package/claw/modules/chain_queries.ts +3 -3
  5. package/claw/package.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  8. package/dist/analysis/ama_fitting/fetch_lp_candles.js +8 -1
  9. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
  10. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
  11. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
  12. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
  13. package/dist/analysis/bot_key_utils.js +9 -7
  14. package/dist/analysis/chart_utils.d.ts +9 -2
  15. package/dist/analysis/chart_utils.js +51 -1
  16. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
  17. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +19 -5
  18. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +21 -2
  19. package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
  20. package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
  21. package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
  22. package/dist/dexbot.js +89 -138
  23. package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
  24. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
  25. package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
  26. package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
  27. package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
  28. package/dist/market_adapter/inputs/window_cache.js +53 -17
  29. package/dist/market_adapter/lp_chart_core.js +1 -0
  30. package/dist/market_adapter/utils/chain.js +4 -3
  31. package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
  32. package/dist/market_adapter/utils/pair_orientation.js +142 -0
  33. package/dist/modules/account_bots.d.ts +37 -3
  34. package/dist/modules/account_bots.js +77 -37
  35. package/dist/modules/account_orders.d.ts +4 -1
  36. package/dist/modules/account_orders.js +4 -1
  37. package/dist/modules/bitshares-native/resolvers.js +3 -3
  38. package/dist/modules/bitshares_client.d.ts +12 -10
  39. package/dist/modules/bitshares_client.js +12 -10
  40. package/dist/modules/bot_settings.js +3 -3
  41. package/dist/modules/chain_keys.d.ts +5 -1
  42. package/dist/modules/chain_keys.js +5 -1
  43. package/dist/modules/chain_orders.d.ts +6 -2
  44. package/dist/modules/chain_orders.js +6 -2
  45. package/dist/modules/constants.d.ts +5 -0
  46. package/dist/modules/constants.js +7 -1
  47. package/dist/modules/dexbot_class.d.ts +3 -1
  48. package/dist/modules/dexbot_class.js +3 -1
  49. package/dist/modules/graceful_shutdown.d.ts +6 -2
  50. package/dist/modules/graceful_shutdown.js +6 -2
  51. package/dist/modules/launcher/bot_supervisor.js +4 -0
  52. package/dist/modules/launcher/launch_modes.js +6 -3
  53. package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
  54. package/dist/modules/launcher/monolithic_runtime.js +60 -1
  55. package/dist/modules/launcher/runtime_mode.d.ts +79 -0
  56. package/dist/modules/launcher/runtime_mode.js +223 -0
  57. package/dist/modules/market_adapter_whitelist.d.ts +8 -0
  58. package/dist/modules/market_adapter_whitelist.js +8 -0
  59. package/dist/modules/order/accounting.d.ts +15 -1
  60. package/dist/modules/order/accounting.js +15 -1
  61. package/dist/modules/order/async_lock.d.ts +9 -3
  62. package/dist/modules/order/async_lock.js +9 -3
  63. package/dist/modules/order/export.d.ts +0 -5
  64. package/dist/modules/order/export.js +0 -5
  65. package/dist/modules/order/format.d.ts +6 -4
  66. package/dist/modules/order/format.js +6 -4
  67. package/dist/modules/order/grid.d.ts +29 -18
  68. package/dist/modules/order/grid.js +29 -18
  69. package/dist/modules/order/index.d.ts +1 -1
  70. package/dist/modules/order/index.js +1 -1
  71. package/dist/modules/order/logger_state.d.ts +1 -1
  72. package/dist/modules/order/logger_state.js +1 -1
  73. package/dist/modules/order/sync_engine.d.ts +26 -11
  74. package/dist/modules/order/sync_engine.js +26 -11
  75. package/dist/modules/order/utils/math.d.ts +59 -21
  76. package/dist/modules/order/utils/math.js +59 -21
  77. package/dist/modules/order/utils/order.d.ts +64 -20
  78. package/dist/modules/order/utils/order.js +64 -20
  79. package/dist/modules/order/utils/system.d.ts +41 -11
  80. package/dist/modules/order/utils/system.js +41 -11
  81. package/dist/modules/order/utils/validate.d.ts +5 -2
  82. package/dist/modules/order/utils/validate.js +5 -2
  83. package/dist/modules/utils/asset_symbols.d.ts +5 -5
  84. package/dist/modules/utils/asset_symbols.js +5 -5
  85. package/dist/modules/utils/errors.d.ts +2 -1
  86. package/dist/modules/utils/errors.js +2 -1
  87. package/dist/scripts/rich_list.d.ts +32 -0
  88. package/dist/scripts/rich_list.js +16 -8
  89. package/dist/unlock.js +49 -18
  90. package/docs/BITSHARES_ONBOARDING.md +7 -0
  91. package/docs/COW_INVARIANTS.md +1 -1
  92. package/docs/DEXBOT_COMPARISON.md +5 -5
  93. package/docs/EVOLUTION.md +8 -7
  94. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -3
  95. package/docs/GRID_RECALCULATION.md +18 -6
  96. package/docs/LIFECYCLE.md +8 -8
  97. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +4 -4
  98. package/docs/README.md +1 -1
  99. package/docs/WORKFLOW.md +5 -5
  100. package/market_adapter/README.md +10 -3
  101. package/package.json +3 -1
  102. package/tests/README.md +29 -0
@@ -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).
@@ -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
  */
@@ -12,7 +12,7 @@
12
12
  * - Detects and flags out-of-spread conditions
13
13
  *
14
14
  * ===============================================================================
15
- * TABLE OF CONTENTS - Grid Functions (23 exported functions)
15
+ * TABLE OF CONTENTS - Grid Functions (34 exports)
16
16
  * ===============================================================================
17
17
  *
18
18
  * CONFIGURATION & CALCULATION (2 functions)
@@ -37,36 +37,49 @@
37
37
  * GRID STATE CHECKING (2 functions)
38
38
  * 8. checkAndUpdateGridIfNeeded(manager) - Complete fund trigger: available-
39
39
  * funds ratio + over-allocation + on-chain committed-drift legs
40
- * 8b. checkCommittedSizeDrift(manager) - Async committed-drift-only accessor
40
+ * 9. checkCommittedSizeDrift(manager) - Async committed-drift-only accessor
41
41
  * (the drift core is folded into checkAndUpdateGridIfNeeded)
42
42
  *
43
43
  * BLOCKCHAIN SYNCHRONIZATION (2 functions - async)
44
- * 9. _recalculateGridOrderSizesFromBlockchain(manager, orderType, options) - Recalculate sizes from blockchain
45
- * 10. updateGridFromBlockchainSnapshot(manager, orderType, fromBlockchainTimer, overrideBoundaryIdx) - Update grid from blockchain
44
+ * 10. _recalculateGridOrderSizesFromBlockchain(manager, orderType, options) - Recalculate sizes from blockchain
45
+ * 11. updateGridFromBlockchainSnapshot(manager, orderType, fromBlockchainTimer, overrideBoundaryIdx) - Update grid from blockchain
46
46
  *
47
47
  * GRID COMPARISON (2 functions - async)
48
- * 11. compareGrids(calculatedGrid, persistedGrid, manager) - Compare two grids
48
+ * 12. compareGrids(calculatedGrid, persistedGrid, manager) - Compare two grids
49
49
  * Validates grid structure and reports divergence metrics
50
- * 12. monitorDivergence(manager, calculatedGrid, persistedGrid) - Unified divergence check
50
+ * 13. monitorDivergence(manager, calculatedGrid, persistedGrid) - Unified divergence check
51
51
  * Runs ratio-based + RMS-based checks and returns combined result
52
52
  *
53
53
  * SPREAD MANAGEMENT (2 functions)
54
- * 13. calculateCurrentSpread(manager) - Calculate current bid-ask spread
55
- * 14. checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch) - Check and flag spread condition
54
+ * 14. calculateCurrentSpread(manager) - Calculate current bid-ask spread
55
+ * 15. checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch) - Check and flag spread condition
56
56
  *
57
57
  * GRID HEALTH MONITORING (4 functions)
58
- * 15. checkGridHealth(manager, updateOrdersOnChainBatch) - Monitor grid health
59
- * 16. checkWindowDust(manager) - Dust check scoped to the active buy/sell window
60
- * 17. hasAnyDust(manager, partials, side) - Check for dust orders
61
- * 18. getDustOrders(manager, partials, side) - Get dust order IDs
58
+ * 16. checkGridHealth(manager, updateOrdersOnChainBatch) - Monitor grid health
59
+ * 17. checkWindowDust(manager) - Dust check scoped to the active buy/sell window
60
+ * 18. hasAnyDust(manager, partials, side) - Check for dust orders
61
+ * 19. getDustOrders(manager, partials, side) - Get dust order IDs
62
62
  *
63
63
  * SIDE SELECTION (1 function)
64
- * 19. determineOrderSideByFunds(manager, currentMarketPrice) - Determine priority side
64
+ * 20. determineOrderSideByFunds(manager, currentMarketPrice) - Determine priority side
65
+ *
66
+ * SPREAD CORRECTION PLANNING (11 exports)
67
+ * 21. SPREAD_CORRECTION_REFUSAL - Refusal-cause vocabulary constant
68
+ * 22. SpreadCorrectionRefusalCause - Refusal-cause union type
69
+ * 23. isTransientSpreadRefusal(cause) - Whether a refusal cause is retryable
70
+ * 24. classifySpreadRefusalCause(...) - Classify why a correction batch did not land
71
+ * 25. recordSpreadCorrectionRefusal(...) - Record a refusal on the manager
72
+ * 26. recordSpreadCorrectionRetry(...) - Count a bounded re-plan retry
73
+ * 27. getOccupiedCorrectionSlots(...) - Planned CREATE destinations already occupied
74
+ * 28. replanSpreadCorrectionFromFreshMaster(...) - Re-plan from the current master
75
+ * 29. OccupiedCorrectionResolution - Outcome of plan-time collision resolution
76
+ * 30. resolveOccupiedCorrection(...) - Resolve a correction whose destination was taken
77
+ * 31. prepareSpreadCorrectionOrders(...) - Prepare orders to correct a wide spread
65
78
  *
66
79
  * BLOAT STATUS (3 functions)
67
- * 20. isGridBloated(manager, orders) - Check whether the grid is bloated
68
- * 21. isGridBloatGraceActive(manager) - Check the bloat grace state
69
- * 22. clearGridBloatFlag(manager) - Clear the bloat state
80
+ * 32. isGridBloated(manager, orders) - Check whether the grid is bloated
81
+ * 33. isGridBloatGraceActive(manager) - Check the bloat grace state
82
+ * 34. clearGridBloatFlag(manager) - Clear the bloat state
70
83
  *
71
84
  * ===============================================================================
72
85
  *
@@ -589,8 +602,6 @@ export declare function calculateCurrentSpread(manager: OrderManagerLike): numbe
589
602
  * - RACE CONDITION WINDOW: Between lock release and blockchain submission
590
603
  * - MITIGATION: Pre-flight fund verification before submission; comprehensive error handling
591
604
  *
592
- * See RACE_CONDITION_ANALYSIS.md for detailed vulnerability documentation.
593
- *
594
605
  * @param {import('./types').OrderManager} manager - Manager instance
595
606
  * @param {Object} BitShares - BitShares API client
596
607
  * @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function
@@ -12,7 +12,7 @@
12
12
  * - Detects and flags out-of-spread conditions
13
13
  *
14
14
  * ===============================================================================
15
- * TABLE OF CONTENTS - Grid Functions (23 exported functions)
15
+ * TABLE OF CONTENTS - Grid Functions (34 exports)
16
16
  * ===============================================================================
17
17
  *
18
18
  * CONFIGURATION & CALCULATION (2 functions)
@@ -37,36 +37,49 @@
37
37
  * GRID STATE CHECKING (2 functions)
38
38
  * 8. checkAndUpdateGridIfNeeded(manager) - Complete fund trigger: available-
39
39
  * funds ratio + over-allocation + on-chain committed-drift legs
40
- * 8b. checkCommittedSizeDrift(manager) - Async committed-drift-only accessor
40
+ * 9. checkCommittedSizeDrift(manager) - Async committed-drift-only accessor
41
41
  * (the drift core is folded into checkAndUpdateGridIfNeeded)
42
42
  *
43
43
  * BLOCKCHAIN SYNCHRONIZATION (2 functions - async)
44
- * 9. _recalculateGridOrderSizesFromBlockchain(manager, orderType, options) - Recalculate sizes from blockchain
45
- * 10. updateGridFromBlockchainSnapshot(manager, orderType, fromBlockchainTimer, overrideBoundaryIdx) - Update grid from blockchain
44
+ * 10. _recalculateGridOrderSizesFromBlockchain(manager, orderType, options) - Recalculate sizes from blockchain
45
+ * 11. updateGridFromBlockchainSnapshot(manager, orderType, fromBlockchainTimer, overrideBoundaryIdx) - Update grid from blockchain
46
46
  *
47
47
  * GRID COMPARISON (2 functions - async)
48
- * 11. compareGrids(calculatedGrid, persistedGrid, manager) - Compare two grids
48
+ * 12. compareGrids(calculatedGrid, persistedGrid, manager) - Compare two grids
49
49
  * Validates grid structure and reports divergence metrics
50
- * 12. monitorDivergence(manager, calculatedGrid, persistedGrid) - Unified divergence check
50
+ * 13. monitorDivergence(manager, calculatedGrid, persistedGrid) - Unified divergence check
51
51
  * Runs ratio-based + RMS-based checks and returns combined result
52
52
  *
53
53
  * SPREAD MANAGEMENT (2 functions)
54
- * 13. calculateCurrentSpread(manager) - Calculate current bid-ask spread
55
- * 14. checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch) - Check and flag spread condition
54
+ * 14. calculateCurrentSpread(manager) - Calculate current bid-ask spread
55
+ * 15. checkSpreadCondition(manager, BitShares, updateOrdersOnChainBatch) - Check and flag spread condition
56
56
  *
57
57
  * GRID HEALTH MONITORING (4 functions)
58
- * 15. checkGridHealth(manager, updateOrdersOnChainBatch) - Monitor grid health
59
- * 16. checkWindowDust(manager) - Dust check scoped to the active buy/sell window
60
- * 17. hasAnyDust(manager, partials, side) - Check for dust orders
61
- * 18. getDustOrders(manager, partials, side) - Get dust order IDs
58
+ * 16. checkGridHealth(manager, updateOrdersOnChainBatch) - Monitor grid health
59
+ * 17. checkWindowDust(manager) - Dust check scoped to the active buy/sell window
60
+ * 18. hasAnyDust(manager, partials, side) - Check for dust orders
61
+ * 19. getDustOrders(manager, partials, side) - Get dust order IDs
62
62
  *
63
63
  * SIDE SELECTION (1 function)
64
- * 19. determineOrderSideByFunds(manager, currentMarketPrice) - Determine priority side
64
+ * 20. determineOrderSideByFunds(manager, currentMarketPrice) - Determine priority side
65
+ *
66
+ * SPREAD CORRECTION PLANNING (11 exports)
67
+ * 21. SPREAD_CORRECTION_REFUSAL - Refusal-cause vocabulary constant
68
+ * 22. SpreadCorrectionRefusalCause - Refusal-cause union type
69
+ * 23. isTransientSpreadRefusal(cause) - Whether a refusal cause is retryable
70
+ * 24. classifySpreadRefusalCause(...) - Classify why a correction batch did not land
71
+ * 25. recordSpreadCorrectionRefusal(...) - Record a refusal on the manager
72
+ * 26. recordSpreadCorrectionRetry(...) - Count a bounded re-plan retry
73
+ * 27. getOccupiedCorrectionSlots(...) - Planned CREATE destinations already occupied
74
+ * 28. replanSpreadCorrectionFromFreshMaster(...) - Re-plan from the current master
75
+ * 29. OccupiedCorrectionResolution - Outcome of plan-time collision resolution
76
+ * 30. resolveOccupiedCorrection(...) - Resolve a correction whose destination was taken
77
+ * 31. prepareSpreadCorrectionOrders(...) - Prepare orders to correct a wide spread
65
78
  *
66
79
  * BLOAT STATUS (3 functions)
67
- * 20. isGridBloated(manager, orders) - Check whether the grid is bloated
68
- * 21. isGridBloatGraceActive(manager) - Check the bloat grace state
69
- * 22. clearGridBloatFlag(manager) - Clear the bloat state
80
+ * 32. isGridBloated(manager, orders) - Check whether the grid is bloated
81
+ * 33. isGridBloatGraceActive(manager) - Check the bloat grace state
82
+ * 34. clearGridBloatFlag(manager) - Clear the bloat state
70
83
  *
71
84
  * ===============================================================================
72
85
  *
@@ -2378,8 +2391,6 @@ export function calculateCurrentSpread(manager) {
2378
2391
  * - RACE CONDITION WINDOW: Between lock release and blockchain submission
2379
2392
  * - MITIGATION: Pre-flight fund verification before submission; comprehensive error handling
2380
2393
  *
2381
- * See RACE_CONDITION_ANALYSIS.md for detailed vulnerability documentation.
2382
- *
2383
2394
  * @param {import('./types').OrderManager} manager - Manager instance
2384
2395
  * @param {Object} BitShares - BitShares API client
2385
2396
  * @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function
@@ -33,7 +33,7 @@
33
33
  * 1. manager.ts - OrderManager class (order lifecycle, fund tracking)
34
34
  * 2. grid.ts - Grid class (grid creation, synchronization, health)
35
35
  * 3. utils/math.ts, utils/order.ts, utils/system.ts - Helper functions by concern
36
- * 4. format.ts - Numeric formatting (18 functions for consistent display)
36
+ * 4. format.ts - Numeric formatting (17 functions for consistent display)
37
37
  * 5. accounting.ts - Accountant class (fund calculations and reconciliation)
38
38
  * 6. logger.ts - Logger class (structured, color-coded output)
39
39
  * 7. async_lock.ts - AsyncLock class (race condition prevention)
@@ -33,7 +33,7 @@
33
33
  * 1. manager.ts - OrderManager class (order lifecycle, fund tracking)
34
34
  * 2. grid.ts - Grid class (grid creation, synchronization, health)
35
35
  * 3. utils/math.ts, utils/order.ts, utils/system.ts - Helper functions by concern
36
- * 4. format.ts - Numeric formatting (18 functions for consistent display)
36
+ * 4. format.ts - Numeric formatting (17 functions for consistent display)
37
37
  * 5. accounting.ts - Accountant class (fund calculations and reconciliation)
38
38
  * 6. logger.ts - Logger class (structured, color-coded output)
39
39
  * 7. async_lock.ts - AsyncLock class (race condition prevention)
@@ -16,7 +16,7 @@
16
16
  * - Maintain audit trail for debugging
17
17
  *
18
18
  * ===============================================================================
19
- * TABLE OF CONTENTS - LoggerState Class (2 methods)
19
+ * TABLE OF CONTENTS - LoggerState Class (3 methods)
20
20
  * ===============================================================================
21
21
  *
22
22
  * INITIALIZATION (1 method)
@@ -17,7 +17,7 @@
17
17
  * - Maintain audit trail for debugging
18
18
  *
19
19
  * ===============================================================================
20
- * TABLE OF CONTENTS - LoggerState Class (2 methods)
20
+ * TABLE OF CONTENTS - LoggerState Class (3 methods)
21
21
  * ===============================================================================
22
22
  *
23
23
  * INITIALIZATION (1 method)
@@ -15,12 +15,17 @@
15
15
  * Uses AsyncLock to prevent concurrent sync operations (defense-in-depth locking).
16
16
  *
17
17
  * ===============================================================================
18
- * TABLE OF CONTENTS - SyncEngine Class (8 methods) + 1 module-level helper
18
+ * TABLE OF CONTENTS - SyncEngine Class (12 methods) + module-level helpers
19
19
  * ===============================================================================
20
20
  *
21
- * MODULE-LEVEL HELPER (internal, not exported):
22
- * hasEquivalentRawOnChainOrder(a, b) - Compare two chain orders for equivalence
23
- * Used internally during sync to detect redundant/duplicate chain entries
21
+ * MODULE-LEVEL HELPERS (internal, not exported):
22
+ * readSingleOrderSeam / batchReadOrdersSeam - Chain-order read indirection seams
23
+ * confirmSuspectEmptyRead(mgr) - Re-read after a suspicious empty snapshot
24
+ * describeNearestAdoptionCandidates(mgr, chainOrder, precision, matchedIds) -
25
+ * Diagnostic candidates for nearest-slot adoption
26
+ * chainPriceOnSameLevel(...) - Chain price vs a grid level under precision rules
27
+ * adoptedSlotKeepsItsOwnPrice(mgr, adopted, chainOrderId, path) - Adoption guard
28
+ * adoptChainOrderIntoSlot(...) - Adopt an unmatched chain order into a free slot
24
29
  *
25
30
  * INITIALIZATION (1 method)
26
31
  * 1. constructor(manager) - Create new SyncEngine with manager reference
@@ -39,30 +44,40 @@
39
44
  * Pass 1: Match grid orders to chain (known grid → chain, includes orphan cleanup)
40
45
  * Pass 2: Add missing chain orders (unknown chain → grid)
41
46
  *
42
- * FILL PROCESSING (2 methods)
43
- * 5. syncFromFillHistory(fill) - Process single fill event synchronously
47
+ * FILL PROCESSING (5 methods)
48
+ * 5. _findMatchingGridOrder(mgr, orderId) - Look up the grid slot owning a chain order (internal)
49
+ *
50
+ * 6. _computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw) -
51
+ * Resolve the asset/side context for a fill (internal)
52
+ *
53
+ * 7. _computeFillTransitionResult(mgr, params) - Compute the post-fill slot
54
+ * transition and fund deltas without mutating state (internal, async)
55
+ *
56
+ * 8. syncFromFillHistory(fill) - Process single fill event synchronously
44
57
  * Updates grid order state based on fill data
45
58
  * Updates fund state and accounting
46
59
  * Handles both maker and taker fills
47
60
  *
48
- * 6. syncFromFillHistoryBatch(fills) - Process multiple fill events in batch
61
+ * 9. syncFromFillHistoryBatch(fills) - Process multiple fill events in batch
49
62
  * Acquires _gridLock once for all fills in block group
50
63
  * Batches drift refetch into one get_objects RPC call
51
64
  * Applies all grid mutations in a single applyGridUpdateBatch
52
65
  *
53
- * FULL SYNCHRONIZATION (1 method - async)
54
- * 7. synchronizeWithChain(chainData, source) - Full sync (fetch + sync) (async)
66
+ * FULL SYNCHRONIZATION (2 methods - async)
67
+ * 10. _assertGenesisInvariant(mgr) - Fail-closed check that a snapshot has a genesis ladder (internal)
68
+ *
69
+ * 11. synchronizeWithChain(chainData, source) - Full sync (fetch + sync) (async)
55
70
  * Fetches fresh account balances
56
71
  * Calls syncFromOpenOrders() with chain data
57
72
  * Source: event type that triggered sync (fill, poll, broadcast, etc.)
58
73
  *
59
74
  * ACCOUNT STATE (2 methods - async)
60
- * 8. fetchAccountBalancesAndSetTotals(accountId) - Fetch account totals (async)
75
+ * 12. fetchAccountBalancesAndSetTotals() - Fetch account totals (async)
61
76
  * Retrieves BUY/SELL totals and free balances from blockchain
62
77
  * Sets manager.accountTotals
63
78
  * Triggers fund recalculation
64
79
  *
65
- * 9. initializeAssets() - Initialize asset metadata (async)
80
+ * 13. initializeAssets() - Initialize asset metadata (async)
66
81
  * Fetches asset precision and other metadata
67
82
  * Sets manager.assets
68
83
  * Called once at bot startup
@@ -15,12 +15,17 @@
15
15
  * Uses AsyncLock to prevent concurrent sync operations (defense-in-depth locking).
16
16
  *
17
17
  * ===============================================================================
18
- * TABLE OF CONTENTS - SyncEngine Class (8 methods) + 1 module-level helper
18
+ * TABLE OF CONTENTS - SyncEngine Class (12 methods) + module-level helpers
19
19
  * ===============================================================================
20
20
  *
21
- * MODULE-LEVEL HELPER (internal, not exported):
22
- * hasEquivalentRawOnChainOrder(a, b) - Compare two chain orders for equivalence
23
- * Used internally during sync to detect redundant/duplicate chain entries
21
+ * MODULE-LEVEL HELPERS (internal, not exported):
22
+ * readSingleOrderSeam / batchReadOrdersSeam - Chain-order read indirection seams
23
+ * confirmSuspectEmptyRead(mgr) - Re-read after a suspicious empty snapshot
24
+ * describeNearestAdoptionCandidates(mgr, chainOrder, precision, matchedIds) -
25
+ * Diagnostic candidates for nearest-slot adoption
26
+ * chainPriceOnSameLevel(...) - Chain price vs a grid level under precision rules
27
+ * adoptedSlotKeepsItsOwnPrice(mgr, adopted, chainOrderId, path) - Adoption guard
28
+ * adoptChainOrderIntoSlot(...) - Adopt an unmatched chain order into a free slot
24
29
  *
25
30
  * INITIALIZATION (1 method)
26
31
  * 1. constructor(manager) - Create new SyncEngine with manager reference
@@ -39,30 +44,40 @@
39
44
  * Pass 1: Match grid orders to chain (known grid → chain, includes orphan cleanup)
40
45
  * Pass 2: Add missing chain orders (unknown chain → grid)
41
46
  *
42
- * FILL PROCESSING (2 methods)
43
- * 5. syncFromFillHistory(fill) - Process single fill event synchronously
47
+ * FILL PROCESSING (5 methods)
48
+ * 5. _findMatchingGridOrder(mgr, orderId) - Look up the grid slot owning a chain order (internal)
49
+ *
50
+ * 6. _computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw) -
51
+ * Resolve the asset/side context for a fill (internal)
52
+ *
53
+ * 7. _computeFillTransitionResult(mgr, params) - Compute the post-fill slot
54
+ * transition and fund deltas without mutating state (internal, async)
55
+ *
56
+ * 8. syncFromFillHistory(fill) - Process single fill event synchronously
44
57
  * Updates grid order state based on fill data
45
58
  * Updates fund state and accounting
46
59
  * Handles both maker and taker fills
47
60
  *
48
- * 6. syncFromFillHistoryBatch(fills) - Process multiple fill events in batch
61
+ * 9. syncFromFillHistoryBatch(fills) - Process multiple fill events in batch
49
62
  * Acquires _gridLock once for all fills in block group
50
63
  * Batches drift refetch into one get_objects RPC call
51
64
  * Applies all grid mutations in a single applyGridUpdateBatch
52
65
  *
53
- * FULL SYNCHRONIZATION (1 method - async)
54
- * 7. synchronizeWithChain(chainData, source) - Full sync (fetch + sync) (async)
66
+ * FULL SYNCHRONIZATION (2 methods - async)
67
+ * 10. _assertGenesisInvariant(mgr) - Fail-closed check that a snapshot has a genesis ladder (internal)
68
+ *
69
+ * 11. synchronizeWithChain(chainData, source) - Full sync (fetch + sync) (async)
55
70
  * Fetches fresh account balances
56
71
  * Calls syncFromOpenOrders() with chain data
57
72
  * Source: event type that triggered sync (fill, poll, broadcast, etc.)
58
73
  *
59
74
  * ACCOUNT STATE (2 methods - async)
60
- * 8. fetchAccountBalancesAndSetTotals(accountId) - Fetch account totals (async)
75
+ * 12. fetchAccountBalancesAndSetTotals() - Fetch account totals (async)
61
76
  * Retrieves BUY/SELL totals and free balances from blockchain
62
77
  * Sets manager.accountTotals
63
78
  * Triggers fund recalculation
64
79
  *
65
- * 9. initializeAssets() - Initialize asset metadata (async)
80
+ * 13. initializeAssets() - Initialize asset metadata (async)
66
81
  * Fetches asset precision and other metadata
67
82
  * Sets manager.assets
68
83
  * Called once at bot startup