@clonegod/ttd-base-common 1.0.26 → 1.1.2

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 (144) hide show
  1. package/dist/appconfig/BaseQuoteAppConfig.d.ts +10 -0
  2. package/dist/appconfig/BaseQuoteAppConfig.js +36 -0
  3. package/dist/appconfig/BaseTradeAppConfig.d.ts +7 -0
  4. package/dist/appconfig/BaseTradeAppConfig.js +13 -0
  5. package/dist/appconfig/base_dex_env_args.d.ts +5 -0
  6. package/dist/appconfig/base_dex_env_args.js +68 -0
  7. package/dist/appconfig/base_env_args.d.ts +82 -0
  8. package/dist/appconfig/base_env_args.js +91 -0
  9. package/dist/appconfig/ensure_core_env.d.ts +1 -0
  10. package/dist/appconfig/ensure_core_env.js +18 -0
  11. package/dist/appconfig/index.d.ts +5 -0
  12. package/dist/appconfig/index.js +21 -0
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.js +2 -2
  15. package/dist/quote/depth/amm_depth_calculator.d.ts +19 -0
  16. package/dist/quote/depth/amm_depth_calculator.js +55 -0
  17. package/dist/quote/depth/clmm_depth_calculator.d.ts +28 -0
  18. package/dist/quote/depth/clmm_depth_calculator.js +176 -0
  19. package/dist/quote/depth/index.d.ts +51 -0
  20. package/dist/quote/depth/index.js +264 -0
  21. package/dist/quote/depth/tick_liquidity_snapshot.d.ts +58 -0
  22. package/dist/quote/depth/tick_liquidity_snapshot.js +143 -0
  23. package/dist/quote/event/index.d.ts +1 -0
  24. package/dist/quote/event/index.js +1 -0
  25. package/dist/quote/event/pool_event_listener.d.ts +5 -3
  26. package/dist/quote/event/pool_event_listener.js +128 -150
  27. package/dist/quote/event/swap_debouncer.d.ts +22 -0
  28. package/dist/quote/event/swap_debouncer.js +80 -0
  29. package/dist/quote/get_base_token_price.d.ts +6 -0
  30. package/dist/quote/get_base_token_price.js +90 -0
  31. package/dist/quote/index.d.ts +7 -0
  32. package/dist/quote/index.js +7 -0
  33. package/dist/quote/preload_token_prices.d.ts +2 -0
  34. package/dist/quote/preload_token_prices.js +37 -0
  35. package/dist/quote/price_feed_handler.d.ts +15 -0
  36. package/dist/quote/price_feed_handler.js +56 -0
  37. package/dist/quote/pricing/fee_helpers.d.ts +13 -0
  38. package/dist/quote/pricing/fee_helpers.js +68 -0
  39. package/dist/quote/pricing/index.d.ts +3 -1
  40. package/dist/quote/pricing/index.js +3 -1
  41. package/dist/quote/pricing/pool_state_initializer.d.ts +12 -0
  42. package/dist/quote/pricing/pool_state_initializer.js +191 -0
  43. package/dist/quote/pricing/sdk_token_factory.d.ts +2 -0
  44. package/dist/quote/pricing/sdk_token_factory.js +21 -0
  45. package/dist/quote/quote_amount.d.ts +4 -0
  46. package/dist/quote/quote_amount.js +24 -0
  47. package/dist/quote/tick/cached_tick_data_provider.d.ts +12 -0
  48. package/dist/quote/tick/cached_tick_data_provider.js +45 -0
  49. package/dist/quote/tick/clmm_tick_cache.d.ts +42 -0
  50. package/dist/quote/tick/clmm_tick_cache.js +236 -0
  51. package/dist/quote/tick/index.d.ts +4 -0
  52. package/dist/{ws → quote/tick}/index.js +4 -2
  53. package/dist/quote/tick/state_view_tick_loader.d.ts +17 -0
  54. package/dist/quote/tick/state_view_tick_loader.js +136 -0
  55. package/dist/quote/tick/tick_lens_loaders.d.ts +24 -0
  56. package/dist/quote/tick/tick_lens_loaders.js +158 -0
  57. package/dist/quote/verify/index.d.ts +2 -0
  58. package/dist/quote/verify/index.js +5 -0
  59. package/dist/quote/verify/quote_price_verify.d.ts +30 -0
  60. package/dist/quote/verify/quote_price_verify.js +240 -0
  61. package/dist/redis/redis_client.d.ts +3 -2
  62. package/dist/redis/redis_client.js +86 -116
  63. package/dist/send-tx/constants.d.ts +2 -0
  64. package/dist/send-tx/constants.js +6 -0
  65. package/dist/send-tx/index.d.ts +2 -0
  66. package/dist/{config → send-tx}/index.js +2 -1
  67. package/dist/send-tx/types.d.ts +4 -0
  68. package/dist/send-tx/types.js +2 -0
  69. package/dist/trade/abstract_dex_trade.d.ts +43 -21
  70. package/dist/trade/abstract_dex_trade.js +347 -133
  71. package/dist/trade/caller_manager.d.ts +31 -0
  72. package/dist/trade/caller_manager.js +202 -0
  73. package/dist/trade/check/abstract_tx_result_checker.d.ts +28 -0
  74. package/dist/trade/check/abstract_tx_result_checker.js +192 -0
  75. package/dist/trade/check/index.d.ts +1 -1
  76. package/dist/trade/check/index.js +1 -1
  77. package/dist/trade/index.d.ts +2 -2
  78. package/dist/trade/index.js +2 -2
  79. package/dist/trade/parse/base_parser.d.ts +1 -2
  80. package/dist/trade/parse/base_parser.js +36 -36
  81. package/dist/trade/trade_trace.d.ts +17 -0
  82. package/dist/trade/trade_trace.js +65 -0
  83. package/dist/types/config_types.d.ts +3 -3
  84. package/dist/types/event_types.d.ts +3 -3
  85. package/dist/types/pool_state.d.ts +140 -13
  86. package/dist/utils/ethers_compat.d.ts +13 -0
  87. package/dist/utils/ethers_compat.js +18 -0
  88. package/dist/utils/fast_signer.d.ts +1 -0
  89. package/dist/utils/fast_signer.js +87 -0
  90. package/dist/utils/gas_helper.d.ts +2 -2
  91. package/dist/utils/gas_helper.js +48 -60
  92. package/dist/utils/index.d.ts +5 -2
  93. package/dist/utils/index.js +6 -2
  94. package/dist/utils/pool_filter.d.ts +8 -0
  95. package/dist/utils/pool_filter.js +38 -0
  96. package/dist/utils/trade_direction.d.ts +14 -0
  97. package/dist/utils/trade_direction.js +23 -0
  98. package/package.json +3 -3
  99. package/dist/config/base_env_args.d.ts +0 -11
  100. package/dist/config/base_env_args.js +0 -19
  101. package/dist/config/index.d.ts +0 -1
  102. package/dist/quote/event/verify_clmm_swap_event.d.ts +0 -1
  103. package/dist/quote/event/verify_clmm_swap_event.js +0 -178
  104. package/dist/quote/pricing/token_price_cache.d.ts +0 -10
  105. package/dist/quote/pricing/token_price_cache.js +0 -40
  106. package/dist/trade/abstract_dex_trade_plus.d.ts +0 -43
  107. package/dist/trade/abstract_dex_trade_plus.js +0 -421
  108. package/dist/trade/check/tx_websocket_manager.d.ts +0 -23
  109. package/dist/trade/check/tx_websocket_manager.js +0 -119
  110. package/dist/trade/send/alchemy_base.d.ts +0 -5
  111. package/dist/trade/send/alchemy_base.js +0 -48
  112. package/dist/trade/send/ankr_base.d.ts +0 -5
  113. package/dist/trade/send/ankr_base.js +0 -48
  114. package/dist/trade/send/base_rpc.d.ts +0 -5
  115. package/dist/trade/send/base_rpc.js +0 -48
  116. package/dist/trade/send/blockpi_base.d.ts +0 -5
  117. package/dist/trade/send/blockpi_base.js +0 -48
  118. package/dist/trade/send/bloxroute_base.d.ts +0 -11
  119. package/dist/trade/send/bloxroute_base.js +0 -115
  120. package/dist/trade/send/chainstack_base.d.ts +0 -5
  121. package/dist/trade/send/chainstack_base.js +0 -48
  122. package/dist/trade/send/drpc_base.d.ts +0 -5
  123. package/dist/trade/send/drpc_base.js +0 -48
  124. package/dist/trade/send/getblock_base.d.ts +0 -5
  125. package/dist/trade/send/getblock_base.js +0 -48
  126. package/dist/trade/send/index.d.ts +0 -15
  127. package/dist/trade/send/index.js +0 -33
  128. package/dist/trade/send/infura_base.d.ts +0 -5
  129. package/dist/trade/send/infura_base.js +0 -48
  130. package/dist/trade/send/moralis_base.d.ts +0 -5
  131. package/dist/trade/send/moralis_base.js +0 -48
  132. package/dist/trade/send/onerpc_base.d.ts +0 -5
  133. package/dist/trade/send/onerpc_base.js +0 -48
  134. package/dist/trade/send/quicknode_base.d.ts +0 -5
  135. package/dist/trade/send/quicknode_base.js +0 -48
  136. package/dist/trade/send/send_tx.d.ts +0 -17
  137. package/dist/trade/send/send_tx.js +0 -163
  138. package/dist/ws/event_filter.d.ts +0 -8
  139. package/dist/ws/event_filter.js +0 -36
  140. package/dist/ws/index.d.ts +0 -2
  141. package/dist/ws/subscribe_v2_events.d.ts +0 -14
  142. package/dist/ws/subscribe_v2_events.js +0 -174
  143. package/dist/ws/subscribe_v3_events.d.ts +0 -14
  144. package/dist/ws/subscribe_v3_events.js +0 -174
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.calculateClmmDepth = calculateClmmDepth;
4
+ exports.priceFromSqrtX96 = priceFromSqrtX96;
5
+ exports.getSqrtRatioAtTick = getSqrtRatioAtTick;
6
+ exports.computeTargetSqrtPrice = computeTargetSqrtPrice;
7
+ exports.bigIntSqrt = bigIntSqrt;
8
+ const Q96 = 1n << 96n;
9
+ const MAX_UINT256 = (1n << 256n) - 1n;
10
+ function getSqrtRatioAtTick(tick) {
11
+ const absTick = Math.abs(tick);
12
+ if (absTick > 887272)
13
+ throw new Error(`Tick out of range: ${tick}`);
14
+ let ratio = (absTick & 0x1) !== 0
15
+ ? 0xfffcb933bd6fad37aa2d162d1a594001n
16
+ : 0x100000000000000000000000000000000n;
17
+ if (absTick & 0x2)
18
+ ratio = (ratio * 0xfff97272373d413259a46990580e213an) >> 128n;
19
+ if (absTick & 0x4)
20
+ ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdccn) >> 128n;
21
+ if (absTick & 0x8)
22
+ ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0n) >> 128n;
23
+ if (absTick & 0x10)
24
+ ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644n) >> 128n;
25
+ if (absTick & 0x20)
26
+ ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0n) >> 128n;
27
+ if (absTick & 0x40)
28
+ ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861n) >> 128n;
29
+ if (absTick & 0x80)
30
+ ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053n) >> 128n;
31
+ if (absTick & 0x100)
32
+ ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4n) >> 128n;
33
+ if (absTick & 0x200)
34
+ ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54n) >> 128n;
35
+ if (absTick & 0x400)
36
+ ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3n) >> 128n;
37
+ if (absTick & 0x800)
38
+ ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9n) >> 128n;
39
+ if (absTick & 0x1000)
40
+ ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825n) >> 128n;
41
+ if (absTick & 0x2000)
42
+ ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5n) >> 128n;
43
+ if (absTick & 0x4000)
44
+ ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7n) >> 128n;
45
+ if (absTick & 0x8000)
46
+ ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6n) >> 128n;
47
+ if (absTick & 0x10000)
48
+ ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9n) >> 128n;
49
+ if (absTick & 0x20000)
50
+ ratio = (ratio * 0x5d6af8dedb81196699c329225ee604n) >> 128n;
51
+ if (absTick & 0x40000)
52
+ ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98n) >> 128n;
53
+ if (absTick & 0x80000)
54
+ ratio = (ratio * 0x48a170391f7dc42444e8fa2n) >> 128n;
55
+ if (tick > 0)
56
+ ratio = MAX_UINT256 / ratio;
57
+ return (ratio >> 32n) + (ratio % (1n << 32n) === 0n ? 0n : 1n);
58
+ }
59
+ function calculateClmmDepth(input) {
60
+ const { poolAddress, tickCache, currentTick, tickSpacing, zeroForOne, targetBps, inputDecimals, outputDecimals, } = input;
61
+ const currentSqrtPriceX96 = BigInt(input.sqrtPriceX96);
62
+ let liquidity = BigInt(input.liquidity);
63
+ if (liquidity === 0n) {
64
+ return { amountInWei: 0n, amountIn: 0, amountOutWei: 0n, amountOut: 0, currentTick, targetTick: currentTick, targetSqrtPriceX96: currentSqrtPriceX96 };
65
+ }
66
+ const targetSqrtPriceX96 = computeTargetSqrtPrice(currentSqrtPriceX96, targetBps, zeroForOne);
67
+ const allTicks = tickCache.getCachedTickIndices(poolAddress);
68
+ const ticksToTraverse = getTicksBetween(allTicks, currentTick, targetSqrtPriceX96, zeroForOne, tickSpacing);
69
+ let totalInput = 0n;
70
+ let totalOutput = 0n;
71
+ let sqrtPriceCursor = currentSqrtPriceX96;
72
+ for (const tick of ticksToTraverse) {
73
+ const sqrtPriceAtTick = getSqrtRatioAtTick(tick);
74
+ if (zeroForOne && sqrtPriceAtTick <= targetSqrtPriceX96)
75
+ break;
76
+ if (!zeroForOne && sqrtPriceAtTick >= targetSqrtPriceX96)
77
+ break;
78
+ if (liquidity > 0n) {
79
+ totalInput += calcInputForRange(sqrtPriceCursor, sqrtPriceAtTick, liquidity, zeroForOne);
80
+ totalOutput += calcOutputForRange(sqrtPriceCursor, sqrtPriceAtTick, liquidity, zeroForOne);
81
+ }
82
+ let liquidityNet = tickCache.getTickLiquidityNet(poolAddress, tick) || 0n;
83
+ if (zeroForOne)
84
+ liquidityNet = -liquidityNet;
85
+ liquidity = liquidity + liquidityNet;
86
+ if (liquidity < 0n)
87
+ liquidity = 0n;
88
+ sqrtPriceCursor = sqrtPriceAtTick;
89
+ }
90
+ if (liquidity > 0n && sqrtPriceCursor !== targetSqrtPriceX96) {
91
+ totalInput += calcInputForRange(sqrtPriceCursor, targetSqrtPriceX96, liquidity, zeroForOne);
92
+ totalOutput += calcOutputForRange(sqrtPriceCursor, targetSqrtPriceX96, liquidity, zeroForOne);
93
+ }
94
+ const amountIn = Number(totalInput) / Math.pow(10, inputDecimals);
95
+ const amountOut = Number(totalOutput) / Math.pow(10, outputDecimals);
96
+ const sqrtPriceFloat = Number(targetSqrtPriceX96) / Number(Q96);
97
+ const targetTick = Math.floor(Math.log(sqrtPriceFloat * sqrtPriceFloat) / Math.log(1.0001));
98
+ return { amountInWei: totalInput, amountIn, amountOutWei: totalOutput, amountOut, currentTick, targetTick, targetSqrtPriceX96 };
99
+ }
100
+ function priceFromSqrtX96(sqrtPriceX96, baseDecimals, quoteDecimals, baseIsToken0) {
101
+ const sp = Number(sqrtPriceX96) / Number(Q96);
102
+ const priceToken1PerToken0 = sp * sp;
103
+ if (baseIsToken0) {
104
+ return priceToken1PerToken0 * Math.pow(10, baseDecimals - quoteDecimals);
105
+ }
106
+ else {
107
+ return (1 / priceToken1PerToken0) * Math.pow(10, baseDecimals - quoteDecimals);
108
+ }
109
+ }
110
+ function computeTargetSqrtPrice(currentSqrtPriceX96, bps, zeroForOne) {
111
+ const PRECISION = 10n ** 18n;
112
+ const bpsBigInt = BigInt(bps);
113
+ let factor;
114
+ if (zeroForOne) {
115
+ factor = 10000n - bpsBigInt;
116
+ }
117
+ else {
118
+ factor = 10000n + bpsBigInt;
119
+ }
120
+ const sqrtFactor = bigIntSqrt(factor * PRECISION);
121
+ const sqrtBase = bigIntSqrt(10000n * PRECISION);
122
+ return currentSqrtPriceX96 * sqrtFactor / sqrtBase;
123
+ }
124
+ function bigIntSqrt(n) {
125
+ if (n < 0n)
126
+ throw new Error('sqrt of negative');
127
+ if (n === 0n)
128
+ return 0n;
129
+ if (n <= 3n)
130
+ return 1n;
131
+ let x = n;
132
+ let y = (x + 1n) / 2n;
133
+ while (y < x) {
134
+ x = y;
135
+ y = (x + n / x) / 2n;
136
+ }
137
+ return x;
138
+ }
139
+ function getTicksBetween(allTicks, currentTick, targetSqrtPriceX96, zeroForOne, tickSpacing) {
140
+ if (zeroForOne) {
141
+ return allTicks
142
+ .filter(t => t <= currentTick)
143
+ .sort((a, b) => b - a);
144
+ }
145
+ else {
146
+ return allTicks
147
+ .filter(t => t > currentTick)
148
+ .sort((a, b) => a - b);
149
+ }
150
+ }
151
+ function calcInputForRange(sqrtPriceA, sqrtPriceB, liquidity, zeroForOne) {
152
+ const sqrtPriceLower = sqrtPriceA < sqrtPriceB ? sqrtPriceA : sqrtPriceB;
153
+ const sqrtPriceUpper = sqrtPriceA < sqrtPriceB ? sqrtPriceB : sqrtPriceA;
154
+ const diff = sqrtPriceUpper - sqrtPriceLower;
155
+ if (diff === 0n || liquidity === 0n)
156
+ return 0n;
157
+ if (zeroForOne) {
158
+ return liquidity * diff * Q96 / (sqrtPriceLower * sqrtPriceUpper);
159
+ }
160
+ else {
161
+ return liquidity * diff / Q96;
162
+ }
163
+ }
164
+ function calcOutputForRange(sqrtPriceA, sqrtPriceB, liquidity, zeroForOne) {
165
+ const sqrtPriceLower = sqrtPriceA < sqrtPriceB ? sqrtPriceA : sqrtPriceB;
166
+ const sqrtPriceUpper = sqrtPriceA < sqrtPriceB ? sqrtPriceB : sqrtPriceA;
167
+ const diff = sqrtPriceUpper - sqrtPriceLower;
168
+ if (diff === 0n || liquidity === 0n)
169
+ return 0n;
170
+ if (zeroForOne) {
171
+ return liquidity * diff / Q96;
172
+ }
173
+ else {
174
+ return liquidity * diff * Q96 / (sqrtPriceLower * sqrtPriceUpper);
175
+ }
176
+ }
@@ -0,0 +1,51 @@
1
+ import { QuoteDepthOutput } from '@clonegod/ttd-core';
2
+ import { ClmmTickCache } from '../tick/clmm_tick_cache';
3
+ export { calculateClmmDepth, getSqrtRatioAtTick, computeTargetSqrtPrice, bigIntSqrt, priceFromSqrtX96 } from './clmm_depth_calculator';
4
+ export type { ClmmDepthInput, DepthResult } from './clmm_depth_calculator';
5
+ export { calculateAmmDepth } from './amm_depth_calculator';
6
+ export type { AmmDepthInput, AmmDepthResult } from './amm_depth_calculator';
7
+ export { buildTickLiquiditySnapshot } from './tick_liquidity_snapshot';
8
+ export type { TickLiquiditySnapshot, TickLiquiditySnapshotInput, TickDataPoint } from './tick_liquidity_snapshot';
9
+ import { TickLiquiditySnapshot } from './tick_liquidity_snapshot';
10
+ export declare function logFeeChainConfigOnce(poolName: string, poolAddress: string, configFeeBps: number, chainFeeBps: number, dexId?: string, pair?: string): void;
11
+ export declare function clearFeeMatchLogged(poolAddress: string): void;
12
+ export interface BuildClmmDepthInput {
13
+ poolInfo: {
14
+ pool_name: string;
15
+ tokenA: any;
16
+ tokenB: any;
17
+ quote_token: string;
18
+ };
19
+ poolAddress: string;
20
+ tickCache: ClmmTickCache;
21
+ poolState: {
22
+ tick: number;
23
+ sqrtPriceX96: string;
24
+ liquidity: string;
25
+ tickSpacing: number;
26
+ token0: string;
27
+ };
28
+ basePriceUsd: number;
29
+ quotePriceUsd: number;
30
+ feeRateBps: number;
31
+ }
32
+ export interface ClmmDepthResult {
33
+ depth: QuoteDepthOutput;
34
+ tickLiquidity?: TickLiquiditySnapshot;
35
+ }
36
+ export declare function buildClmmDepth(input: BuildClmmDepthInput): ClmmDepthResult | undefined;
37
+ export interface BuildAmmDepthInput {
38
+ poolInfo: {
39
+ pool_name: string;
40
+ tokenA: any;
41
+ tokenB: any;
42
+ quote_token: string;
43
+ };
44
+ reserve0: string;
45
+ reserve1: string;
46
+ token0Address: string;
47
+ basePriceUsd: number;
48
+ quotePriceUsd: number;
49
+ feeRateBps: number;
50
+ }
51
+ export declare function buildAmmDepth(input: BuildAmmDepthInput): QuoteDepthOutput | undefined;
@@ -0,0 +1,264 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildTickLiquiditySnapshot = exports.calculateAmmDepth = exports.priceFromSqrtX96 = exports.bigIntSqrt = exports.computeTargetSqrtPrice = exports.getSqrtRatioAtTick = exports.calculateClmmDepth = void 0;
4
+ exports.logFeeChainConfigOnce = logFeeChainConfigOnce;
5
+ exports.clearFeeMatchLogged = clearFeeMatchLogged;
6
+ exports.buildClmmDepth = buildClmmDepth;
7
+ exports.buildAmmDepth = buildAmmDepth;
8
+ const ttd_core_1 = require("@clonegod/ttd-core");
9
+ const ttd_core_2 = require("@clonegod/ttd-core");
10
+ const clmm_depth_calculator_1 = require("./clmm_depth_calculator");
11
+ const amm_depth_calculator_1 = require("./amm_depth_calculator");
12
+ const trade_direction_1 = require("../../utils/trade_direction");
13
+ var clmm_depth_calculator_2 = require("./clmm_depth_calculator");
14
+ Object.defineProperty(exports, "calculateClmmDepth", { enumerable: true, get: function () { return clmm_depth_calculator_2.calculateClmmDepth; } });
15
+ Object.defineProperty(exports, "getSqrtRatioAtTick", { enumerable: true, get: function () { return clmm_depth_calculator_2.getSqrtRatioAtTick; } });
16
+ Object.defineProperty(exports, "computeTargetSqrtPrice", { enumerable: true, get: function () { return clmm_depth_calculator_2.computeTargetSqrtPrice; } });
17
+ Object.defineProperty(exports, "bigIntSqrt", { enumerable: true, get: function () { return clmm_depth_calculator_2.bigIntSqrt; } });
18
+ Object.defineProperty(exports, "priceFromSqrtX96", { enumerable: true, get: function () { return clmm_depth_calculator_2.priceFromSqrtX96; } });
19
+ var amm_depth_calculator_2 = require("./amm_depth_calculator");
20
+ Object.defineProperty(exports, "calculateAmmDepth", { enumerable: true, get: function () { return amm_depth_calculator_2.calculateAmmDepth; } });
21
+ var tick_liquidity_snapshot_1 = require("./tick_liquidity_snapshot");
22
+ Object.defineProperty(exports, "buildTickLiquiditySnapshot", { enumerable: true, get: function () { return tick_liquidity_snapshot_1.buildTickLiquiditySnapshot; } });
23
+ const tick_liquidity_snapshot_2 = require("./tick_liquidity_snapshot");
24
+ const clmm_tick_cache_1 = require("../tick/clmm_tick_cache");
25
+ let _depthPctLogged = false;
26
+ function logDepthLevelsOnce() {
27
+ if (_depthPctLogged)
28
+ return;
29
+ _depthPctLogged = true;
30
+ const pcts = (0, ttd_core_2.getDepthPricePctLevels)();
31
+ (0, ttd_core_1.log_info)(`[Depth] pctLevels=${JSON.stringify(pcts)}, default=${ttd_core_2.DEFAULT_TIER_PCT}`);
32
+ }
33
+ const _feeMatchLoggedPools = new Set();
34
+ function logFeeChainConfigOnce(poolName, poolAddress, configFeeBps, chainFeeBps, dexId, pair) {
35
+ if (_feeMatchLoggedPools.has(poolAddress))
36
+ return;
37
+ _feeMatchLoggedPools.add(poolAddress);
38
+ const diff = Math.abs(configFeeBps - chainFeeBps);
39
+ const drifted = diff >= 0.01;
40
+ if (drifted) {
41
+ (0, ttd_core_1.log_warn)(`[Fee] ${poolName} 配置漂移: config=${configFeeBps}bps ≠ chain=${chainFeeBps}bps (差 ${diff.toFixed(2)}bps) — 已用链上值,请运维检查池子配置`);
42
+ }
43
+ else {
44
+ (0, ttd_core_1.log_info)(`[Fee] ${poolName} config=${configFeeBps}bps == chain=${chainFeeBps}bps ✓`);
45
+ }
46
+ const addrLower = poolAddress.toLowerCase();
47
+ ttd_core_2.ALERT_TYPES.QUOTE_FEE_CHAIN_DRIFT.reportIfChanged(addrLower, drifted, () => ({
48
+ identity: addrLower,
49
+ scope: { dex_id: dexId, pool_address: addrLower, pair },
50
+ title: `${poolName} fee 漂移 cfg=${configFeeBps}bps chain=${chainFeeBps}bps`,
51
+ detail: {
52
+ pool_name: poolName,
53
+ config_fee_bps: configFeeBps,
54
+ chain_fee_bps: chainFeeBps,
55
+ diff_bps: diff,
56
+ },
57
+ }));
58
+ }
59
+ function clearFeeMatchLogged(poolAddress) {
60
+ _feeMatchLoggedPools.delete(poolAddress);
61
+ }
62
+ function grossUpFee(amountInNet, feeRateBps) {
63
+ if (feeRateBps <= 0 || amountInNet <= 0) {
64
+ return { amountInGross: amountInNet, feeAmount: 0 };
65
+ }
66
+ const feeRatio = feeRateBps / 10000;
67
+ const amountInGross = amountInNet / (1 - feeRatio);
68
+ const feeAmount = amountInGross - amountInNet;
69
+ return { amountInGross, feeAmount };
70
+ }
71
+ const _tickLiquidityLastBuild = new Map();
72
+ function assembleEntry(tiers) {
73
+ const defaultTier = tiers.find(t => t.pct === ttd_core_2.DEFAULT_TIER_PCT) ?? tiers[0];
74
+ return {
75
+ price: defaultTier.price,
76
+ amount: defaultTier.amount,
77
+ amount_in: defaultTier.amount_in,
78
+ amount_in_usd: defaultTier.amount_in_usd,
79
+ fee: defaultTier.fee,
80
+ fee_usd: defaultTier.fee_usd,
81
+ tick_move: defaultTier.tick_move,
82
+ tiers,
83
+ };
84
+ }
85
+ function buildClmmDepth(input) {
86
+ logDepthLevelsOnce();
87
+ const pctLevels = (0, ttd_core_2.getDepthPricePctLevels)();
88
+ if (pctLevels.length === 0)
89
+ return undefined;
90
+ const { poolInfo, poolAddress, tickCache, poolState, basePriceUsd, quotePriceUsd, feeRateBps } = input;
91
+ if (BigInt(poolState.liquidity) === 0n)
92
+ return undefined;
93
+ if (feeRateBps == null || feeRateBps < 0) {
94
+ (0, ttd_core_1.log_debug)(`[Depth] ${poolInfo.pool_name} CLMM: invalid feeRateBps=${feeRateBps}, skip`, '');
95
+ return undefined;
96
+ }
97
+ try {
98
+ const askDirection = (0, trade_direction_1.resolveTradeDirection)(poolInfo, true);
99
+ const bidDirection = (0, trade_direction_1.resolveTradeDirection)(poolInfo, false);
100
+ const askZeroForOne = askDirection.inputToken.address.toLowerCase() === poolState.token0.toLowerCase();
101
+ const bidZeroForOne = bidDirection.inputToken.address.toLowerCase() === poolState.token0.toLowerCase();
102
+ const baseToken = askDirection.baseToken;
103
+ const quoteToken = askDirection.quoteToken;
104
+ const baseIsToken0 = baseToken.address.toLowerCase() === poolState.token0.toLowerCase();
105
+ const midPrice = (0, clmm_depth_calculator_1.priceFromSqrtX96)(BigInt(poolState.sqrtPriceX96), baseToken.decimals, quoteToken.decimals, baseIsToken0);
106
+ const askTiers = [];
107
+ const bidTiers = [];
108
+ for (const pct of pctLevels) {
109
+ const bps = Math.round(pct * 100);
110
+ const askResult = (0, clmm_depth_calculator_1.calculateClmmDepth)({
111
+ poolAddress, tickCache,
112
+ currentTick: poolState.tick, sqrtPriceX96: poolState.sqrtPriceX96,
113
+ liquidity: poolState.liquidity, tickSpacing: poolState.tickSpacing,
114
+ zeroForOne: askZeroForOne, targetBps: bps,
115
+ inputDecimals: quoteToken.decimals, outputDecimals: baseToken.decimals,
116
+ });
117
+ const bidResult = (0, clmm_depth_calculator_1.calculateClmmDepth)({
118
+ poolAddress, tickCache,
119
+ currentTick: poolState.tick, sqrtPriceX96: poolState.sqrtPriceX96,
120
+ liquidity: poolState.liquidity, tickSpacing: poolState.tickSpacing,
121
+ zeroForOne: bidZeroForOne, targetBps: bps,
122
+ inputDecimals: baseToken.decimals, outputDecimals: quoteToken.decimals,
123
+ });
124
+ const askTargetPrice = (0, clmm_depth_calculator_1.priceFromSqrtX96)(askResult.targetSqrtPriceX96, baseToken.decimals, quoteToken.decimals, baseIsToken0);
125
+ const bidTargetPrice = (0, clmm_depth_calculator_1.priceFromSqrtX96)(bidResult.targetSqrtPriceX96, baseToken.decimals, quoteToken.decimals, baseIsToken0);
126
+ const askGross = grossUpFee(askResult.amountIn, feeRateBps);
127
+ const bidGross = grossUpFee(bidResult.amountIn, feeRateBps);
128
+ const askTickMove = askResult.targetTick < askResult.currentTick
129
+ ? `${askResult.targetTick} <- ${askResult.currentTick}`
130
+ : `${askResult.currentTick} -> ${askResult.targetTick}`;
131
+ const bidTickMove = bidResult.targetTick > bidResult.currentTick
132
+ ? `${bidResult.currentTick} -> ${bidResult.targetTick}`
133
+ : `${bidResult.targetTick} <- ${bidResult.currentTick}`;
134
+ askTiers.push({
135
+ pct,
136
+ price: askTargetPrice,
137
+ amount: askResult.amountOut,
138
+ amount_in: askGross.amountInGross,
139
+ amount_in_usd: askGross.amountInGross * quotePriceUsd,
140
+ fee: askGross.feeAmount,
141
+ fee_usd: askGross.feeAmount * quotePriceUsd,
142
+ tick_move: askTickMove,
143
+ });
144
+ bidTiers.push({
145
+ pct,
146
+ price: bidTargetPrice,
147
+ amount: bidResult.amountOut,
148
+ amount_in: bidGross.amountInGross,
149
+ amount_in_usd: bidGross.amountInGross * basePriceUsd,
150
+ fee: bidGross.feeAmount,
151
+ fee_usd: bidGross.feeAmount * basePriceUsd,
152
+ tick_move: bidTickMove,
153
+ });
154
+ }
155
+ const depth = {
156
+ mid_price: midPrice,
157
+ fee_rate_bps: feeRateBps,
158
+ ask: assembleEntry(askTiers),
159
+ bid: assembleEntry(bidTiers),
160
+ };
161
+ let tickLiquidity;
162
+ const now = Date.now();
163
+ const lastBuild = _tickLiquidityLastBuild.get(poolAddress) || 0;
164
+ if (now - lastBuild < clmm_tick_cache_1.TICK_REFRESH_INTERVAL_MS) {
165
+ return { depth, tickLiquidity: undefined };
166
+ }
167
+ _tickLiquidityLastBuild.set(poolAddress, now);
168
+ try {
169
+ const tokenAIsToken0 = poolInfo.tokenA?.address?.toLowerCase() === poolState.token0.toLowerCase();
170
+ const token0Info = tokenAIsToken0 ? poolInfo.tokenA : poolInfo.tokenB;
171
+ const token1Info = tokenAIsToken0 ? poolInfo.tokenB : poolInfo.tokenA;
172
+ tickLiquidity = (0, tick_liquidity_snapshot_2.buildTickLiquiditySnapshot)({
173
+ poolAddress,
174
+ pair: '',
175
+ protocolId: '',
176
+ tickCache,
177
+ currentTick: poolState.tick,
178
+ sqrtPriceX96: poolState.sqrtPriceX96,
179
+ liquidity: poolState.liquidity,
180
+ tickSpacing: poolState.tickSpacing,
181
+ token0: { address: poolState.token0, symbol: token0Info?.symbol || '', decimals: token0Info?.decimals || 18 },
182
+ token1: { address: token1Info?.address || '', symbol: token1Info?.symbol || '', decimals: token1Info?.decimals || 18 },
183
+ baseIsToken0,
184
+ token0PriceUsd: baseIsToken0 ? basePriceUsd : quotePriceUsd,
185
+ token1PriceUsd: baseIsToken0 ? quotePriceUsd : basePriceUsd,
186
+ });
187
+ }
188
+ catch (e) {
189
+ (0, ttd_core_1.log_debug)(`[TickLiquidity] ${poolInfo.pool_name} failed: ${e.message}`, '');
190
+ }
191
+ return { depth, tickLiquidity };
192
+ }
193
+ catch (error) {
194
+ (0, ttd_core_1.log_debug)(`[Depth] ${poolInfo.pool_name} CLMM depth failed: ${error.message}`, '');
195
+ return undefined;
196
+ }
197
+ }
198
+ function buildAmmDepth(input) {
199
+ logDepthLevelsOnce();
200
+ const pctLevels = (0, ttd_core_2.getDepthPricePctLevels)();
201
+ if (pctLevels.length === 0)
202
+ return undefined;
203
+ const { poolInfo, reserve0, reserve1, token0Address, basePriceUsd, quotePriceUsd, feeRateBps } = input;
204
+ if (feeRateBps == null || feeRateBps < 0) {
205
+ (0, ttd_core_1.log_debug)(`[Depth] ${poolInfo.pool_name} AMM: invalid feeRateBps=${feeRateBps}, skip`, '');
206
+ return undefined;
207
+ }
208
+ try {
209
+ const askDirection = (0, trade_direction_1.resolveTradeDirection)(poolInfo, true);
210
+ const baseToken = askDirection.baseToken;
211
+ const quoteToken = askDirection.quoteToken;
212
+ const baseIsToken0 = baseToken.address.toLowerCase() === token0Address.toLowerCase();
213
+ const baseDec = baseIsToken0 ? baseToken.decimals : quoteToken.decimals;
214
+ const quoteDec = baseIsToken0 ? quoteToken.decimals : baseToken.decimals;
215
+ const baseReserveUi = Number(BigInt(baseIsToken0 ? reserve0 : reserve1)) / Math.pow(10, baseToken.decimals);
216
+ const quoteReserveUi = Number(BigInt(baseIsToken0 ? reserve1 : reserve0)) / Math.pow(10, quoteToken.decimals);
217
+ const midPrice = quoteReserveUi / baseReserveUi;
218
+ const askTiers = [];
219
+ const bidTiers = [];
220
+ for (const pct of pctLevels) {
221
+ const bps = Math.round(pct * 100);
222
+ const askResult = (0, amm_depth_calculator_1.calculateAmmDepth)({
223
+ reserve0, reserve1, targetBps: bps, isBuy: true, baseIsToken0,
224
+ token0Decimals: baseIsToken0 ? baseToken.decimals : quoteToken.decimals,
225
+ token1Decimals: baseIsToken0 ? quoteToken.decimals : baseToken.decimals,
226
+ });
227
+ const bidResult = (0, amm_depth_calculator_1.calculateAmmDepth)({
228
+ reserve0, reserve1, targetBps: bps, isBuy: false, baseIsToken0,
229
+ token0Decimals: baseIsToken0 ? baseToken.decimals : quoteToken.decimals,
230
+ token1Decimals: baseIsToken0 ? quoteToken.decimals : baseToken.decimals,
231
+ });
232
+ const askGross = grossUpFee(askResult.amountIn, feeRateBps);
233
+ const bidGross = grossUpFee(bidResult.amountIn, feeRateBps);
234
+ askTiers.push({
235
+ pct,
236
+ price: askResult.targetPrice,
237
+ amount: askResult.amountOut,
238
+ amount_in: askGross.amountInGross,
239
+ amount_in_usd: askGross.amountInGross * quotePriceUsd,
240
+ fee: askGross.feeAmount,
241
+ fee_usd: askGross.feeAmount * quotePriceUsd,
242
+ });
243
+ bidTiers.push({
244
+ pct,
245
+ price: bidResult.targetPrice,
246
+ amount: bidResult.amountOut,
247
+ amount_in: bidGross.amountInGross,
248
+ amount_in_usd: bidGross.amountInGross * basePriceUsd,
249
+ fee: bidGross.feeAmount,
250
+ fee_usd: bidGross.feeAmount * basePriceUsd,
251
+ });
252
+ }
253
+ return {
254
+ mid_price: midPrice,
255
+ fee_rate_bps: feeRateBps,
256
+ ask: assembleEntry(askTiers),
257
+ bid: assembleEntry(bidTiers),
258
+ };
259
+ }
260
+ catch (error) {
261
+ (0, ttd_core_1.log_debug)(`[Depth] ${poolInfo.pool_name} AMM depth failed: ${error.message}`, '');
262
+ return undefined;
263
+ }
264
+ }
@@ -0,0 +1,58 @@
1
+ import { ClmmTickCache } from '../tick/clmm_tick_cache';
2
+ export interface TickLiquiditySnapshotInput {
3
+ poolAddress: string;
4
+ pair: string;
5
+ protocolId: string;
6
+ tickCache: ClmmTickCache;
7
+ currentTick: number;
8
+ sqrtPriceX96: string;
9
+ liquidity: string;
10
+ tickSpacing: number;
11
+ token0: {
12
+ address: string;
13
+ symbol: string;
14
+ decimals: number;
15
+ };
16
+ token1: {
17
+ address: string;
18
+ symbol: string;
19
+ decimals: number;
20
+ };
21
+ baseIsToken0: boolean;
22
+ token0PriceUsd: number;
23
+ token1PriceUsd: number;
24
+ rangeBps?: number;
25
+ }
26
+ export interface TickDataPoint {
27
+ tick: number;
28
+ price0: number;
29
+ price1: number;
30
+ liquidity: string;
31
+ amount0: number;
32
+ amount1: number;
33
+ tvlUsd: number;
34
+ buyable: number;
35
+ sellable: number;
36
+ }
37
+ export interface TickLiquiditySnapshot {
38
+ poolAddress: string;
39
+ pair: string;
40
+ protocolId: string;
41
+ currentTick: number;
42
+ tickSpacing: number;
43
+ currentPrice: number;
44
+ token0: {
45
+ address: string;
46
+ symbol: string;
47
+ decimals: number;
48
+ };
49
+ token1: {
50
+ address: string;
51
+ symbol: string;
52
+ decimals: number;
53
+ };
54
+ ticks: TickDataPoint[];
55
+ totalTvlUsd: number;
56
+ timestamp: number;
57
+ }
58
+ export declare function buildTickLiquiditySnapshot(input: TickLiquiditySnapshotInput): TickLiquiditySnapshot | undefined;