@clonegod/ttd-bsc-common 3.1.18 → 3.1.22

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 (37) hide show
  1. package/dist/config/BscQuoteAppConfig.js +2 -0
  2. package/dist/config/bsc_env_args.d.ts +60 -1
  3. package/dist/config/bsc_env_args.js +121 -21
  4. package/dist/quote/verify/quote_price_verify.js +1 -1
  5. package/dist/trade/abstract_dex_trade.d.ts +2 -1
  6. package/dist/trade/abstract_dex_trade.js +10 -12
  7. package/dist/trade/caller_manager.d.ts +3 -0
  8. package/dist/trade/caller_manager.js +53 -5
  9. package/dist/trade/check/abstract_tx_result_checker.d.ts +28 -0
  10. package/dist/trade/check/abstract_tx_result_checker.js +169 -0
  11. package/dist/trade/check/base_tx_result_checker.js +1 -1
  12. package/dist/trade/check/index.d.ts +1 -1
  13. package/dist/trade/check/index.js +1 -1
  14. package/dist/trade/parse/base_parser.js +1 -1
  15. package/package.json +3 -3
  16. package/dist/quote/accuracy/index.d.ts +0 -2
  17. package/dist/quote/accuracy/index.js +0 -5
  18. package/dist/quote/accuracy/quote_accuracy_checker.d.ts +0 -42
  19. package/dist/quote/accuracy/quote_accuracy_checker.js +0 -144
  20. package/dist/quote/depth/verify_depth.d.ts +0 -10
  21. package/dist/quote/depth/verify_depth.js +0 -55
  22. package/dist/quote/event/verify_clmm_swap_event.d.ts +0 -1
  23. package/dist/quote/event/verify_clmm_swap_event.js +0 -178
  24. package/dist/redis/index.d.ts +0 -1
  25. package/dist/redis/index.js +0 -17
  26. package/dist/redis/redis_client.d.ts +0 -23
  27. package/dist/redis/redis_client.js +0 -126
  28. package/dist/trade/check/tx_websocket_manager.d.ts +0 -21
  29. package/dist/trade/check/tx_websocket_manager.js +0 -167
  30. package/dist/yyws/index.d.ts +0 -2
  31. package/dist/yyws/index.js +0 -18
  32. package/dist/yyws/mock_ws_server.d.ts +0 -1
  33. package/dist/yyws/mock_ws_server.js +0 -77
  34. package/dist/yyws/type.d.ts +0 -25
  35. package/dist/yyws/type.js +0 -2
  36. package/dist/yyws/yyws_client.d.ts +0 -2
  37. package/dist/yyws/yyws_client.js +0 -76
@@ -39,7 +39,7 @@ class TradeResultSubscriber {
39
39
  getSubscriptions() {
40
40
  if (this.cachedSubscriptions)
41
41
  return this.cachedSubscriptions;
42
- const groupIds = (process.env.TRADE_GROUP_ID || process.env.VAULT_GROUP_ID || '').split(',').map(s => s.trim()).filter(Boolean);
42
+ const groupIds = ((0, ttd_core_1.getCoreEnv)()?.trade_group_id || '').split(',').map(s => s.trim()).filter(Boolean);
43
43
  const subs = [];
44
44
  for (const gid of groupIds) {
45
45
  const w = (0, ttd_core_1.load_wallet)(gid, true);
@@ -1 +1 @@
1
- export * from "./base_tx_result_checker";
1
+ export * from "./abstract_tx_result_checker";
@@ -14,4 +14,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./base_tx_result_checker"), exports);
17
+ __exportStar(require("./abstract_tx_result_checker"), exports);
@@ -13,7 +13,7 @@ class BaseTxParser {
13
13
  this.provider = new ethers_compat_1.ethersCompat.JsonRpcProvider(config.rpcEndpoint);
14
14
  }
15
15
  async getBlockTime(blockNumber) {
16
- if (process.env.NEED_BLOCK_TIME_INFO !== 'true') {
16
+ if (!(0, ttd_core_1.getCoreEnv)().trade_parse_fetch_block_time) {
17
17
  return 0;
18
18
  }
19
19
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clonegod/ttd-bsc-common",
3
- "version": "3.1.18",
3
+ "version": "3.1.22",
4
4
  "description": "BSC common library",
5
5
  "license": "UNLICENSED",
6
6
  "main": "dist/index.js",
@@ -14,8 +14,8 @@
14
14
  "push": "npm run build && npm publish"
15
15
  },
16
16
  "dependencies": {
17
- "@clonegod/ttd-core": "3.1.18",
18
- "axios": "^1.12.0",
17
+ "@clonegod/ttd-core": "3.1.21",
18
+ "axios": "1.15.0",
19
19
  "dotenv": "^16.4.7",
20
20
  "ethers": "^5.8.0",
21
21
  "secp256k1": "^5.0.1"
@@ -1,2 +0,0 @@
1
- export { QuoteAccuracyChecker } from './quote_accuracy_checker';
2
- export type { CheckSwapParams, CheckSyncParams } from './quote_accuracy_checker';
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.QuoteAccuracyChecker = void 0;
4
- var quote_accuracy_checker_1 = require("./quote_accuracy_checker");
5
- Object.defineProperty(exports, "QuoteAccuracyChecker", { enumerable: true, get: function () { return quote_accuracy_checker_1.QuoteAccuracyChecker; } });
@@ -1,42 +0,0 @@
1
- export interface CheckSwapParams {
2
- poolAddress: string;
3
- poolName: string;
4
- blockNumber: number;
5
- txHash: string;
6
- amount0: string;
7
- amount1: string;
8
- token0Address: string;
9
- token1Address: string;
10
- token0Decimals: number;
11
- token1Decimals: number;
12
- poolInfo: {
13
- tokenA: any;
14
- tokenB: any;
15
- quote_token: string;
16
- };
17
- }
18
- export interface CheckSyncParams {
19
- poolAddress: string;
20
- poolName: string;
21
- blockNumber: number;
22
- reserve0: string;
23
- reserve1: string;
24
- token0Address: string;
25
- token1Address: string;
26
- token0Decimals: number;
27
- token1Decimals: number;
28
- poolInfo: {
29
- tokenA: any;
30
- tokenB: any;
31
- quote_token: string;
32
- };
33
- }
34
- export declare class QuoteAccuracyChecker {
35
- private quoteCache;
36
- private reserveCache;
37
- private get enabled();
38
- cacheQuote(poolAddress: string, priceId: string, source: string, askPrice: number, bidPrice: number, blockNumber: number, quoteAmountUsd: number, token0PriceUsd?: number, token1PriceUsd?: number): void;
39
- checkSwap(params: CheckSwapParams): void;
40
- checkSync(params: CheckSyncParams): void;
41
- private compareAndLog;
42
- }
@@ -1,144 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.QuoteAccuracyChecker = void 0;
4
- const trade_direction_1 = require("../../utils/trade_direction");
5
- class QuoteAccuracyChecker {
6
- constructor() {
7
- this.quoteCache = new Map();
8
- this.reserveCache = new Map();
9
- }
10
- get enabled() {
11
- return process.env.QUOTE_ACCURACY_LOG === 'true';
12
- }
13
- cacheQuote(poolAddress, priceId, source, askPrice, bidPrice, blockNumber, quoteAmountUsd, token0PriceUsd = 0, token1PriceUsd = 0) {
14
- if (!this.enabled)
15
- return;
16
- this.quoteCache.set(poolAddress, {
17
- priceId, source, askPrice, bidPrice, blockNumber, quoteAmountUsd,
18
- verifiedBlock: 0,
19
- token0PriceUsd, token1PriceUsd,
20
- });
21
- }
22
- checkSwap(params) {
23
- if (!this.enabled)
24
- return;
25
- const { poolAddress, poolName, blockNumber, txHash, amount0, amount1, poolInfo } = params;
26
- const { token0Address, token1Address, token0Decimals, token1Decimals } = params;
27
- const cached = this.quoteCache.get(poolAddress);
28
- if (!cached)
29
- return;
30
- if (blockNumber <= cached.blockNumber)
31
- return;
32
- if (blockNumber <= cached.verifiedBlock)
33
- return;
34
- cached.verifiedBlock = blockNumber;
35
- const amt0 = BigInt(amount0);
36
- const amt1 = BigInt(amount1);
37
- if (amt0 === 0n && amt1 === 0n)
38
- return;
39
- let inputTokenAddress;
40
- let outputTokenAddress;
41
- let inputAmountUi;
42
- let outputAmountUi;
43
- if (amt0 > 0n && amt1 < 0n) {
44
- inputTokenAddress = token0Address;
45
- outputTokenAddress = token1Address;
46
- inputAmountUi = Number(amt0) / Math.pow(10, token0Decimals);
47
- outputAmountUi = Number(-amt1) / Math.pow(10, token1Decimals);
48
- }
49
- else if (amt0 < 0n && amt1 > 0n) {
50
- inputTokenAddress = token1Address;
51
- outputTokenAddress = token0Address;
52
- inputAmountUi = Number(amt1) / Math.pow(10, token1Decimals);
53
- outputAmountUi = Number(-amt0) / Math.pow(10, token0Decimals);
54
- }
55
- else {
56
- return;
57
- }
58
- this.compareAndLog(poolAddress, poolName, poolInfo, cached, inputTokenAddress, outputTokenAddress, inputAmountUi, outputAmountUi, cached.token0PriceUsd, cached.token1PriceUsd, token0Address, blockNumber, txHash);
59
- }
60
- checkSync(params) {
61
- if (!this.enabled)
62
- return;
63
- const { poolAddress, poolName, blockNumber, reserve0, reserve1, poolInfo } = params;
64
- const { token0Address, token1Address, token0Decimals, token1Decimals } = params;
65
- const cached = this.quoteCache.get(poolAddress);
66
- if (!cached)
67
- return;
68
- if (blockNumber <= cached.blockNumber)
69
- return;
70
- if (blockNumber <= cached.verifiedBlock)
71
- return;
72
- const newR0 = BigInt(reserve0);
73
- const newR1 = BigInt(reserve1);
74
- const oldReserves = this.reserveCache.get(poolAddress);
75
- this.reserveCache.set(poolAddress, { reserve0: newR0, reserve1: newR1 });
76
- if (!oldReserves)
77
- return;
78
- const delta0 = newR0 - oldReserves.reserve0;
79
- const delta1 = newR1 - oldReserves.reserve1;
80
- if ((delta0 > 0n && delta1 > 0n) || (delta0 < 0n && delta1 < 0n) || (delta0 === 0n && delta1 === 0n)) {
81
- return;
82
- }
83
- cached.verifiedBlock = blockNumber;
84
- let inputTokenAddress;
85
- let outputTokenAddress;
86
- let inputAmountUi;
87
- let outputAmountUi;
88
- if (delta0 > 0n && delta1 < 0n) {
89
- inputTokenAddress = token0Address;
90
- outputTokenAddress = token1Address;
91
- inputAmountUi = Number(delta0) / Math.pow(10, token0Decimals);
92
- outputAmountUi = Number(-delta1) / Math.pow(10, token1Decimals);
93
- }
94
- else {
95
- inputTokenAddress = token1Address;
96
- outputTokenAddress = token0Address;
97
- inputAmountUi = Number(delta1) / Math.pow(10, token1Decimals);
98
- outputAmountUi = Number(-delta0) / Math.pow(10, token0Decimals);
99
- }
100
- this.compareAndLog(poolAddress, poolName, poolInfo, cached, inputTokenAddress, outputTokenAddress, inputAmountUi, outputAmountUi, cached.token0PriceUsd, cached.token1PriceUsd, token0Address, blockNumber);
101
- }
102
- compareAndLog(poolAddress, poolName, poolInfo, cached, inputTokenAddress, outputTokenAddress, inputAmountUi, outputAmountUi, token0PriceUsd, token1PriceUsd, token0Address, swapBlockNumber, txHash) {
103
- if (inputAmountUi <= 0 || outputAmountUi <= 0)
104
- return;
105
- let swapUsd = 0;
106
- if (token0PriceUsd && token1PriceUsd && token0Address) {
107
- const inputIsToken0 = inputTokenAddress.toLowerCase() === token0Address.toLowerCase();
108
- swapUsd = inputIsToken0
109
- ? inputAmountUi * token0PriceUsd
110
- : inputAmountUi * token1PriceUsd;
111
- }
112
- const direction = (0, trade_direction_1.resolveTradeDirection)(poolInfo, true);
113
- const baseToken = direction.baseToken;
114
- const quoteToken = direction.quoteToken;
115
- const inputIsQuoteToken = inputTokenAddress.toLowerCase() === quoteToken.address.toLowerCase();
116
- const isBuy = inputIsQuoteToken;
117
- const execPrice = (0, trade_direction_1.calculateStandardPrice)(inputAmountUi, outputAmountUi, isBuy);
118
- const execPriceNum = Number(execPrice);
119
- const refPrice = isBuy ? cached.askPrice : cached.bidPrice;
120
- const side = isBuy ? 'BUY' : 'SELL';
121
- if (refPrice <= 0 || execPriceNum <= 0)
122
- return;
123
- const diffBps = (execPriceNum - refPrice) / refPrice * 10000;
124
- const absDiffBps = Math.abs(diffBps);
125
- const status = absDiffBps < 10 ? '✅' : absDiffBps < 30 ? '⚠️' : '❌';
126
- const usdStr = swapUsd > 0 ? `$${swapUsd.toFixed(0)}` : '$?';
127
- const minUsd = cached.quoteAmountUsd * 0.5;
128
- const maxUsd = cached.quoteAmountUsd * 2;
129
- const inRange = swapUsd <= 0 || (swapUsd >= minUsd && swapUsd <= maxUsd);
130
- const rangeTag = inRange ? '' : ' [out]';
131
- const tradeFlow = isBuy
132
- ? `${inputAmountUi.toFixed(4)} ${quoteToken.symbol} -> ${outputAmountUi.toFixed(4)} ${baseToken.symbol}`
133
- : `${inputAmountUi.toFixed(4)} ${baseToken.symbol} -> ${outputAmountUi.toFixed(4)} ${quoteToken.symbol}`;
134
- const quoteSrc = cached.source || '?';
135
- const quoteTag = `quote[${quoteSrc} blk:${cached.blockNumber}]`;
136
- const swapBlk = swapBlockNumber || '?';
137
- const swapTx = txHash ? ` ${txHash.slice(0, 10)}` : '';
138
- const swapTag = `swap[blk:${swapBlk}${swapTx}]`;
139
- const priceLabel = isBuy ? 'ask' : 'bid';
140
- const msg = ` ↳ [Verify] ${side} ${usdStr} (${tradeFlow}) ${quoteTag} ${priceLabel}=${refPrice.toFixed(12)} vs ${swapTag} exec=${execPriceNum.toFixed(12)} diff=${diffBps > 0 ? '+' : ''}${diffBps.toFixed(1)}bps ${status}${rangeTag}`;
141
- console.log(msg);
142
- }
143
- }
144
- exports.QuoteAccuracyChecker = QuoteAccuracyChecker;
@@ -1,10 +0,0 @@
1
- import { PoolDepthData } from '@clonegod/ttd-core';
2
- export declare function isDepthVerifyEnabled(): boolean;
3
- export interface DepthVerifyInput {
4
- poolName: string;
5
- askPrice: number;
6
- bidPrice: number;
7
- depth: PoolDepthData;
8
- quoteByUsd: (quoteAmountUsd: number, isBuy: boolean) => Promise<number | null>;
9
- }
10
- export declare function verifyDepth(input: DepthVerifyInput): Promise<void>;
@@ -1,55 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isDepthVerifyEnabled = isDepthVerifyEnabled;
4
- exports.verifyDepth = verifyDepth;
5
- const ttd_core_1 = require("@clonegod/ttd-core");
6
- function isDepthVerifyEnabled() {
7
- return process.env.DEPTH_VERIFY === 'true';
8
- }
9
- async function verifyDepth(input) {
10
- if (!isDepthVerifyEnabled())
11
- return;
12
- const { poolName, askPrice, bidPrice, depth, quoteByUsd } = input;
13
- if (askPrice <= 0 || bidPrice <= 0)
14
- return;
15
- const bpsKeys = new Set([
16
- ...Object.keys(depth.ask).map(Number),
17
- ...Object.keys(depth.bid).map(Number),
18
- ]);
19
- const lines = [];
20
- for (const bps of [...bpsKeys].sort((a, b) => a - b)) {
21
- const askData = depth.ask[bps];
22
- const bidData = depth.bid[bps];
23
- const parts = [];
24
- if (askData && askData.amountInUsd > 0) {
25
- try {
26
- const execPrice = await quoteByUsd(askData.amountInUsd, true);
27
- if (execPrice !== null && execPrice > 0) {
28
- const actualBps = Math.abs(execPrice - askPrice) / askPrice * 10000;
29
- const diff = Math.abs(actualBps - bps);
30
- const status = diff < bps * 0.3 ? '✅' : '⚠️';
31
- parts.push(`ask: ${askData.amountIn.toFixed(4)} quote -> ${askData.amount.toFixed(4)} base, ${actualBps.toFixed(1)}bps ${status}`);
32
- }
33
- }
34
- catch { }
35
- }
36
- if (bidData && bidData.amountInUsd > 0) {
37
- try {
38
- const execPrice = await quoteByUsd(bidData.amountInUsd, false);
39
- if (execPrice !== null && execPrice > 0) {
40
- const actualBps = Math.abs(bidPrice - execPrice) / bidPrice * 10000;
41
- const diff = Math.abs(actualBps - bps);
42
- const status = diff < bps * 0.3 ? '✅' : '⚠️';
43
- parts.push(`bid: ${bidData.amountIn.toFixed(4)} base -> ${bidData.amount.toFixed(4)} quote, ${actualBps.toFixed(1)}bps ${status}`);
44
- }
45
- }
46
- catch { }
47
- }
48
- if (parts.length > 0) {
49
- lines.push(` ${bps}bps => ${parts.join(' | ')}`);
50
- }
51
- }
52
- if (lines.length > 0) {
53
- (0, ttd_core_1.log_info)(`[DepthVerify] ${poolName}:\n${lines.join('\n')}`);
54
- }
55
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,178 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const dotenv_1 = __importDefault(require("dotenv"));
16
- dotenv_1.default.config();
17
- const ethers_1 = require("ethers");
18
- const constants_1 = require("../../common/constants");
19
- const log = (level, msg, data) => {
20
- const timestamp = new Date().toISOString();
21
- console.log(`${timestamp} [${level}] ${msg}`);
22
- if (data)
23
- console.log(data);
24
- };
25
- function verifySwapEventParsing() {
26
- return __awaiter(this, void 0, void 0, function* () {
27
- const wsEndpoint = process.env.WS_ENDPOINT || '';
28
- const poolAddress = '0xc1a780989734a0e5df875cebe410748562e1c5e6';
29
- const poolName = 'B2/BNB';
30
- log('INFO', `正在连接到WebSocket: ${wsEndpoint}`);
31
- const wsProvider = new ethers_1.ethers.providers.WebSocketProvider(wsEndpoint);
32
- yield wsProvider.ready;
33
- log('INFO', '连接成功,准备测试事件解析');
34
- const updatedSwapHash = ethers_1.ethers.utils.id(constants_1.EVENT_SIGNATURES.SWAP_RAW);
35
- log('INFO', `更新后的Swap事件哈希: ${updatedSwapHash}`);
36
- const capturedSwapHash = '0x19b47279256b2a23a1665c810c8d55a1758940ee09377d4f8d26497a3577dc83';
37
- log('INFO', `之前捕获的Swap事件哈希: ${capturedSwapHash}`);
38
- if (updatedSwapHash === capturedSwapHash) {
39
- log('INFO', '✅ 事件哈希匹配,签名修改正确');
40
- }
41
- else {
42
- log('WARN', '⚠️ 事件哈希不匹配,可能需要调整签名格式');
43
- }
44
- const methods = [
45
- {
46
- name: "方法1:直接使用更新后的SWAP_RAW签名",
47
- createInterface: () => new ethers_1.ethers.utils.Interface([constants_1.EVENT_SIGNATURES.SWAP_RAW])
48
- },
49
- {
50
- name: "方法2:添加event前缀(推荐方式)",
51
- createInterface: () => new ethers_1.ethers.utils.Interface([`event ${constants_1.EVENT_SIGNATURES.SWAP_RAW}`])
52
- },
53
- {
54
- name: "方法3:带错误处理的解析方式(新增)",
55
- parse: (log) => {
56
- try {
57
- const completeSwapDefinition = "event " + constants_1.EVENT_SIGNATURES.SWAP_RAW;
58
- const iface = new ethers_1.ethers.utils.Interface([completeSwapDefinition]);
59
- try {
60
- return iface.parseLog(log);
61
- }
62
- catch (parseError) {
63
- if (parseError.code === 'BUFFER_OVERRUN') {
64
- console.log('\x1b[33m%s\x1b[0m', `检测到BUFFER_OVERRUN错误,触发备用解析流程`);
65
- return {
66
- args: {
67
- sender: "备用解析流程",
68
- recipient: "备用解析流程",
69
- amount0: ethers_1.ethers.BigNumber.from(0),
70
- amount1: ethers_1.ethers.BigNumber.from(0),
71
- sqrtPriceX96: ethers_1.ethers.BigNumber.from(0),
72
- tick: 0,
73
- }
74
- };
75
- }
76
- throw parseError;
77
- }
78
- }
79
- catch (error) {
80
- throw error;
81
- }
82
- }
83
- }
84
- ];
85
- log('INFO', `设置原始事件监听器,只按地址过滤`);
86
- const filter = { address: poolAddress };
87
- wsProvider.on(filter, (log) => {
88
- var _a, _b, _c, _d;
89
- try {
90
- const isSwapEvent = (log.topics[0] === capturedSwapHash || log.topics[0] === updatedSwapHash);
91
- if (isSwapEvent) {
92
- console.log('\x1b[32m%s\x1b[0m', `收到Swap事件: 交易哈希=${log.transactionHash}, 区块=${log.blockNumber}`);
93
- for (const method of methods) {
94
- try {
95
- let parsedEvent;
96
- if (method.parse) {
97
- parsedEvent = method.parse(log);
98
- }
99
- else if (method.createInterface) {
100
- const iface = method.createInterface();
101
- parsedEvent = iface.parseLog(log);
102
- }
103
- else {
104
- throw new Error("方法未正确定义");
105
- }
106
- console.log('\x1b[32m%s\x1b[0m', `${method.name} - 解析成功!`);
107
- console.log({
108
- sender: parsedEvent.args.sender,
109
- recipient: parsedEvent.args.recipient,
110
- amount0: (_a = parsedEvent.args.amount0) === null || _a === void 0 ? void 0 : _a.toString(),
111
- amount1: (_b = parsedEvent.args.amount1) === null || _b === void 0 ? void 0 : _b.toString(),
112
- sqrtPriceX96: (_c = parsedEvent.args.sqrtPriceX96) === null || _c === void 0 ? void 0 : _c.toString(),
113
- tick: (_d = parsedEvent.args.tick) === null || _d === void 0 ? void 0 : _d.toString()
114
- });
115
- }
116
- catch (error) {
117
- console.log('\x1b[31m%s\x1b[0m', `${method.name} - 解析失败: ${error.message}`);
118
- console.log(error.code ? `错误代码: ${error.code}` : '无错误代码');
119
- }
120
- }
121
- console.log('----------------------------');
122
- }
123
- }
124
- catch (error) {
125
- log('ERROR', `处理事件出错:`, error);
126
- }
127
- });
128
- log('INFO', '测试脚本启动成功,等待Swap事件...');
129
- const interval = setInterval(() => __awaiter(this, void 0, void 0, function* () {
130
- try {
131
- const blockNumber = yield wsProvider.getBlockNumber();
132
- log('DEBUG', `心跳检测成功,当前区块: ${blockNumber}`);
133
- }
134
- catch (error) {
135
- log('ERROR', '心跳检测失败,可能断开连接');
136
- }
137
- }), 15000);
138
- process.on('SIGINT', () => {
139
- log('INFO', '收到退出信号,正在清理...');
140
- clearInterval(interval);
141
- wsProvider.removeAllListeners();
142
- if (wsProvider._websocket)
143
- wsProvider._websocket.close();
144
- log('INFO', '已清理,退出程序');
145
- process.exit(0);
146
- });
147
- });
148
- }
149
- function updateCurrentPoolState(wsProvider, poolAddress, poolName) {
150
- return __awaiter(this, void 0, void 0, function* () {
151
- log('INFO', `[${poolName}] 模拟备用方法:通过直接查询获取池状态`);
152
- try {
153
- const poolAbi = [
154
- "function slot0() external view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)",
155
- "function liquidity() external view returns (uint128)"
156
- ];
157
- const poolContract = new ethers_1.ethers.Contract(poolAddress, poolAbi, wsProvider);
158
- const [slot0Data, liquidityData] = yield Promise.all([
159
- poolContract.slot0(),
160
- poolContract.liquidity()
161
- ]);
162
- const [sqrtPriceX96, tick] = slot0Data;
163
- const liquidity = liquidityData;
164
- log('INFO', `[${poolName}] 备用方法成功: tick=${tick}, liquidity=${liquidity.toString()}`);
165
- return { sqrtPriceX96, tick, liquidity };
166
- }
167
- catch (error) {
168
- log('ERROR', `[${poolName}] 备用方法失败:`, error);
169
- return null;
170
- }
171
- });
172
- }
173
- verifySwapEventParsing()
174
- .then(() => log('INFO', '验证脚本启动成功'))
175
- .catch(error => {
176
- log('ERROR', '验证脚本启动失败:', error);
177
- process.exit(1);
178
- });
@@ -1 +0,0 @@
1
- export * from "./redis_client";
@@ -1,17 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./redis_client"), exports);
@@ -1,23 +0,0 @@
1
- import { RedisClientType } from "redis";
2
- export declare class SimpleRedisClient {
3
- private lock_prefix;
4
- private redisClient;
5
- private lockMaxRetries;
6
- private lockRetryDelayMs;
7
- private lockExpireSeconds;
8
- constructor(lock_prefix: string);
9
- getRedisClient(): Promise<RedisClientType>;
10
- private getLockKey;
11
- acquireLock(lock_key: string, lock_value: string, expireSeconds?: number): Promise<boolean>;
12
- releaseLock(lock_key: string, lock_value: string): Promise<boolean>;
13
- withLock<T>(lock_identifier: string, callback: () => Promise<T>, release_lock_delay_ms?: number): Promise<T>;
14
- getValue(key: string): Promise<string>;
15
- setValue(key: string, value: string, expireSeconds: number): Promise<any>;
16
- hsetValue(key: string, field: string, value: string, expireSeconds: number): Promise<any>;
17
- hgetvalue(key: string, field: string): Promise<any>;
18
- hkeys(key: string): Promise<any>;
19
- hgetall(key: string): Promise<any>;
20
- hmget(key: string, fields: string[]): Promise<(string | null)[]>;
21
- lrange(key: string, start?: number, stop?: number): Promise<string[]>;
22
- del(key: string, field?: string): Promise<any>;
23
- }