-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
278 lines (241 loc) · 9.25 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
const { ethers } = require("ethers");
const fs = require('fs');
const axios = require('axios');
const HttpsProxyAgent = require('https-proxy-agent');
const SocksProxyAgent = require('socks-proxy-agent');
// 颜色输出函数
const colorize = {
green: (text) => `\x1b[32m${text}\x1b[0m`,
red: (text) => `\x1b[31m${text}\x1b[0m`,
yellow: (text) => `\x1b[33m${text}\x1b[0m`,
blue: (text) => `\x1b[34m${text}\x1b[0m`,
cyan: (text) => `\x1b[36m${text}\x1b[0m`,
magenta: (text) => `\x1b[35m${text}\x1b[0m`,
white: (text) => `\x1b[37m${text}\x1b[0m`,
};
// 日志函数
const logger = {
info: (message) => console.log(colorize.blue(message)),
success: (message) => console.log(colorize.green(message)),
error: (message) => console.log(colorize.red(message)),
warning: (message) => console.log(colorize.yellow(message)),
tx: (message) => console.log(colorize.cyan(message)),
};
// 睡眠函数
const sleep = (minutes) => new Promise(resolve => setTimeout(resolve, minutes * 60 * 1000));
// 倒计时显示
async function countdown(minutes) {
const totalSeconds = minutes * 60;
for (let i = totalSeconds; i > 0; i--) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
const mins = Math.floor(i / 60);
const secs = i % 60;
process.stdout.write(`下一轮交易倒计时: ${mins}分${secs}秒`);
await new Promise(resolve => setTimeout(resolve, 1000));
}
console.log('\n');
}
// 读取钱包配置
function getWallets() {
try {
const content = fs.readFileSync('token.txt', 'utf-8');
const wallets = content
.split('\n')
.map(line => line.trim())
.filter(Boolean)
.map((line, index) => {
const [privateKey, walletAddress] = line.split(',').map(s => s.trim());
if (!privateKey || !walletAddress) {
logger.warning(`第 ${index + 1} 行格式不正确: ${line}`);
return null;
}
return { privateKey, walletAddress };
})
.filter(wallet => wallet !== null);
logger.info(`成功加载 ${wallets.length} 个钱包`);
return wallets;
} catch (error) {
logger.error('读取钱包文件失败:', error.message);
process.exit(1);
}
}
// 读取代理配置
function getProxies() {
try {
const proxies = fs.readFileSync('proxy.txt', 'utf-8')
.split('\n')
.map(line => line.trim())
.filter(Boolean);
logger.info(`成功加载 ${proxies.length} 个代理`);
return proxies;
} catch (error) {
logger.warning('未找到代理文件或读取失败,将使用直连模式');
return [];
}
}
// 添加重试函数
async function withRetry(fn, maxAttempts = 3, delaySeconds = 5) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt === maxAttempts) throw error;
logger.warning(`尝试第 ${attempt} 次失败,${delaySeconds} 秒后重试...`);
await new Promise(resolve => setTimeout(resolve, delaySeconds * 1000));
}
}
}
// 创建Provider
function createProvider(proxy) {
const providerUrl = "https://rpc-testnet.inichain.com";
let agent;
if (proxy) {
if (proxy.startsWith('http://') || proxy.startsWith('https://')) {
agent = new HttpsProxyAgent(proxy);
} else if (proxy.startsWith('socks5://')) {
agent = new SocksProxyAgent(proxy);
}
}
const provider = new ethers.JsonRpcProvider(providerUrl, undefined, {
timeout: 30000, // 增加超时时间到 30 秒
});
if (agent) {
provider.send = async (method, params) => {
return await withRetry(async () => {
const response = await axios.post(providerUrl, {
jsonrpc: "2.0",
id: 1,
method,
params
}, {
httpsAgent: agent,
timeout: 30000
});
return response.data.result;
});
};
}
return provider;
}
// 处理单个钱包的交易
async function processSingleWallet(wallet, proxy, index, routerAddress, path, swapAmount) {
return await withRetry(async () => {
try {
const provider = createProvider(proxy);
const signer = new ethers.Wallet(wallet.privateKey, provider);
const abi = [
"function swapExactETHForTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable",
"function getAmountsOut(uint256 amountIn, address[] path) view returns (uint256[] amounts)"
];
const contract = new ethers.Contract(routerAddress, abi, signer);
logger.info(`钱包 ${index + 1}: ${wallet.walletAddress}`);
logger.info(`代理状态: ${proxy ? colorize.magenta(proxy) : "直连模式"}`);
// 获取gas价格
const feeData = await provider.getFeeData();
const gasPrice = feeData.gasPrice;
// 准备交易参数
const swapAmountWei = ethers.parseEther(swapAmount);
const deadline = Math.floor(Date.now() / 1000) + 60 * 20;
const txParams = {
value: swapAmountWei,
gasLimit: 300000n
};
// 发送交易
const tx = await contract.swapExactETHForTokens(
0, // amountOutMin
path,
wallet.walletAddress,
deadline,
txParams
);
logger.tx(`钱包 ${index + 1} 交易哈希: ${tx.hash}`);
logger.info(`Gas Price: ${ethers.formatUnits(gasPrice, 'gwei')} Gwei`);
const receipt = await tx.wait();
logger.success(`钱包 ${index + 1} 交易成功 (Gas Used: ${receipt.gasUsed})`);
return {
success: true,
wallet: wallet.walletAddress,
hash: tx.hash
};
} catch (error) {
logger.error(`钱包 ${index + 1} 交易失败: ${error.message}`);
return {
success: false,
wallet: wallet.walletAddress,
error: error.message
};
}
});
}
// 计算距离下一个零点的时间间隔
function getTimeUntilMidnight() {
const now = new Date();
const nextMidnight = new Date(now);
nextMidnight.setHours(24, 0, 0, 0); // 设置为第二天零点
return nextMidnight.getTime() - now.getTime();
}
// 每天零点重置
function resetAtMidnight() {
const timeUntilMidnight = getTimeUntilMidnight();
setTimeout(() => {
logger.info("到了零点,开始重置...");
// 这里你可以进行重置操作,例如重新开始交易等
main(); // 重新执行主函数或其他重置操作
resetAtMidnight(); // 继续在未来的零点时刻执行此操作
}, timeUntilMidnight);
}
// 主函数
async function main() {
const wallets = getWallets();
const proxies = getProxies();
if (wallets.length === 0) {
logger.error('没有找到有效的钱包配置');
process.exit(1);
}
// 配置参数
const TOTAL_ROUNDS = 144; // 总轮数
const DELAY_MINUTES = 11; // 轮次间隔
const SWAP_AMOUNT = "0.0001"; // 交易数量
const routerAddress = "0x4ccB784744969D9B63C15cF07E622DDA65A88Ee7";
const path = [
"0xfbecae21c91446f9c7b87e4e5869926998f99ffe", // Token in
"0xcf259bca0315c6d32e877793b6a10e97e7647fde" // Token out
];
// 开始循环交易
for (let round = 0; round < TOTAL_ROUNDS; round++) {
const currentTime = new Date().toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
});
logger.info(`\n当前时间: ${currentTime}`);
logger.info(`执行第 ${round + 1}/${TOTAL_ROUNDS} 轮交易\n`);
// 并发处理所有钱包的交易
const transactions = wallets.map((wallet, index) => {
// 获取对应的代理(如果没有代理,使用 null 代表直连)
const proxy = proxies[index] || null;
return processSingleWallet(wallet, proxy, index, routerAddress, path, SWAP_AMOUNT);
});
// 等待所有交易完成
const results = await Promise.all(transactions);
// 显示交易统计
const successful = results.filter(r => r.success).length;
const failed = results.filter(r => !r.success).length;
logger.info(`成功交易: ${successful},失败交易: ${failed}`);
// 每轮结束后休息指定时间
if (round < TOTAL_ROUNDS - 1) {
logger.info(`等待 ${DELAY_MINUTES} 分钟,进入下一轮`);
await countdown(DELAY_MINUTES);
}
}
}
// 执行主函数并设置每天零点重置
main().catch(error => {
logger.error(`程序出错: ${error.message}`);
});
resetAtMidnight(); // 每天零点进行重置