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
@@ -4,56 +4,93 @@
4
4
  * Pure numeric calculations, blockchain conversions, fee math, and fund allocation.
5
5
  *
6
6
  * ===============================================================================
7
- * TABLE OF CONTENTS (44 exported functions)
7
+ * TABLE OF CONTENTS (78 exports)
8
8
  * ===============================================================================
9
9
  *
10
- * SECTION 1: PARSING & VALIDATION (6 functions)
10
+ * SECTION 1: GENESIS LADDER & RAIL GEOMETRY (28 items)
11
+ * - GridGenesis - Genesis ladder type: start price, increment, gap slots,
12
+ * price levels and their hash
13
+ * - priceLevelsForGenesis(genesis) - Extract the frozen price ladder from a genesis
14
+ * - buildGenesisFromPriceLevels(levels, config) - Build a genesis from precomputed levels
15
+ * - derivePriceLevels(startPrice, increment, minPrice, maxPrice) - Derive the
16
+ * geometric price ladder (the "rail") from a live config
17
+ * - hashPriceLevels(levels) - Deterministic hash of a price ladder
18
+ * - priceForSlot(idx, genesis) - Authoritative price for a slot index
19
+ * - slotIndexForPrice(price, genesis) - Resolve a price to its slot index
20
+ * - slotIdForPrice(price, genesis) - Resolve a price to its "slot-N" id
21
+ * - assertSlotPriceInvariant(...) - Reject a slot whose price disagrees with its index
22
+ * - priceSlotEqual(...) - Compare slot/price pairs under the genesis invariant
23
+ * - sameGridLevel(a, b) - Same ladder level, resolving each price against its genesis
24
+ * - sameGridPrice(a, b) - Same genesis-derived ladder level by precision
25
+ * - pricesOnSameLevel(a, b, ...) - Same order-book price LEVEL under precision
26
+ * - isChainPriceOutOfGrid(price, genesis, ...) - Whether a chain price is off the rail
27
+ * - getBtsSide(assets) - Which side of the pair holds BTS
28
+ * - getSellStartIdx(boundaryIdx, gapSlots) - Sell start index from boundary + gap
29
+ * - calculateGapSlots(incrementPercent, targetSpreadPercent) - Gap-slot count
30
+ * - resolveGapSlots(manager) - Configured gap-slot count for a manager
31
+ * - resolveGapBand(manager) - Gap-band geometry { start, end, gapSlots }
32
+ * - countGapBandSpread(manager) - Count SPREAD slots strictly inside the gap band
33
+ * - isSlotInRail(...) - Geometric rail-membership test for a slot
34
+ * - isSlotIndexInGapBand(idx, ...) - Whether a slot index sits inside the gap band
35
+ * - isEvacuationRotationAllowed(...) - Whether a gap-evacuation rotation is geometrically valid
36
+ * - isEvacuationSizeStillValid(...) - Re-proof a stamped evacuation size against live geometry
37
+ * - validateBoundaryCommit(...) - Validate a proposed boundary commit against geometry
38
+ * - validatePersistedBoundary(...) - Validate a boundary restored from disk
39
+ * - isTransientInBandRejection(reason) - Whether a persisted-boundary rejection is transient
40
+ * - BOUNDARY_REJECT_PLACED_IN_BAND - Rejection reason: target slot holds an in-band order
41
+ *
42
+ * SECTION 2: PARSING & VALIDATION (10 functions)
11
43
  * - isExplicitZeroAllocation(value) - Check if value is explicitly zero
12
44
  * - isPercentageString(v) - Check if value is percentage string
45
+ * - isPositiveNumber(value) - Check if value is a positive number
46
+ * - isPositiveNumberOrPercent(value) - Positive number or positive percentage string
47
+ * - isPositiveInt(value) - Check if value is a positive integer
13
48
  * - parsePercentageString(v) - Parse percentage string to decimal
49
+ * - toDecimal(value) - Convert number/percentage/numeric string to a decimal
14
50
  * - parseRelativeMultiplier(value) - Parse "3x" multiplier syntax to number
15
51
  * - resolveRelativePrice(value, startPrice, mode) - Resolve relative price values
16
52
  * - validateGridPriceBounds(min, max, center) - Reject bounds not bracketing center
17
53
  *
18
- * SECTION 2: FUND CALCULATIONS (4 functions)
54
+ * SECTION 3: FUND CALCULATIONS (8 functions)
19
55
  * - computeChainFundTotals(accountTotals, committedChain) - Compute total funds
20
56
  * - calculateAvailableFundsValue(side, accountTotals, funds, ...) - Calculate available funds
57
+ * - adjustBudgetForBtsFees(budget, btsFeeData, ...) - Reserve BTS fees from a side budget
58
+ * - getGridBestPrices(manager) - Best (highest) buy and best (lowest) sell price
21
59
  * - calculateSpreadFromOrders(activeBuys, activeSells) - Calculate spread percentage
22
60
  * - resolveConfigValue(value, total) - Resolve percentage or absolute config value
61
+ * - resolveConfigValueWithRegistry(value, total, registry) - Config value incl. shared-account funds
62
+ * - hasValidAccountTotals(accountTotals, checkFree) - Validate account totals structure
23
63
  *
24
- * SECTION 3: BLOCKCHAIN CONVERSIONS (5 functions)
64
+ * SECTION 4: BLOCKCHAIN CONVERSIONS (6 functions)
25
65
  * - blockchainToFloat(intValue, precision) - Convert blockchain int to float
26
66
  * - floatToBlockchainInt(floatValue, precision) - Convert float to blockchain int
67
+ * - floorToBlockchainInt(floatValue, precision) - Convert float to int by flooring
27
68
  * - quantizeFloat(value, precision) - Round float to blockchain precision
28
69
  * - normalizeInt(value, precision) - Normalize int within precision bounds
29
- * - hasValidAccountTotals(accountTotals, checkFree) - Validate account totals structure
70
+ * - quantumForPrecision(precision) - Smallest representable unit for a precision
30
71
  *
31
- * SECTION 4: PRECISION & FORMATTING UTILITIES (8 functions)
32
- * - roundTo(value, factor) - Round to a factor
33
- * - fixedTo(value, decimals) - Format to fixed decimal string
34
- * - roundToDecimals(value, decimals) - Round to N decimal places
72
+ * SECTION 5: PRECISION UTILITIES (4 functions)
35
73
  * - getPrecision(assets, orderType) - Get precision for order type
36
74
  * - getPrecisionByOrderType(assets, orderType) - Alias for getPrecision
37
- * - getPrecisionForSide(assets, side) - Get precision by side (buy/sell)
38
75
  * - getPrecisionsForManager(manager) - Get both asset precisions
39
76
  * - getPrecisionSlack(precision) - Calculate tolerance for precision
40
77
  *
41
- * SECTION 5: ORDER SIZE VALIDATION (7 functions)
78
+ * SECTION 6: ORDER SIZE VALIDATION (8 functions)
42
79
  * - calculatePriceTolerance(price, size, type, assets) - Calculate price match tolerance
80
+ * - findCrossedOrder(...) - Find an opposite-side order a placement would CROSS
43
81
  * - validateOrderAmountsWithinLimits(amountToSell, minToReceive) - Validate order limits
44
- * - getMinOrderSize(assets, type) - Get minimum order size for type
82
+ * - getMinOrderSize(orderType, assets, factor) - Get minimum order size
45
83
  * - getDustThresholdFactor() - Get dust threshold multiplier
46
84
  * - getSingleDustThreshold(idealSize, dustThresholdPercent) - Get single dust threshold
47
85
  * - getDoubleDustThreshold(idealSize, dustThresholdPercent) - Get double dust threshold
48
- * - getMinOrderSize(orderType, assets, factor) - Get minimum order size
49
86
  * - validateOrderSize(manager, size, type, context) - Validate order size against minimums
50
87
  *
51
- * SECTION 6: FEE CALCULATIONS (2 functions + 2 internal)
88
+ * SECTION 7: FEE CALCULATIONS (3 functions)
52
89
  * - getAssetFees(assetSymbol, assetAmount, isMaker) - Get fee info for asset
90
+ * - getAssetFeesSafe(assetSymbol, assetAmount, isMaker) - Fee info without throwing
53
91
  * - _setFeeCache(cache) - Set internal fee cache (internal)
54
- * - _getFeeCache() - Get internal fee cache (internal)
55
92
  *
56
- * SECTION 7: FUND ALLOCATION (6 functions)
93
+ * SECTION 8: FUND ALLOCATION (6 functions)
57
94
  * - allocateFundsByWeights(available, targetCount) - Allocate funds by weight
58
95
  * - cloneWeightDistribution(weightDistribution, base) - Clone weight distribution safely
59
96
  * - calculateOrderSizes(manager, orderType) - Calculate order sizes for placement
@@ -61,13 +98,14 @@
61
98
  * - calculateGridSideDivergenceMetric(manager, orderType, threshold) - Calculate divergence
62
99
  * - clamp(value, min, max) - Clamp a value between min and max bounds
63
100
  *
64
- * SECTION 8: FEE DEDUCTION (3 functions)
101
+ * SECTION 9: FEE DEDUCTION (2 functions)
65
102
  * - calculateOrderCreationFees(count, btsFeeData) - Calculate total creation fees
66
- * - deductOrderFeesFromFunds(available, count, btsFeeData, btsSide) - Deduct fees from funds
67
103
  * - calculateSwapInAmount(targetReceive, poolReserveOut, poolReserveIn) - AMM swap math
68
104
  *
69
- * SECTION 9: GRID UTILITIES (1 function)
70
- * - calculateGapSlots(incrementPercent, targetSpreadPercent) - Calculate gap slots count
105
+ * SECTION 10: FORMATTING (3 functions)
106
+ * - roundTo(value, factor) - Round to a factor
107
+ * - fixedTo(value, decimals) - Format to fixed decimal string
108
+ * - roundToDecimals(value, decimals) - Round to N decimal places
71
109
  *
72
110
  * ===============================================================================
73
111
  */
@@ -845,7 +883,7 @@ declare function calculateSwapInAmount(targetReceive: number, poolReserveOut: nu
845
883
  *
846
884
  * @param {number} incrementPercent - Grid increment percentage
847
885
  * @param {number} targetSpreadPercent - Target spread percentage
848
- * @param {Object} GRID_LIMITS - Grid limits constants (optional, uses defaults)
886
+ * @param {Object} [gridLimits] - Grid limits constants (optional, uses defaults)
849
887
  * @returns {number} Number of gap slots
850
888
  */
851
889
  declare function calculateGapSlots(incrementPercent: number | undefined, targetSpreadPercent: number | undefined, gridLimits?: GridLimitsLike): number;
@@ -4,56 +4,93 @@
4
4
  * Pure numeric calculations, blockchain conversions, fee math, and fund allocation.
5
5
  *
6
6
  * ===============================================================================
7
- * TABLE OF CONTENTS (44 exported functions)
7
+ * TABLE OF CONTENTS (78 exports)
8
8
  * ===============================================================================
9
9
  *
10
- * SECTION 1: PARSING & VALIDATION (6 functions)
10
+ * SECTION 1: GENESIS LADDER & RAIL GEOMETRY (28 items)
11
+ * - GridGenesis - Genesis ladder type: start price, increment, gap slots,
12
+ * price levels and their hash
13
+ * - priceLevelsForGenesis(genesis) - Extract the frozen price ladder from a genesis
14
+ * - buildGenesisFromPriceLevels(levels, config) - Build a genesis from precomputed levels
15
+ * - derivePriceLevels(startPrice, increment, minPrice, maxPrice) - Derive the
16
+ * geometric price ladder (the "rail") from a live config
17
+ * - hashPriceLevels(levels) - Deterministic hash of a price ladder
18
+ * - priceForSlot(idx, genesis) - Authoritative price for a slot index
19
+ * - slotIndexForPrice(price, genesis) - Resolve a price to its slot index
20
+ * - slotIdForPrice(price, genesis) - Resolve a price to its "slot-N" id
21
+ * - assertSlotPriceInvariant(...) - Reject a slot whose price disagrees with its index
22
+ * - priceSlotEqual(...) - Compare slot/price pairs under the genesis invariant
23
+ * - sameGridLevel(a, b) - Same ladder level, resolving each price against its genesis
24
+ * - sameGridPrice(a, b) - Same genesis-derived ladder level by precision
25
+ * - pricesOnSameLevel(a, b, ...) - Same order-book price LEVEL under precision
26
+ * - isChainPriceOutOfGrid(price, genesis, ...) - Whether a chain price is off the rail
27
+ * - getBtsSide(assets) - Which side of the pair holds BTS
28
+ * - getSellStartIdx(boundaryIdx, gapSlots) - Sell start index from boundary + gap
29
+ * - calculateGapSlots(incrementPercent, targetSpreadPercent) - Gap-slot count
30
+ * - resolveGapSlots(manager) - Configured gap-slot count for a manager
31
+ * - resolveGapBand(manager) - Gap-band geometry { start, end, gapSlots }
32
+ * - countGapBandSpread(manager) - Count SPREAD slots strictly inside the gap band
33
+ * - isSlotInRail(...) - Geometric rail-membership test for a slot
34
+ * - isSlotIndexInGapBand(idx, ...) - Whether a slot index sits inside the gap band
35
+ * - isEvacuationRotationAllowed(...) - Whether a gap-evacuation rotation is geometrically valid
36
+ * - isEvacuationSizeStillValid(...) - Re-proof a stamped evacuation size against live geometry
37
+ * - validateBoundaryCommit(...) - Validate a proposed boundary commit against geometry
38
+ * - validatePersistedBoundary(...) - Validate a boundary restored from disk
39
+ * - isTransientInBandRejection(reason) - Whether a persisted-boundary rejection is transient
40
+ * - BOUNDARY_REJECT_PLACED_IN_BAND - Rejection reason: target slot holds an in-band order
41
+ *
42
+ * SECTION 2: PARSING & VALIDATION (10 functions)
11
43
  * - isExplicitZeroAllocation(value) - Check if value is explicitly zero
12
44
  * - isPercentageString(v) - Check if value is percentage string
45
+ * - isPositiveNumber(value) - Check if value is a positive number
46
+ * - isPositiveNumberOrPercent(value) - Positive number or positive percentage string
47
+ * - isPositiveInt(value) - Check if value is a positive integer
13
48
  * - parsePercentageString(v) - Parse percentage string to decimal
49
+ * - toDecimal(value) - Convert number/percentage/numeric string to a decimal
14
50
  * - parseRelativeMultiplier(value) - Parse "3x" multiplier syntax to number
15
51
  * - resolveRelativePrice(value, startPrice, mode) - Resolve relative price values
16
52
  * - validateGridPriceBounds(min, max, center) - Reject bounds not bracketing center
17
53
  *
18
- * SECTION 2: FUND CALCULATIONS (4 functions)
54
+ * SECTION 3: FUND CALCULATIONS (8 functions)
19
55
  * - computeChainFundTotals(accountTotals, committedChain) - Compute total funds
20
56
  * - calculateAvailableFundsValue(side, accountTotals, funds, ...) - Calculate available funds
57
+ * - adjustBudgetForBtsFees(budget, btsFeeData, ...) - Reserve BTS fees from a side budget
58
+ * - getGridBestPrices(manager) - Best (highest) buy and best (lowest) sell price
21
59
  * - calculateSpreadFromOrders(activeBuys, activeSells) - Calculate spread percentage
22
60
  * - resolveConfigValue(value, total) - Resolve percentage or absolute config value
61
+ * - resolveConfigValueWithRegistry(value, total, registry) - Config value incl. shared-account funds
62
+ * - hasValidAccountTotals(accountTotals, checkFree) - Validate account totals structure
23
63
  *
24
- * SECTION 3: BLOCKCHAIN CONVERSIONS (5 functions)
64
+ * SECTION 4: BLOCKCHAIN CONVERSIONS (6 functions)
25
65
  * - blockchainToFloat(intValue, precision) - Convert blockchain int to float
26
66
  * - floatToBlockchainInt(floatValue, precision) - Convert float to blockchain int
67
+ * - floorToBlockchainInt(floatValue, precision) - Convert float to int by flooring
27
68
  * - quantizeFloat(value, precision) - Round float to blockchain precision
28
69
  * - normalizeInt(value, precision) - Normalize int within precision bounds
29
- * - hasValidAccountTotals(accountTotals, checkFree) - Validate account totals structure
70
+ * - quantumForPrecision(precision) - Smallest representable unit for a precision
30
71
  *
31
- * SECTION 4: PRECISION & FORMATTING UTILITIES (8 functions)
32
- * - roundTo(value, factor) - Round to a factor
33
- * - fixedTo(value, decimals) - Format to fixed decimal string
34
- * - roundToDecimals(value, decimals) - Round to N decimal places
72
+ * SECTION 5: PRECISION UTILITIES (4 functions)
35
73
  * - getPrecision(assets, orderType) - Get precision for order type
36
74
  * - getPrecisionByOrderType(assets, orderType) - Alias for getPrecision
37
- * - getPrecisionForSide(assets, side) - Get precision by side (buy/sell)
38
75
  * - getPrecisionsForManager(manager) - Get both asset precisions
39
76
  * - getPrecisionSlack(precision) - Calculate tolerance for precision
40
77
  *
41
- * SECTION 5: ORDER SIZE VALIDATION (7 functions)
78
+ * SECTION 6: ORDER SIZE VALIDATION (8 functions)
42
79
  * - calculatePriceTolerance(price, size, type, assets) - Calculate price match tolerance
80
+ * - findCrossedOrder(...) - Find an opposite-side order a placement would CROSS
43
81
  * - validateOrderAmountsWithinLimits(amountToSell, minToReceive) - Validate order limits
44
- * - getMinOrderSize(assets, type) - Get minimum order size for type
82
+ * - getMinOrderSize(orderType, assets, factor) - Get minimum order size
45
83
  * - getDustThresholdFactor() - Get dust threshold multiplier
46
84
  * - getSingleDustThreshold(idealSize, dustThresholdPercent) - Get single dust threshold
47
85
  * - getDoubleDustThreshold(idealSize, dustThresholdPercent) - Get double dust threshold
48
- * - getMinOrderSize(orderType, assets, factor) - Get minimum order size
49
86
  * - validateOrderSize(manager, size, type, context) - Validate order size against minimums
50
87
  *
51
- * SECTION 6: FEE CALCULATIONS (2 functions + 2 internal)
88
+ * SECTION 7: FEE CALCULATIONS (3 functions)
52
89
  * - getAssetFees(assetSymbol, assetAmount, isMaker) - Get fee info for asset
90
+ * - getAssetFeesSafe(assetSymbol, assetAmount, isMaker) - Fee info without throwing
53
91
  * - _setFeeCache(cache) - Set internal fee cache (internal)
54
- * - _getFeeCache() - Get internal fee cache (internal)
55
92
  *
56
- * SECTION 7: FUND ALLOCATION (6 functions)
93
+ * SECTION 8: FUND ALLOCATION (6 functions)
57
94
  * - allocateFundsByWeights(available, targetCount) - Allocate funds by weight
58
95
  * - cloneWeightDistribution(weightDistribution, base) - Clone weight distribution safely
59
96
  * - calculateOrderSizes(manager, orderType) - Calculate order sizes for placement
@@ -61,13 +98,14 @@
61
98
  * - calculateGridSideDivergenceMetric(manager, orderType, threshold) - Calculate divergence
62
99
  * - clamp(value, min, max) - Clamp a value between min and max bounds
63
100
  *
64
- * SECTION 8: FEE DEDUCTION (3 functions)
101
+ * SECTION 9: FEE DEDUCTION (2 functions)
65
102
  * - calculateOrderCreationFees(count, btsFeeData) - Calculate total creation fees
66
- * - deductOrderFeesFromFunds(available, count, btsFeeData, btsSide) - Deduct fees from funds
67
103
  * - calculateSwapInAmount(targetReceive, poolReserveOut, poolReserveIn) - AMM swap math
68
104
  *
69
- * SECTION 9: GRID UTILITIES (1 function)
70
- * - calculateGapSlots(incrementPercent, targetSpreadPercent) - Calculate gap slots count
105
+ * SECTION 10: FORMATTING (3 functions)
106
+ * - roundTo(value, factor) - Round to a factor
107
+ * - fixedTo(value, decimals) - Format to fixed decimal string
108
+ * - roundToDecimals(value, decimals) - Round to N decimal places
71
109
  *
72
110
  * ===============================================================================
73
111
  */
@@ -1378,7 +1416,7 @@ function calculateSwapInAmount(targetReceive, poolReserveOut, poolReserveIn) {
1378
1416
  *
1379
1417
  * @param {number} incrementPercent - Grid increment percentage
1380
1418
  * @param {number} targetSpreadPercent - Target spread percentage
1381
- * @param {Object} GRID_LIMITS - Grid limits constants (optional, uses defaults)
1419
+ * @param {Object} [gridLimits] - Grid limits constants (optional, uses defaults)
1382
1420
  * @returns {number} Number of gap slots
1383
1421
  */
1384
1422
  function calculateGapSlots(incrementPercent, targetSpreadPercent, gridLimits = {}) {
@@ -5,68 +5,112 @@
5
5
  * Includes grid indexing, order comparison, delta building, and strategy calculations.
6
6
  *
7
7
  * ===============================================================================
8
- * TABLE OF CONTENTS (35 exported functions)
8
+ * TABLE OF CONTENTS (76 exported functions)
9
9
  * ===============================================================================
10
10
  *
11
- * SECTION 1: CHAIN ORDER MATCHING & RECONCILIATION (5 functions)
11
+ * SECTION 1: CHAIN ORDER MATCHING & RECONCILIATION (7 functions)
12
12
  * - parseChainOrder(chainOrder, assets) - Parse blockchain order to grid format
13
13
  * - applyChainSizeToGridOrder(manager, gridOrder, chainSize) - Apply chain size to grid
14
14
  * - correctOrderPriceOnChain(manager, correctionInfo, ...) - Correct order price on chain
15
15
  * - correctAllPriceMismatches(manager, accountName, ...) - Correct all price mismatches
16
- *
17
- * SECTION 2: ORDER CONSTRUCTION (3 functions)
16
+ * - _validatePriceCorrectionEntry(...) - Drain-time staleness check for a queued correction
17
+ * - _stampCorrectionProvenance(...) - Stamp queue provenance on a correction entry
18
+ * - findLiveOrderOwnerByChainId(...) - Find the live grid slot that owns a chain order
19
+ *
20
+ * SECTION 2: CROSSING-PLACEMENT GUARDS (8 functions)
21
+ * - chainOrderMatchesSlot(...) - Exact chain-order/grid-slot match
22
+ * - chainOrderMatchesSlotWithTolerance(...) - Match within price tolerance
23
+ * - crossingCandidateChainId(order) - Chain id of a crossing-check candidate
24
+ * - isCrossingCheckCandidate(order) - Predicate for crossing-placement guards
25
+ * - buildCrossingCheckCandidates(...) - Candidate set for crossing-placement checks
26
+ * - chainOrderUnchangedFromCache(...) - Chain order still matches cached pre-update state
27
+ * - detectCrossedBookPlan(...) - Pre-broadcast crossed-book assert
28
+ * - collectKnownOnChainOrderIds(...) - On-chain ids master must converge against
29
+ *
30
+ * SECTION 3: ORDER CONSTRUCTION (5 functions)
18
31
  * - buildCreateOrderArgs(order, assetA, assetB) - Build create order arguments
19
32
  * - getOrderTypeFromUpdatedFlags(buyUpdated, sellUpdated) - Get type from update flags
20
33
  * - resolveConfiguredPriceBound(value, fallback, startPrice, mode) - Resolve price bounds
21
34
  * - buildFillKey(fillOrParts) - Build a stable fill dedupe key
22
35
  * - buildCreateOpFingerprint(params) - Build fingerprint for create operations
23
36
  *
24
- * SECTION 3: STATE TRANSITIONS (2 functions)
37
+ * SECTION 4: STATE TRANSITIONS & PLACEHOLDERS (6 functions)
25
38
  * - virtualizeOrder(order) - Convert order to VIRTUAL state
26
39
  * - convertToSpreadPlaceholder(order) - Convert order to SPREAD placeholder
27
- *
28
- * SECTION 4: FILTERING & COUNTING (5 functions)
40
+ * - toRailHolePlaceholder(order) - Convert to a rail-typed hole placeholder
41
+ * - geometryTypeForSlotIndex(...) - BUY/SELL type for a slot index
42
+ * - resolveSpreadOrderSide(order) - Resolve the real side of a SPREAD slot
43
+ * - resolveOnChainRetypeType(...) - Type to keep when a live-order slot would retype
44
+ *
45
+ * SECTION 5: GAP EVACUATION (3 functions)
46
+ * - detectGapEvacuationCandidates(...) - Detect gap-evacuation candidates by geometry
47
+ * - updateGapEvacuationStreaks(...) - Tick per-slot gap-evacuation streak counter
48
+ * - collectRefillSlotIds(...) - Refill-slot wire for the COW boundary hold
49
+ *
50
+ * SECTION 6: FILTERING & DRIFT DIAGNOSTICS (12 functions)
51
+ * - parseSlotIndex(id) - Parse "slot-N" to its rail index
29
52
  * - filterOrdersByType(orders, orderType) - Filter orders by type
30
-
31
53
  * - buildOutsideInPairGroups(items, accessors) - Outside->center pair grouping
32
54
  * - extractBatchOperationResults(result) - Extract operation_results from chain batch result
33
55
  * - formatUnmatchedChainOrder(order) - Format structural drift diagnostics
34
- *
35
- * SECTION 5: STATE PREDICATES (7 functions)
56
+ * - isNonBlockingUnmatchedOrder(...) - Deliberate hold that must not read as drift
57
+ * - isStrandedHoldOrder(...) - Stranded hold detection
58
+ * - isOrderGoneErrorMessage(err) - Detect "chain order does not exist"
59
+ * - recordDuplicateOrphanDetection(orderId) - Record a duplicate-orphan detection
60
+ * - clearDuplicateOrphanDetection(orderId) - Clear the detection counter
61
+ * - duplicateOrphanLogInfo(...) - Log level + re-detection info for duplicate orphans
62
+ * - _filterUnmatchedChainOrders(...) - Drop a satisfied id from the unmatched list
63
+ *
64
+ * SECTION 7: STATE PREDICATES (8 functions)
36
65
  * - isOrderOnChain(order) - Check if order is ACTIVE or PARTIAL
37
66
  * - isOrderVirtual(order) - Check if order is VIRTUAL
38
67
  * - hasOnChainId(order) - Check if order has blockchain orderId
39
68
  * - isOrderPlaced(order) - Check if order is placed on chain
40
69
  * - isPhantomOrder(order) - Check if order is phantom (ACTIVE without orderId)
41
70
  * - isSlotAvailable(order) - Check if slot is available for placement
71
+ * - isEmptyGridSlot(order) - Empty reusable placeholder test
42
72
  * - isOrderHealthy(order, context) - Comprehensive order health check
43
73
  *
44
- * SECTION 6: SIZE VALIDATION (2 functions)
74
+ * SECTION 8: SIZE VALIDATION (2 functions)
45
75
  * - checkSizeThreshold(size, threshold) - Check if size exceeds threshold
46
76
  * - checkSizesBeforeMinimum(sizes, minSize) - Check sizes against minimum
47
77
  *
48
- * SECTION 7: GRID BOUNDARY & ROLES (3 functions)
78
+ * SECTION 9: GRID BOUNDARY & ROLES (5 functions)
49
79
  * - calculateIdealBoundary(allSlots, startPrice, gapSlots) - Calculate ideal boundary
50
80
  * - assignGridRoles(allSlots, boundaryIdx, gapSlots, ...) - Assign BUY/SELL roles
51
81
  * - shouldFlagOutOfSpread(order, startPrice, configSpread) - Check if order is out of spread
82
+ * - deriveTargetBoundary(...) - Target boundary for a rebalance plan
83
+ * - isShiftEligibleFill(...) - Whether a fill may drive boundary shift/rotation
52
84
  *
53
- * SECTION 8: GRID INDEXING (2 functions)
85
+ * SECTION 10: GRID INDEXING (2 functions)
54
86
  * - buildIndexes(grid) - Build complete index set from grid
55
87
  * - validateIndexes(grid, indexes) - Validate index consistency
56
88
  *
57
- * SECTION 9: ORDER COMPARISON & DELTA (3 functions)
89
+ * SECTION 11: ORDER COMPARISON & DELTA (2 functions)
58
90
  * - ordersEqual(a, b) - Compare two orders for equality
59
91
  * - buildDelta(masterGrid, workingGrid) - Build delta actions between grids
60
- * - getOrderSize(order) - Extract order size with fallback
61
92
  *
62
- * SECTION 10: STRATEGY CALCULATIONS (7 functions)
93
+ * SECTION 12: STRATEGY / EDGE / BUDGET (11 functions)
63
94
  * - resolveEdgeCount(config, side) - Clamped per-side edge count (>=0 int, 0 disables)
64
95
  * - resolveEdgeOrders(config) - Total edge orders buy+sell (fee/count totals)
65
- * - resolveLiveEdgeAnchorPrice(manager, side) - Live-grid edge anchor (genesis ladder extreme; null when no usable ladder)
96
+ * - selectEdgeSlots(sortedAsc, count, excludeIds, edge, anchorPrice?) - Shared position picker (both edges anchor toward their bound)
97
+ * - getCoreOrdersTotal(config) - Total target order count across both sides
98
+ * - getSideBudget(...) - Side budget after BTS fee deduction
99
+ * - calculateBudgetedSizes(...) - Sizes for all slots on a side using weighted distribution
100
+ * - edgeOrderIdSet(allSlots, config, orderType, anchorPrice?, excludeIds?) - Edge order id set (config count; shares the picker ordering; excludeIds carries the window exclusion)
101
+ * - liveWindowIdSet(...) - Window member ids for one side from the live manager
66
102
  * - resolveEdgeAnchorPrice(config, side) - Config-bound anchor fallback (buy→minPrice, sell→maxPrice; null when unresolvable)
103
+ * - resolveLiveEdgeAnchorPrice(manager, side) - Live-grid edge anchor (genesis ladder extreme; null when no usable ladder)
67
104
  * - compareEdge(a, b, edge, anchorPrice) - Shared anchored edge comparator (single ordering source)
68
- * - edgeOrderIdSet(allSlots, config, orderType, anchorPrice?, excludeIds?) - Edge order id set (config count; shares the picker ordering; excludeIds carries the window exclusion)
69
- * - selectEdgeSlots(sortedAsc, count, excludeIds, edge, anchorPrice?) - Shared position picker (both edges anchor toward their bound)
105
+ *
106
+ * SECTION 13: GRID PRICE INVARIANT (2 functions)
107
+ * - checkGridPriceInvariant(...) - The price emitted for a slot must equal its genesis price
108
+ * - reportGridPriceInvariant(...) - Report one GRID-PRICE-INVARIANT check
109
+ *
110
+ * SECTION 14: PERSISTED CRAWL & PLACEMENT GRACE (3 functions)
111
+ * - consumePendingFillCrawls(...) - Apply recorded-but-uncommitted fill crawls to the boundary
112
+ * - recordOrderPlacement(...) - Record a fresh on-chain placement timestamp
113
+ * - isFreshlyPlacedOrder(...) - Chain order placed within the surplus-cancel grace
70
114
  *
71
115
  * ===============================================================================
72
116
  */
@@ -732,7 +776,7 @@ declare function isOrderOnChain(order: SlotLike | null | undefined): boolean;
732
776
  * @param {Object} slot - The slot being retyped
733
777
  * @param {number} idx - Slot index
734
778
  * @param {number} buyEndIdx - Boundary index (last BUY slot)
735
- * @param {Object} ORDER_TYPES - ORDER_TYPES constants
779
+ * @param {Object} orderTypes - ORDER_TYPES constants
736
780
  * @returns {string} Type to keep for the on-chain slot
737
781
  */
738
782
  declare function resolveOnChainRetypeType(slot: SlotLike, idx: number, buyEndIdx: number, orderTypes: {
@@ -5,68 +5,112 @@
5
5
  * Includes grid indexing, order comparison, delta building, and strategy calculations.
6
6
  *
7
7
  * ===============================================================================
8
- * TABLE OF CONTENTS (35 exported functions)
8
+ * TABLE OF CONTENTS (76 exported functions)
9
9
  * ===============================================================================
10
10
  *
11
- * SECTION 1: CHAIN ORDER MATCHING & RECONCILIATION (5 functions)
11
+ * SECTION 1: CHAIN ORDER MATCHING & RECONCILIATION (7 functions)
12
12
  * - parseChainOrder(chainOrder, assets) - Parse blockchain order to grid format
13
13
  * - applyChainSizeToGridOrder(manager, gridOrder, chainSize) - Apply chain size to grid
14
14
  * - correctOrderPriceOnChain(manager, correctionInfo, ...) - Correct order price on chain
15
15
  * - correctAllPriceMismatches(manager, accountName, ...) - Correct all price mismatches
16
- *
17
- * SECTION 2: ORDER CONSTRUCTION (3 functions)
16
+ * - _validatePriceCorrectionEntry(...) - Drain-time staleness check for a queued correction
17
+ * - _stampCorrectionProvenance(...) - Stamp queue provenance on a correction entry
18
+ * - findLiveOrderOwnerByChainId(...) - Find the live grid slot that owns a chain order
19
+ *
20
+ * SECTION 2: CROSSING-PLACEMENT GUARDS (8 functions)
21
+ * - chainOrderMatchesSlot(...) - Exact chain-order/grid-slot match
22
+ * - chainOrderMatchesSlotWithTolerance(...) - Match within price tolerance
23
+ * - crossingCandidateChainId(order) - Chain id of a crossing-check candidate
24
+ * - isCrossingCheckCandidate(order) - Predicate for crossing-placement guards
25
+ * - buildCrossingCheckCandidates(...) - Candidate set for crossing-placement checks
26
+ * - chainOrderUnchangedFromCache(...) - Chain order still matches cached pre-update state
27
+ * - detectCrossedBookPlan(...) - Pre-broadcast crossed-book assert
28
+ * - collectKnownOnChainOrderIds(...) - On-chain ids master must converge against
29
+ *
30
+ * SECTION 3: ORDER CONSTRUCTION (5 functions)
18
31
  * - buildCreateOrderArgs(order, assetA, assetB) - Build create order arguments
19
32
  * - getOrderTypeFromUpdatedFlags(buyUpdated, sellUpdated) - Get type from update flags
20
33
  * - resolveConfiguredPriceBound(value, fallback, startPrice, mode) - Resolve price bounds
21
34
  * - buildFillKey(fillOrParts) - Build a stable fill dedupe key
22
35
  * - buildCreateOpFingerprint(params) - Build fingerprint for create operations
23
36
  *
24
- * SECTION 3: STATE TRANSITIONS (2 functions)
37
+ * SECTION 4: STATE TRANSITIONS & PLACEHOLDERS (6 functions)
25
38
  * - virtualizeOrder(order) - Convert order to VIRTUAL state
26
39
  * - convertToSpreadPlaceholder(order) - Convert order to SPREAD placeholder
27
- *
28
- * SECTION 4: FILTERING & COUNTING (5 functions)
40
+ * - toRailHolePlaceholder(order) - Convert to a rail-typed hole placeholder
41
+ * - geometryTypeForSlotIndex(...) - BUY/SELL type for a slot index
42
+ * - resolveSpreadOrderSide(order) - Resolve the real side of a SPREAD slot
43
+ * - resolveOnChainRetypeType(...) - Type to keep when a live-order slot would retype
44
+ *
45
+ * SECTION 5: GAP EVACUATION (3 functions)
46
+ * - detectGapEvacuationCandidates(...) - Detect gap-evacuation candidates by geometry
47
+ * - updateGapEvacuationStreaks(...) - Tick per-slot gap-evacuation streak counter
48
+ * - collectRefillSlotIds(...) - Refill-slot wire for the COW boundary hold
49
+ *
50
+ * SECTION 6: FILTERING & DRIFT DIAGNOSTICS (12 functions)
51
+ * - parseSlotIndex(id) - Parse "slot-N" to its rail index
29
52
  * - filterOrdersByType(orders, orderType) - Filter orders by type
30
-
31
53
  * - buildOutsideInPairGroups(items, accessors) - Outside->center pair grouping
32
54
  * - extractBatchOperationResults(result) - Extract operation_results from chain batch result
33
55
  * - formatUnmatchedChainOrder(order) - Format structural drift diagnostics
34
- *
35
- * SECTION 5: STATE PREDICATES (7 functions)
56
+ * - isNonBlockingUnmatchedOrder(...) - Deliberate hold that must not read as drift
57
+ * - isStrandedHoldOrder(...) - Stranded hold detection
58
+ * - isOrderGoneErrorMessage(err) - Detect "chain order does not exist"
59
+ * - recordDuplicateOrphanDetection(orderId) - Record a duplicate-orphan detection
60
+ * - clearDuplicateOrphanDetection(orderId) - Clear the detection counter
61
+ * - duplicateOrphanLogInfo(...) - Log level + re-detection info for duplicate orphans
62
+ * - _filterUnmatchedChainOrders(...) - Drop a satisfied id from the unmatched list
63
+ *
64
+ * SECTION 7: STATE PREDICATES (8 functions)
36
65
  * - isOrderOnChain(order) - Check if order is ACTIVE or PARTIAL
37
66
  * - isOrderVirtual(order) - Check if order is VIRTUAL
38
67
  * - hasOnChainId(order) - Check if order has blockchain orderId
39
68
  * - isOrderPlaced(order) - Check if order is placed on chain
40
69
  * - isPhantomOrder(order) - Check if order is phantom (ACTIVE without orderId)
41
70
  * - isSlotAvailable(order) - Check if slot is available for placement
71
+ * - isEmptyGridSlot(order) - Empty reusable placeholder test
42
72
  * - isOrderHealthy(order, context) - Comprehensive order health check
43
73
  *
44
- * SECTION 6: SIZE VALIDATION (2 functions)
74
+ * SECTION 8: SIZE VALIDATION (2 functions)
45
75
  * - checkSizeThreshold(size, threshold) - Check if size exceeds threshold
46
76
  * - checkSizesBeforeMinimum(sizes, minSize) - Check sizes against minimum
47
77
  *
48
- * SECTION 7: GRID BOUNDARY & ROLES (3 functions)
78
+ * SECTION 9: GRID BOUNDARY & ROLES (5 functions)
49
79
  * - calculateIdealBoundary(allSlots, startPrice, gapSlots) - Calculate ideal boundary
50
80
  * - assignGridRoles(allSlots, boundaryIdx, gapSlots, ...) - Assign BUY/SELL roles
51
81
  * - shouldFlagOutOfSpread(order, startPrice, configSpread) - Check if order is out of spread
82
+ * - deriveTargetBoundary(...) - Target boundary for a rebalance plan
83
+ * - isShiftEligibleFill(...) - Whether a fill may drive boundary shift/rotation
52
84
  *
53
- * SECTION 8: GRID INDEXING (2 functions)
85
+ * SECTION 10: GRID INDEXING (2 functions)
54
86
  * - buildIndexes(grid) - Build complete index set from grid
55
87
  * - validateIndexes(grid, indexes) - Validate index consistency
56
88
  *
57
- * SECTION 9: ORDER COMPARISON & DELTA (3 functions)
89
+ * SECTION 11: ORDER COMPARISON & DELTA (2 functions)
58
90
  * - ordersEqual(a, b) - Compare two orders for equality
59
91
  * - buildDelta(masterGrid, workingGrid) - Build delta actions between grids
60
- * - getOrderSize(order) - Extract order size with fallback
61
92
  *
62
- * SECTION 10: STRATEGY CALCULATIONS (7 functions)
93
+ * SECTION 12: STRATEGY / EDGE / BUDGET (11 functions)
63
94
  * - resolveEdgeCount(config, side) - Clamped per-side edge count (>=0 int, 0 disables)
64
95
  * - resolveEdgeOrders(config) - Total edge orders buy+sell (fee/count totals)
65
- * - resolveLiveEdgeAnchorPrice(manager, side) - Live-grid edge anchor (genesis ladder extreme; null when no usable ladder)
96
+ * - selectEdgeSlots(sortedAsc, count, excludeIds, edge, anchorPrice?) - Shared position picker (both edges anchor toward their bound)
97
+ * - getCoreOrdersTotal(config) - Total target order count across both sides
98
+ * - getSideBudget(...) - Side budget after BTS fee deduction
99
+ * - calculateBudgetedSizes(...) - Sizes for all slots on a side using weighted distribution
100
+ * - edgeOrderIdSet(allSlots, config, orderType, anchorPrice?, excludeIds?) - Edge order id set (config count; shares the picker ordering; excludeIds carries the window exclusion)
101
+ * - liveWindowIdSet(...) - Window member ids for one side from the live manager
66
102
  * - resolveEdgeAnchorPrice(config, side) - Config-bound anchor fallback (buy→minPrice, sell→maxPrice; null when unresolvable)
103
+ * - resolveLiveEdgeAnchorPrice(manager, side) - Live-grid edge anchor (genesis ladder extreme; null when no usable ladder)
67
104
  * - compareEdge(a, b, edge, anchorPrice) - Shared anchored edge comparator (single ordering source)
68
- * - edgeOrderIdSet(allSlots, config, orderType, anchorPrice?, excludeIds?) - Edge order id set (config count; shares the picker ordering; excludeIds carries the window exclusion)
69
- * - selectEdgeSlots(sortedAsc, count, excludeIds, edge, anchorPrice?) - Shared position picker (both edges anchor toward their bound)
105
+ *
106
+ * SECTION 13: GRID PRICE INVARIANT (2 functions)
107
+ * - checkGridPriceInvariant(...) - The price emitted for a slot must equal its genesis price
108
+ * - reportGridPriceInvariant(...) - Report one GRID-PRICE-INVARIANT check
109
+ *
110
+ * SECTION 14: PERSISTED CRAWL & PLACEMENT GRACE (3 functions)
111
+ * - consumePendingFillCrawls(...) - Apply recorded-but-uncommitted fill crawls to the boundary
112
+ * - recordOrderPlacement(...) - Record a fresh on-chain placement timestamp
113
+ * - isFreshlyPlacedOrder(...) - Chain order placed within the surplus-cancel grace
70
114
  *
71
115
  * ===============================================================================
72
116
  */
@@ -1835,7 +1879,7 @@ function isOrderOnChain(order) {
1835
1879
  * @param {Object} slot - The slot being retyped
1836
1880
  * @param {number} idx - Slot index
1837
1881
  * @param {number} buyEndIdx - Boundary index (last BUY slot)
1838
- * @param {Object} ORDER_TYPES - ORDER_TYPES constants
1882
+ * @param {Object} orderTypes - ORDER_TYPES constants
1839
1883
  * @returns {string} Type to keep for the on-chain slot
1840
1884
  */
1841
1885
  function resolveOnChainRetypeType(slot, idx, buyEndIdx, orderTypes) {