@clonegod/ttd-bsc-common 1.0.90 → 3.0.1
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.
- package/dist/config/BscQuoteAppConfig.d.ts +11 -0
- package/dist/config/BscQuoteAppConfig.js +62 -0
- package/dist/config/bsc_env_args.d.ts +1 -1
- package/dist/config/bsc_env_args.js +2 -2
- package/dist/config/index.d.ts +1 -0
- package/dist/config/index.js +1 -0
- package/dist/quote/event/index.d.ts +1 -0
- package/dist/quote/event/index.js +1 -0
- package/dist/quote/event/pool_event_listener.d.ts +1 -1
- package/dist/quote/event/pool_event_listener.js +31 -31
- package/dist/quote/event/swap_debouncer.d.ts +22 -0
- package/dist/quote/event/swap_debouncer.js +92 -0
- package/dist/quote/index.d.ts +1 -0
- package/dist/quote/index.js +1 -0
- package/dist/quote/pricing/index.d.ts +2 -0
- package/dist/quote/pricing/index.js +2 -0
- package/dist/quote/pricing/pool_state_initializer.d.ts +8 -0
- package/dist/quote/pricing/pool_state_initializer.js +142 -0
- package/dist/quote/pricing/sdk_token_factory.d.ts +2 -0
- package/dist/quote/pricing/sdk_token_factory.js +21 -0
- package/dist/quote/pricing/token_price_cache.js +4 -4
- package/dist/quote/tick/clmm_tick_cache.d.ts +40 -0
- package/dist/quote/tick/clmm_tick_cache.js +219 -0
- package/dist/quote/tick/index.d.ts +2 -0
- package/dist/{trade/send → quote/tick}/index.js +2 -8
- package/dist/quote/tick/tick_lens_loaders.d.ts +25 -0
- package/dist/quote/tick/tick_lens_loaders.js +170 -0
- package/dist/redis/redis_client.d.ts +1 -0
- package/dist/redis/redis_client.js +12 -6
- package/dist/trade/abstract_dex_trade.d.ts +31 -17
- package/dist/trade/abstract_dex_trade.js +214 -109
- package/dist/trade/caller_manager.d.ts +35 -0
- package/dist/trade/caller_manager.js +178 -0
- package/dist/trade/check/tx_websocket_manager.js +11 -11
- package/dist/trade/index.d.ts +1 -2
- package/dist/trade/index.js +1 -2
- package/dist/trade/parse/base_parser.js +2 -2
- package/dist/types/pool_state.d.ts +31 -0
- package/dist/utils/gas_helper.js +9 -9
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.js +1 -0
- package/dist/utils/trade_direction.d.ts +15 -0
- package/dist/utils/trade_direction.js +23 -0
- package/dist/ws/event_filter.js +2 -2
- package/dist/yyws/yyws_client.js +2 -2
- package/package.json +3 -2
- package/dist/trade/abstract_dex_trade_plus.d.ts +0 -44
- package/dist/trade/abstract_dex_trade_plus.js +0 -449
- package/dist/trade/send/48club.d.ts +0 -17
- package/dist/trade/send/48club.js +0 -123
- package/dist/trade/send/48club_member.d.ts +0 -1
- package/dist/trade/send/48club_member.js +0 -25
- package/dist/trade/send/48club_sp.d.ts +0 -9
- package/dist/trade/send/48club_sp.js +0 -137
- package/dist/trade/send/blockrazor.d.ts +0 -7
- package/dist/trade/send/blockrazor.js +0 -78
- package/dist/trade/send/blxr.d.ts +0 -0
- package/dist/trade/send/blxr.js +0 -0
- package/dist/trade/send/bsc_rpc.d.ts +0 -6
- package/dist/trade/send/bsc_rpc.js +0 -47
- package/dist/trade/send/index.d.ts +0 -6
- package/dist/trade/send/send_bundle_proxy.d.ts +0 -7
- package/dist/trade/send/send_bundle_proxy.js +0 -30
- package/dist/trade/send/send_bundle_ws.d.ts +0 -7
- package/dist/trade/send/send_bundle_ws.js +0 -30
- package/dist/trade/send/send_tx.d.ts +0 -9
- package/dist/trade/send/send_tx.js +0 -119
- package/dist/ws/bsc_stream_ws_client.d.ts +0 -10
- package/dist/ws/bsc_stream_ws_client.js +0 -95
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { BscEnvArgs } from "./bsc_env_args";
|
|
2
|
+
import { AppConfig } from '@clonegod/ttd-core';
|
|
3
|
+
export declare class BscQuoteAppConfig extends AppConfig {
|
|
4
|
+
private eventEmitter;
|
|
5
|
+
env_args: BscEnvArgs;
|
|
6
|
+
constructor();
|
|
7
|
+
on(eventName: string | symbol, listener: (...args: any[]) => void): this;
|
|
8
|
+
emit(eventName: string | symbol, ...args: any[]): boolean;
|
|
9
|
+
init(): Promise<void>;
|
|
10
|
+
subscribe_config_change(): Promise<void>;
|
|
11
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
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
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.BscQuoteAppConfig = void 0;
|
|
13
|
+
const bsc_env_args_1 = require("./bsc_env_args");
|
|
14
|
+
const ttd_core_1 = require("@clonegod/ttd-core");
|
|
15
|
+
const events_1 = require("events");
|
|
16
|
+
class BscQuoteAppConfig extends ttd_core_1.AppConfig {
|
|
17
|
+
constructor() {
|
|
18
|
+
super();
|
|
19
|
+
this.eventEmitter = new events_1.EventEmitter();
|
|
20
|
+
this.env_args = new bsc_env_args_1.BscEnvArgs();
|
|
21
|
+
}
|
|
22
|
+
on(eventName, listener) {
|
|
23
|
+
this.eventEmitter.on(eventName, listener);
|
|
24
|
+
return this;
|
|
25
|
+
}
|
|
26
|
+
emit(eventName, ...args) {
|
|
27
|
+
return this.eventEmitter.emit(eventName, ...args);
|
|
28
|
+
}
|
|
29
|
+
init() {
|
|
30
|
+
const _super = Object.create(null, {
|
|
31
|
+
init: { get: () => super.init }
|
|
32
|
+
});
|
|
33
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
34
|
+
yield _super.init.call(this);
|
|
35
|
+
yield this.arb_cache.init();
|
|
36
|
+
if (!this.arb_event_subscriber) {
|
|
37
|
+
this.arb_event_subscriber = (0, ttd_core_1.getArbEventSubscriber)(this.arb_cache);
|
|
38
|
+
}
|
|
39
|
+
(0, ttd_core_1.log_info)('BscQuoteAppConfig initialized', {
|
|
40
|
+
chain_id: this.env_args.chain_id,
|
|
41
|
+
dex_id: this.env_args.dex_id,
|
|
42
|
+
quote_pair: this.env_args.quote_pair,
|
|
43
|
+
rpc_endpoint: this.env_args.rpc_endpoint,
|
|
44
|
+
ws_endpoint: this.env_args.ws_endpoint,
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
subscribe_config_change() {
|
|
49
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
50
|
+
this.on('config_change', (config) => __awaiter(this, void 0, void 0, function* () {
|
|
51
|
+
(0, ttd_core_1.log_info)('Config change received', config);
|
|
52
|
+
if (config.env_args) {
|
|
53
|
+
this.env_args = new bsc_env_args_1.BscEnvArgs();
|
|
54
|
+
}
|
|
55
|
+
if (config.arb_cache) {
|
|
56
|
+
yield this.arb_cache.init();
|
|
57
|
+
}
|
|
58
|
+
}));
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
exports.BscQuoteAppConfig = BscQuoteAppConfig;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.BscEnvArgs = void 0;
|
|
4
|
-
const
|
|
4
|
+
const ttd_core_1 = require("@clonegod/ttd-core");
|
|
5
5
|
const decimal_js_1 = require("decimal.js");
|
|
6
|
-
class BscEnvArgs extends
|
|
6
|
+
class BscEnvArgs extends ttd_core_1.EnvArgs {
|
|
7
7
|
constructor() {
|
|
8
8
|
super();
|
|
9
9
|
this.large_trade_threshold_usd = parseInt(process.env.LARGE_TRADE_THRESHOLD_USD || '500');
|
package/dist/config/index.d.ts
CHANGED
package/dist/config/index.js
CHANGED
|
@@ -11,7 +11,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
12
|
exports.PoolEventListener = void 0;
|
|
13
13
|
const ethers_1 = require("ethers");
|
|
14
|
-
const
|
|
14
|
+
const ttd_core_1 = require("@clonegod/ttd-core");
|
|
15
15
|
const common_1 = require("../../common");
|
|
16
16
|
const CONFIG = {
|
|
17
17
|
MAX_RETRIES: 3,
|
|
@@ -48,37 +48,37 @@ class PoolEventListener {
|
|
|
48
48
|
return __awaiter(this, void 0, void 0, function* () {
|
|
49
49
|
this.poolList = poolList.filter(pool => ethers_1.ethers.utils.isAddress(pool.pool_address));
|
|
50
50
|
if (this.poolList.length !== poolList.length) {
|
|
51
|
-
(0,
|
|
51
|
+
(0, ttd_core_1.log_warn)(`Found ${poolList.length - this.poolList.length} invalid pool addresses, filtered out`, '');
|
|
52
52
|
}
|
|
53
53
|
yield this.connect();
|
|
54
54
|
});
|
|
55
55
|
}
|
|
56
56
|
start() {
|
|
57
57
|
return __awaiter(this, void 0, void 0, function* () {
|
|
58
|
-
(0,
|
|
58
|
+
(0, ttd_core_1.log_info)(`Starting block listener...`);
|
|
59
59
|
if (!this.isConnected || !this.wsProvider) {
|
|
60
|
-
(0,
|
|
60
|
+
(0, ttd_core_1.log_warn)('WebSocket not connected, cannot start listener', '');
|
|
61
61
|
return;
|
|
62
62
|
}
|
|
63
63
|
yield this.startBlockListener();
|
|
64
64
|
this.isStarted = true;
|
|
65
|
-
(0,
|
|
65
|
+
(0, ttd_core_1.log_info)('Block listener started successfully');
|
|
66
66
|
});
|
|
67
67
|
}
|
|
68
68
|
stop() {
|
|
69
69
|
return __awaiter(this, void 0, void 0, function* () {
|
|
70
|
-
(0,
|
|
70
|
+
(0, ttd_core_1.log_info)(`Stopping block listener...`);
|
|
71
71
|
this.stopBlockListener();
|
|
72
72
|
this.cleanup();
|
|
73
73
|
this.isStarted = false;
|
|
74
|
-
(0,
|
|
74
|
+
(0, ttd_core_1.log_info)(`Block listener stopped`);
|
|
75
75
|
});
|
|
76
76
|
}
|
|
77
77
|
connect() {
|
|
78
78
|
return __awaiter(this, void 0, void 0, function* () {
|
|
79
79
|
for (let i = 0; i < CONFIG.MAX_RETRIES; i++) {
|
|
80
80
|
try {
|
|
81
|
-
(0,
|
|
81
|
+
(0, ttd_core_1.log_info)(`Connecting to WebSocket: ${this.ws_endpoint} (Attempt ${i + 1}/${CONFIG.MAX_RETRIES})`);
|
|
82
82
|
this.wsProvider = new ethers_1.ethers.providers.WebSocketProvider(this.ws_endpoint);
|
|
83
83
|
const wsPromise = this.wsProvider.ready;
|
|
84
84
|
const timeoutPromise = new Promise((_, reject) => {
|
|
@@ -87,7 +87,7 @@ class PoolEventListener {
|
|
|
87
87
|
yield Promise.race([wsPromise, timeoutPromise]);
|
|
88
88
|
this.isConnected = true;
|
|
89
89
|
this.reconnectAttempts = 0;
|
|
90
|
-
(0,
|
|
90
|
+
(0, ttd_core_1.log_info)(`WebSocket connected: ${this.ws_endpoint}`);
|
|
91
91
|
this.setupWebSocketListeners();
|
|
92
92
|
if (this.isStarted) {
|
|
93
93
|
yield this.startBlockListener();
|
|
@@ -95,12 +95,12 @@ class PoolEventListener {
|
|
|
95
95
|
return;
|
|
96
96
|
}
|
|
97
97
|
catch (error) {
|
|
98
|
-
(0,
|
|
98
|
+
(0, ttd_core_1.log_error)(`WebSocket connection failed (Attempt ${i + 1}/${CONFIG.MAX_RETRIES}):`, error);
|
|
99
99
|
if (i === CONFIG.MAX_RETRIES - 1) {
|
|
100
100
|
throw error;
|
|
101
101
|
}
|
|
102
102
|
const delay = CONFIG.RETRY_DELAY_MULTIPLIER * (i + 1);
|
|
103
|
-
(0,
|
|
103
|
+
(0, ttd_core_1.log_info)(`Waiting ${delay / 1000} seconds before retry...`);
|
|
104
104
|
yield new Promise(resolve => setTimeout(resolve, delay));
|
|
105
105
|
}
|
|
106
106
|
}
|
|
@@ -110,15 +110,15 @@ class PoolEventListener {
|
|
|
110
110
|
if (!this.wsProvider)
|
|
111
111
|
return;
|
|
112
112
|
this.wsProvider.on('error', (err) => {
|
|
113
|
-
(0,
|
|
113
|
+
(0, ttd_core_1.log_error)(`WebSocket error:`, err, '');
|
|
114
114
|
this.handleConnectionIssue();
|
|
115
115
|
});
|
|
116
116
|
this.wsProvider._websocket.on('close', (code, reason) => {
|
|
117
|
-
(0,
|
|
117
|
+
(0, ttd_core_1.log_warn)(`WebSocket connection closed, code: ${code}, reason: ${reason || 'unknown'}`);
|
|
118
118
|
this.handleConnectionIssue();
|
|
119
119
|
});
|
|
120
120
|
this.wsProvider._websocket.on('open', () => {
|
|
121
|
-
(0,
|
|
121
|
+
(0, ttd_core_1.log_info)('WebSocket connection opened');
|
|
122
122
|
this.isConnected = true;
|
|
123
123
|
this.reconnectAttempts = 0;
|
|
124
124
|
});
|
|
@@ -138,12 +138,12 @@ class PoolEventListener {
|
|
|
138
138
|
this.lastHeartbeatResponse = Date.now();
|
|
139
139
|
const timeSinceLastHeartbeat = Date.now() - this.lastHeartbeatResponse;
|
|
140
140
|
if (timeSinceLastHeartbeat > CONFIG.HEARTBEAT_TIMEOUT) {
|
|
141
|
-
(0,
|
|
141
|
+
(0, ttd_core_1.log_warn)(`No heartbeat response for ${timeSinceLastHeartbeat / 1000} seconds`);
|
|
142
142
|
this.handleConnectionIssue();
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
145
|
catch (error) {
|
|
146
|
-
(0,
|
|
146
|
+
(0, ttd_core_1.log_error)('Heartbeat check failed:', error);
|
|
147
147
|
this.handleConnectionIssue();
|
|
148
148
|
}
|
|
149
149
|
}), CONFIG.HEARTBEAT_INTERVAL);
|
|
@@ -151,7 +151,7 @@ class PoolEventListener {
|
|
|
151
151
|
handleConnectionIssue() {
|
|
152
152
|
return __awaiter(this, void 0, void 0, function* () {
|
|
153
153
|
if (this.isReconnecting) {
|
|
154
|
-
(0,
|
|
154
|
+
(0, ttd_core_1.log_info)('Already attempting to reconnect, skipping...');
|
|
155
155
|
return;
|
|
156
156
|
}
|
|
157
157
|
this.isReconnecting = true;
|
|
@@ -161,20 +161,20 @@ class PoolEventListener {
|
|
|
161
161
|
this.cleanup();
|
|
162
162
|
this.reconnectAttempts++;
|
|
163
163
|
const delay = Math.min(CONFIG.BASE_RECONNECT_DELAY * Math.pow(2, this.reconnectAttempts), CONFIG.MAX_RECONNECT_DELAY);
|
|
164
|
-
(0,
|
|
164
|
+
(0, ttd_core_1.log_info)(`Attempting to reconnect ${this.reconnectAttempts}/${CONFIG.MAX_RECONNECT_ATTEMPTS}, delay ${delay}ms, node: ${this.ws_endpoint}`);
|
|
165
165
|
if (this.reconnectAttempts > CONFIG.MAX_RECONNECT_ATTEMPTS) {
|
|
166
|
-
(0,
|
|
166
|
+
(0, ttd_core_1.log_error)(`Reconnection failed, reached maximum attempts (${CONFIG.MAX_RECONNECT_ATTEMPTS}), exiting`, new Error('Max reconnect attempts failed'), '');
|
|
167
167
|
this.appConfig.emit(common_1.EVENT_NAMES.WS_CONNECTION_FAILED, {
|
|
168
168
|
endpoint: this.ws_endpoint,
|
|
169
169
|
attempts: CONFIG.MAX_RECONNECT_ATTEMPTS,
|
|
170
170
|
});
|
|
171
171
|
process.exit(1);
|
|
172
172
|
}
|
|
173
|
-
yield (0,
|
|
173
|
+
yield (0, ttd_core_1.sleep)(delay);
|
|
174
174
|
yield this.connect();
|
|
175
175
|
}
|
|
176
176
|
catch (error) {
|
|
177
|
-
(0,
|
|
177
|
+
(0, ttd_core_1.log_error)('Reconnection attempt failed:', error);
|
|
178
178
|
setTimeout(() => this.handleConnectionIssue(), CONFIG.BASE_RECONNECT_DELAY);
|
|
179
179
|
}
|
|
180
180
|
finally {
|
|
@@ -185,19 +185,19 @@ class PoolEventListener {
|
|
|
185
185
|
startBlockListener() {
|
|
186
186
|
return __awaiter(this, void 0, void 0, function* () {
|
|
187
187
|
if (!this.wsProvider || !this.isConnected) {
|
|
188
|
-
(0,
|
|
188
|
+
(0, ttd_core_1.log_warn)(`Cannot start block listener: WebSocket not connected`);
|
|
189
189
|
return;
|
|
190
190
|
}
|
|
191
191
|
try {
|
|
192
192
|
const blockNumber = yield this.wsProvider.getBlockNumber();
|
|
193
193
|
this.lastProcessedBlockNumber = blockNumber;
|
|
194
|
-
(0,
|
|
194
|
+
(0, ttd_core_1.log_info)(`Initializing block listener, current block: ${blockNumber}`);
|
|
195
195
|
this.wsProvider.on('block', (blockNumber) => __awaiter(this, void 0, void 0, function* () {
|
|
196
196
|
try {
|
|
197
197
|
if (!this.isConnected || !this.isBlockListenerActive)
|
|
198
198
|
return;
|
|
199
199
|
this.lastMessageTime = Date.now();
|
|
200
|
-
(0,
|
|
200
|
+
(0, ttd_core_1.log_info)(`------- Block: ${blockNumber} -------`);
|
|
201
201
|
const previousBlockNumber = this.lastProcessedBlockNumber;
|
|
202
202
|
this.lastProcessedBlockNumber = blockNumber;
|
|
203
203
|
const blockUpdateEvent = {
|
|
@@ -208,16 +208,16 @@ class PoolEventListener {
|
|
|
208
208
|
this.appConfig.emit(common_1.EVENT_NAMES.BLOCK_UPDATE, blockUpdateEvent);
|
|
209
209
|
}
|
|
210
210
|
catch (error) {
|
|
211
|
-
(0,
|
|
211
|
+
(0, ttd_core_1.log_error)(`Error processing block event:`, error, '');
|
|
212
212
|
}
|
|
213
213
|
}));
|
|
214
214
|
this.startMessageMonitor();
|
|
215
215
|
this.startDiagnosticMonitor();
|
|
216
216
|
this.isBlockListenerActive = true;
|
|
217
|
-
(0,
|
|
217
|
+
(0, ttd_core_1.log_info)(`Block listener started using WebSocket event subscription`);
|
|
218
218
|
}
|
|
219
219
|
catch (error) {
|
|
220
|
-
(0,
|
|
220
|
+
(0, ttd_core_1.log_error)(`Failed to start block listener:`, error, '');
|
|
221
221
|
this.isBlockListenerActive = false;
|
|
222
222
|
}
|
|
223
223
|
});
|
|
@@ -229,7 +229,7 @@ class PoolEventListener {
|
|
|
229
229
|
this.messageMonitorInterval = setInterval(() => {
|
|
230
230
|
const timeSinceLastMessage = Date.now() - this.lastMessageTime;
|
|
231
231
|
if (timeSinceLastMessage > CONFIG.MESSAGE_TIMEOUT) {
|
|
232
|
-
(0,
|
|
232
|
+
(0, ttd_core_1.log_warn)(`No messages received for ${CONFIG.MESSAGE_TIMEOUT / 1000} seconds, preparing to resubscribe`);
|
|
233
233
|
this.handleConnectionIssue();
|
|
234
234
|
}
|
|
235
235
|
}, CONFIG.MESSAGE_CHECK_INTERVAL);
|
|
@@ -244,7 +244,7 @@ class PoolEventListener {
|
|
|
244
244
|
}, CONFIG.DIAGNOSTIC_INTERVAL);
|
|
245
245
|
}
|
|
246
246
|
logDiagnostics(diagnostics) {
|
|
247
|
-
(0,
|
|
247
|
+
(0, ttd_core_1.log_info)(`WebSocket Connection Diagnostics:
|
|
248
248
|
Connection Status: ${diagnostics.isConnected ? 'Connected' : 'Disconnected'}
|
|
249
249
|
Reconnection Status: ${diagnostics.isReconnecting ? 'Reconnecting' : 'Not Reconnecting'}
|
|
250
250
|
Listener Status: ${diagnostics.isStarted ? 'Started' : 'Not Started'}
|
|
@@ -279,7 +279,7 @@ class PoolEventListener {
|
|
|
279
279
|
clearInterval(this.diagnosticInterval);
|
|
280
280
|
this.diagnosticInterval = null;
|
|
281
281
|
}
|
|
282
|
-
(0,
|
|
282
|
+
(0, ttd_core_1.log_info)(`Block listener stopped`);
|
|
283
283
|
}
|
|
284
284
|
}
|
|
285
285
|
cleanup() {
|
|
@@ -291,7 +291,7 @@ class PoolEventListener {
|
|
|
291
291
|
}
|
|
292
292
|
}
|
|
293
293
|
catch (error) {
|
|
294
|
-
(0,
|
|
294
|
+
(0, ttd_core_1.log_error)(`Failed to cleanup WebSocket resources:`, error, '');
|
|
295
295
|
}
|
|
296
296
|
this.wsProvider = null;
|
|
297
297
|
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export declare class SwapDebouncer<TEvent extends {
|
|
2
|
+
pool_address: string;
|
|
3
|
+
type: string;
|
|
4
|
+
data: {
|
|
5
|
+
blockNumber: number;
|
|
6
|
+
};
|
|
7
|
+
}, TResult = void> {
|
|
8
|
+
private debounceMs;
|
|
9
|
+
private onCalculate;
|
|
10
|
+
private onPublish;
|
|
11
|
+
private debouncedTypes;
|
|
12
|
+
private windows;
|
|
13
|
+
private latestBlock;
|
|
14
|
+
constructor(config: {
|
|
15
|
+
onCalculate: (event: TEvent) => TResult | Promise<TResult>;
|
|
16
|
+
onPublish: (event: TEvent, result: TResult) => void;
|
|
17
|
+
debouncedEventTypes?: string[];
|
|
18
|
+
});
|
|
19
|
+
onEvent(event: TEvent): Promise<void>;
|
|
20
|
+
flush(): void;
|
|
21
|
+
private startWindow;
|
|
22
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
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
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.SwapDebouncer = void 0;
|
|
13
|
+
const ttd_core_1 = require("@clonegod/ttd-core");
|
|
14
|
+
class SwapDebouncer {
|
|
15
|
+
constructor(config) {
|
|
16
|
+
this.windows = new Map();
|
|
17
|
+
this.latestBlock = new Map();
|
|
18
|
+
this.debounceMs = parseInt(process.env.SWAP_DEBOUNCE_MS || '3', 10);
|
|
19
|
+
this.onCalculate = config.onCalculate;
|
|
20
|
+
this.onPublish = config.onPublish;
|
|
21
|
+
this.debouncedTypes = new Set((config.debouncedEventTypes || ['swap']).map(t => t.toLowerCase()));
|
|
22
|
+
}
|
|
23
|
+
onEvent(event) {
|
|
24
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
25
|
+
var _a, _b;
|
|
26
|
+
const poolAddress = event.pool_address;
|
|
27
|
+
const blockNumber = ((_a = event.data) === null || _a === void 0 ? void 0 : _a.blockNumber) || 0;
|
|
28
|
+
if (blockNumber > 0) {
|
|
29
|
+
const lastBlock = this.latestBlock.get(poolAddress) || 0;
|
|
30
|
+
if (blockNumber < lastBlock) {
|
|
31
|
+
(0, ttd_core_1.log_warn)(`SwapDebouncer: stale block dropped, pool=${poolAddress}, event block=${blockNumber}, latest=${lastBlock}`);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
this.latestBlock.set(poolAddress, blockNumber);
|
|
35
|
+
}
|
|
36
|
+
const eventType = (_b = event.type) === null || _b === void 0 ? void 0 : _b.toLowerCase();
|
|
37
|
+
if (!this.debouncedTypes.has(eventType)) {
|
|
38
|
+
const result = yield this.onCalculate(event);
|
|
39
|
+
this.onPublish(event, result);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const window = this.windows.get(poolAddress);
|
|
43
|
+
const result = yield this.onCalculate(event);
|
|
44
|
+
if (window) {
|
|
45
|
+
if (blockNumber > window.blockNumber) {
|
|
46
|
+
if (!window.expired) {
|
|
47
|
+
clearTimeout(window.timer);
|
|
48
|
+
this.onPublish(window.latestEvent, window.latestResult);
|
|
49
|
+
}
|
|
50
|
+
this.windows.delete(poolAddress);
|
|
51
|
+
this.startWindow(poolAddress, event, result, blockNumber);
|
|
52
|
+
}
|
|
53
|
+
else if (window.expired) {
|
|
54
|
+
this.onPublish(event, result);
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
window.latestEvent = event;
|
|
58
|
+
window.latestResult = result;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
this.startWindow(poolAddress, event, result, blockNumber);
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
flush() {
|
|
67
|
+
for (const [_, window] of this.windows) {
|
|
68
|
+
if (!window.expired) {
|
|
69
|
+
clearTimeout(window.timer);
|
|
70
|
+
this.onPublish(window.latestEvent, window.latestResult);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
this.windows.clear();
|
|
74
|
+
}
|
|
75
|
+
startWindow(poolAddress, event, result, blockNumber) {
|
|
76
|
+
const timer = setTimeout(() => {
|
|
77
|
+
const w = this.windows.get(poolAddress);
|
|
78
|
+
if (w) {
|
|
79
|
+
w.expired = true;
|
|
80
|
+
this.onPublish(w.latestEvent, w.latestResult);
|
|
81
|
+
}
|
|
82
|
+
}, this.debounceMs);
|
|
83
|
+
this.windows.set(poolAddress, {
|
|
84
|
+
blockNumber,
|
|
85
|
+
latestEvent: event,
|
|
86
|
+
latestResult: result,
|
|
87
|
+
timer,
|
|
88
|
+
expired: false,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
exports.SwapDebouncer = SwapDebouncer;
|
package/dist/quote/index.d.ts
CHANGED
package/dist/quote/index.js
CHANGED
|
@@ -16,3 +16,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
__exportStar(require("./event"), exports);
|
|
18
18
|
__exportStar(require("./pricing"), exports);
|
|
19
|
+
__exportStar(require("./tick"), exports);
|
|
@@ -16,3 +16,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
__exportStar(require("./token_price_cache"), exports);
|
|
18
18
|
__exportStar(require("./pool"), exports);
|
|
19
|
+
__exportStar(require("./sdk_token_factory"), exports);
|
|
20
|
+
__exportStar(require("./pool_state_initializer"), exports);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { AmmPoolState, ClmmPoolState, InfinityPoolState } from "../../types/pool_state";
|
|
2
|
+
export declare class PoolStateInitializer {
|
|
3
|
+
static initAmmPool(provider: any, poolAddress: string, dexId: string, ethersLib: any): Promise<AmmPoolState>;
|
|
4
|
+
static initClmmPool(provider: any, poolAddress: string, ethersLib: any, poolAbi?: any[]): Promise<ClmmPoolState>;
|
|
5
|
+
static initInfinityPool(provider: any, poolKey: string, poolManagerAddress: string, poolManagerAbi: any, ethersLib: any, decodeParameters: (params: string) => {
|
|
6
|
+
tickSpacing: number;
|
|
7
|
+
}): Promise<InfinityPoolState>;
|
|
8
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
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
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.PoolStateInitializer = void 0;
|
|
13
|
+
const ttd_core_1 = require("@clonegod/ttd-core");
|
|
14
|
+
const V2_PAIR_ABI = [
|
|
15
|
+
'function token0() view returns (address)',
|
|
16
|
+
'function token1() view returns (address)',
|
|
17
|
+
'function getReserves() view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast)',
|
|
18
|
+
];
|
|
19
|
+
const V3_POOL_ABI = [
|
|
20
|
+
'function token0() view returns (address)',
|
|
21
|
+
'function token1() view returns (address)',
|
|
22
|
+
'function fee() view returns (uint24)',
|
|
23
|
+
'function tickSpacing() view returns (int24)',
|
|
24
|
+
'function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)',
|
|
25
|
+
'function liquidity() view returns (uint128)',
|
|
26
|
+
];
|
|
27
|
+
const AMM_FEE_MAP = {
|
|
28
|
+
'PANCAKE-AMM': 25,
|
|
29
|
+
'PANCAKE_AMM': 25,
|
|
30
|
+
'UNISWAP-AMM': 30,
|
|
31
|
+
'UNISWAP_AMM': 30,
|
|
32
|
+
};
|
|
33
|
+
class PoolStateInitializer {
|
|
34
|
+
static initAmmPool(provider, poolAddress, dexId, ethersLib) {
|
|
35
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
36
|
+
try {
|
|
37
|
+
const poolContract = new ethersLib.Contract(poolAddress, V2_PAIR_ABI, provider);
|
|
38
|
+
const [reserves, token0, token1] = yield Promise.all([
|
|
39
|
+
poolContract.getReserves(),
|
|
40
|
+
poolContract.token0(),
|
|
41
|
+
poolContract.token1(),
|
|
42
|
+
]);
|
|
43
|
+
const fee = AMM_FEE_MAP[dexId] || AMM_FEE_MAP[dexId.replace('-', '_')] || 30;
|
|
44
|
+
const state = {
|
|
45
|
+
address: poolAddress,
|
|
46
|
+
token0: token0.toLowerCase(),
|
|
47
|
+
token1: token1.toLowerCase(),
|
|
48
|
+
fee,
|
|
49
|
+
reserve0: reserves[0].toString(),
|
|
50
|
+
reserve1: reserves[1].toString(),
|
|
51
|
+
};
|
|
52
|
+
(0, ttd_core_1.log_info)(`[PoolStateInitializer] AMM pool initialized: ${poolAddress}`, {
|
|
53
|
+
token0: state.token0, token1: state.token1, fee: state.fee,
|
|
54
|
+
});
|
|
55
|
+
return state;
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
(0, ttd_core_1.log_error)(`[PoolStateInitializer] Failed to init AMM pool ${poolAddress}:`, error);
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
static initClmmPool(provider, poolAddress, ethersLib, poolAbi) {
|
|
64
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
65
|
+
try {
|
|
66
|
+
const abi = poolAbi || V3_POOL_ABI;
|
|
67
|
+
const poolContract = new ethersLib.Contract(poolAddress, abi, provider);
|
|
68
|
+
const [token0, token1, fee, tickSpacing, slot0, liquidity] = yield Promise.all([
|
|
69
|
+
poolContract.token0(),
|
|
70
|
+
poolContract.token1(),
|
|
71
|
+
poolContract.fee(),
|
|
72
|
+
poolContract.tickSpacing(),
|
|
73
|
+
poolContract.slot0(),
|
|
74
|
+
poolContract.liquidity(),
|
|
75
|
+
]);
|
|
76
|
+
const [sqrtPriceX96, tick] = slot0;
|
|
77
|
+
const state = {
|
|
78
|
+
address: poolAddress,
|
|
79
|
+
token0: token0.toLowerCase(),
|
|
80
|
+
token1: token1.toLowerCase(),
|
|
81
|
+
fee: Number(fee),
|
|
82
|
+
tickSpacing: Number(tickSpacing),
|
|
83
|
+
tick: Number(tick),
|
|
84
|
+
sqrtPriceX96: sqrtPriceX96.toString(),
|
|
85
|
+
liquidity: liquidity.toString(),
|
|
86
|
+
};
|
|
87
|
+
(0, ttd_core_1.log_info)(`[PoolStateInitializer] CLMM pool initialized: ${poolAddress}`, {
|
|
88
|
+
token0: state.token0, token1: state.token1,
|
|
89
|
+
fee: state.fee, tickSpacing: state.tickSpacing, tick: state.tick,
|
|
90
|
+
});
|
|
91
|
+
return state;
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
(0, ttd_core_1.log_error)(`[PoolStateInitializer] Failed to init CLMM pool ${poolAddress}:`, error);
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
static initInfinityPool(provider, poolKey, poolManagerAddress, poolManagerAbi, ethersLib, decodeParameters) {
|
|
100
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
101
|
+
try {
|
|
102
|
+
const poolManagerContract = new ethersLib.Contract(poolManagerAddress, poolManagerAbi, provider);
|
|
103
|
+
const [slot0Result, liquidity, poolKeyInfo] = yield Promise.all([
|
|
104
|
+
poolManagerContract.getSlot0(poolKey),
|
|
105
|
+
poolManagerContract.getLiquidity(poolKey),
|
|
106
|
+
poolManagerContract.poolIdToPoolKey(poolKey),
|
|
107
|
+
]);
|
|
108
|
+
const [sqrtPriceX96, tick, protocolFee, lpFee] = slot0Result;
|
|
109
|
+
const [currency0, currency1, hooks, poolManager, fee, parameters] = poolKeyInfo;
|
|
110
|
+
const { tickSpacing } = decodeParameters(parameters);
|
|
111
|
+
const state = {
|
|
112
|
+
address: poolKey,
|
|
113
|
+
token0: currency0.toLowerCase ? currency0.toLowerCase() : currency0,
|
|
114
|
+
token1: currency1.toLowerCase ? currency1.toLowerCase() : currency1,
|
|
115
|
+
fee: Number(fee),
|
|
116
|
+
tickSpacing,
|
|
117
|
+
tick: Number(tick),
|
|
118
|
+
sqrtPriceX96: sqrtPriceX96.toString(),
|
|
119
|
+
liquidity: liquidity.toString(),
|
|
120
|
+
hooks,
|
|
121
|
+
poolManager,
|
|
122
|
+
parameters,
|
|
123
|
+
currency0,
|
|
124
|
+
currency1,
|
|
125
|
+
lpFee: Number(lpFee),
|
|
126
|
+
protocolFee: Number(protocolFee),
|
|
127
|
+
};
|
|
128
|
+
(0, ttd_core_1.log_info)(`[PoolStateInitializer] Infinity pool initialized: ${poolKey}`, {
|
|
129
|
+
currency0: state.currency0, currency1: state.currency1,
|
|
130
|
+
fee: state.fee, tickSpacing: state.tickSpacing, tick: state.tick,
|
|
131
|
+
lpFee: state.lpFee, protocolFee: state.protocolFee,
|
|
132
|
+
});
|
|
133
|
+
return state;
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
(0, ttd_core_1.log_error)(`[PoolStateInitializer] Failed to init Infinity pool ${poolKey}:`, error);
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
exports.PoolStateInitializer = PoolStateInitializer;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { StandardPoolInfoType } from "@clonegod/ttd-core";
|
|
2
|
+
export declare function buildSdkTokenMap<T>(chainId: number, poolInfoMap: Map<string, StandardPoolInfoType>, TokenClass: new (chainId: number, address: string, decimals: number, symbol?: string, name?: string) => T): Map<string, T>;
|