-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
617 lines (556 loc) · 18.2 KB
/
main.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
const fs = require("fs");
const path = require("path");
const axios = require("axios");
const { Web3 } = require("web3");
const { logger } = require("./config/logger");
const displayBanner = require("./config/banner");
const ProxyHandler = require('./config/proxy-handler');
const CountdownTimer = require("./config/countdown");
const { ColorTheme } = require("./config/colors");
// Initialize utilities
const colors = new ColorTheme();
const timer = new CountdownTimer();
// Constants
const CONSTANTS = {
CONTRACT_ADDRESS: "0xa18f6FCB2Fd4884436d10610E69DB7BFa1bFe8C7", // Masked
BRIDGE_CONTRACT: "0x5F7CaE7D1eFC8cC05da97D988cFFC253ce3273eF", // Masked
RPC_URL: "https://rpc.testnet.humanity.org/", // Masked
MIN_GAS_PRICE: "1000000000",
MAX_GAS_PRICE: "50000000000", // 50 gwei
FAUCET_URL: "https://faucet.testnet.humanity.org/api/claim", // Masked
BRIDGE_AMOUNT: "1000000000000000000", // 1 ETH in wei
MIN_BALANCE_FOR_REWARD: 0.001,
MIN_BALANCE_FOR_BRIDGE: 1.1,
DEFAULT_GAS_LIMIT: "300000",
GAS_PRICE_MULTIPLIER: 1.2,
GAS_LIMIT_MULTIPLIER: 1.2,
WAIT_BETWEEN_WALLETS: 3000, // 3 seconds
WAIT_BETWEEN_ROUNDS: 24 * 60 * 60, // 24 hours
RETRY_ATTEMPTS: 3,
RETRY_DELAY: 1000,
MAX_PRIORITY_FEE: "2000000000", // 2 gwei
TRANSACTION_TIMEOUT: 180000, // 3 minutes in milliseconds
};
// Contract ABIs
const CONTRACT_ABI = [
{
inputs: [],
name: "claimReward",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
];
const BRIDGE_ABI = [
{
inputs: [
{ internalType: "uint32", name: "destinationNetwork", type: "uint32" },
{ internalType: "address", name: "destinationAddress", type: "address" },
{ internalType: "uint256", name: "amount", type: "uint256" },
{ internalType: "address", name: "token", type: "address" },
{ internalType: "bool", name: "forceUpdateGlobalExitRoot", type: "bool" },
{ internalType: "bytes", name: "permitData", type: "bytes" },
],
name: "bridgeAsset",
outputs: [],
stateMutability: "payable",
type: "function",
},
];
class HumanityClient {
constructor() {
this.proxyHandler = new ProxyHandler();
this.proxyHandler.loadProxies();
this.initializeWeb3();
this.initializeHeaders();
}
async retryOperation(operation, maxAttempts = CONSTANTS.RETRY_ATTEMPTS, delay = CONSTANTS.RETRY_DELAY) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await operation();
} catch (error) {
if (attempt === maxAttempts) throw error;
await new Promise(resolve => setTimeout(resolve, delay * attempt));
}
}
}
async getNonceWithRetry(address) {
return this.retryOperation(async () => {
const nonce = await this.web3.eth.getTransactionCount(address, 'pending');
return nonce;
});
}
async hasEnoughBalanceForGas(address, gasLimit, gasPrice) {
const balance = await this.getBalance(address);
const gasCost = this.web3.utils.toBN(gasLimit).mul(this.web3.utils.toBN(gasPrice));
const balanceWei = this.web3.utils.toWei(balance, 'ether');
return this.web3.utils.toBN(balanceWei).gte(gasCost);
}
initializeWeb3() {
const proxy = this.proxyHandler.getCurrentProxy();
const proxyUrl = this.proxyHandler.getWeb3ProxyConfig(proxy);
const provider = new Web3.providers.HttpProvider(CONSTANTS.RPC_URL, {
proxy: proxyUrl
});
this.web3 = new Web3(provider);
this.contract = new this.web3.eth.Contract(
CONTRACT_ABI,
CONSTANTS.CONTRACT_ADDRESS
);
this.bridgeContract = new this.web3.eth.Contract(
BRIDGE_ABI,
CONSTANTS.BRIDGE_CONTRACT
);
}
initializeHeaders() {
this.headers = {
accept: "*/*",
"accept-encoding": "gzip, deflate, br, zstd",
"accept-language": "en-US;q=0.6,en;q=0.5",
"content-type": "application/json",
origin: "https://faucet.testnet.humanity.org",
referer: "https://faucet.testnet.humanity.org/",
"sec-ch-ua":
'"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99""',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"user-agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
};
}
async countdown(seconds) {
await timer.start(seconds, {
message: colors.style("Time remaining: ", "timerCount"),
format: "HH:mm:ss",
});
}
formatPrivateKey(privateKey) {
const trimmed = privateKey.trim();
return trimmed.startsWith("0x") ? trimmed : `0x${trimmed}`;
}
// Utility method to mask sensitive data
maskAddress(address) {
if (!address) return "";
return `${address.slice(0, 6)}...${address.slice(-4)}`;
}
maskTxHash(hash) {
if (!hash) return "";
return `${hash.slice(0, 10)}...${hash.slice(-8)}`;
}
async loadWallets() {
const privateFile = path.join(__dirname, "private_keys.txt");
try {
const privateKeys = fs
.readFileSync(privateFile, "utf8")
.replace(/\r/g, "")
.split("\n")
.map((key) => key.trim())
.filter(Boolean);
const wallets = privateKeys.map((privateKey) => {
const formattedKey = this.formatPrivateKey(privateKey);
const account =
this.web3.eth.accounts.privateKeyToAccount(formattedKey);
return {
address: account.address,
privateKey: formattedKey,
};
});
logger.info(
colors.style(
`Successfully loaded ${wallets.length} wallets`,
"accountInfo"
)
);
return wallets;
} catch (error) {
logger.error(
colors.style(`Failed to load wallets: ${error.message}`, "accountError")
);
process.exit(1);
}
}
async getBalance(address) {
try {
return await this.retryOperation(async () => {
const balance = await this.web3.eth.getBalance(address);
return this.web3.utils.fromWei(balance, "ether");
});
} catch (error) {
return "0";
}
}
async getSafeGasPrice() {
try {
const gasPrice = await this.web3.eth.getGasPrice();
const maxGasPrice = CONSTANTS.MAX_GAS_PRICE;
const safeGasPrice = Math.min(
Math.max(
Number(gasPrice),
Number(CONSTANTS.MIN_GAS_PRICE)
),
Number(maxGasPrice)
).toString();
return Math.floor(
Number(safeGasPrice) * CONSTANTS.GAS_PRICE_MULTIPLIER
).toString();
} catch (error) {
return CONSTANTS.MIN_GAS_PRICE;
}
}
logTransactionDetails(tx, gasPrice) {
logger.info(colors.style("Transaction details:", "menuTitle"));
logger.info(
`${colors.style(">", "menuBorder")} Gas Price: ${colors.style(
`${this.web3.utils.fromWei(gasPrice, "gwei")} gwei`,
"value"
)}`
);
logger.info(
`${colors.style(">", "menuBorder")} Gas Limit: ${colors.style(
tx.gas,
"value"
)}`
);
logger.info(
`${colors.style(">", "menuBorder")} Nonce: ${colors.style(
tx.nonce,
"value"
)}`
);
}
logBridgeDetails(tx, gasPrice, params) {
logger.info(colors.style("Bridge details:", "menuTitle"));
logger.info(
`${colors.style(">", "menuBorder")} Bridge Amount: ${colors.style(
`${this.web3.utils.fromWei(params.amount, "ether")} ETH`,
"value"
)}`
);
logger.info(
`${colors.style(">", "menuBorder")} Gas Price: ${colors.style(
`${this.web3.utils.fromWei(gasPrice, "gwei")} gwei`,
"value"
)}`
);
logger.info(
`${colors.style(">", "menuBorder")} Gas Limit: ${colors.style(
tx.gas,
"value"
)}`
);
logger.info(
`${colors.style(">", "menuBorder")} Destination: ${colors.style(
this.maskAddress(params.destinationAddress),
"value"
)}`
);
logger.info(
`${colors.style(">", "menuBorder")} Nonce: ${colors.style(
tx.nonce,
"value"
)}`
);
}
async claimTHP(address) {
try {
const proxy = this.proxyHandler.getNextProxy();
const proxyConfig = this.proxyHandler.getAxiosProxyConfig(proxy);
const response = await axios.post(
CONSTANTS.FAUCET_URL,
{ address },
{
headers: this.headers,
proxy: proxyConfig
}
);
if (response.status === 200 && response.data.msg) {
const txHash = response.data.msg.split("Txhash: ")[1];
return { success: true, txHash };
}
return { success: false, error: "Invalid response format" };
} catch (error) {
return { success: false, error: error.message };
}
}
async claimReward(privateKey, address) {
try {
// Check balance
const balance = await this.getBalance(address);
if (parseFloat(balance) < CONSTANTS.MIN_BALANCE_FOR_REWARD) {
return {
success: false,
error: `Insufficient balance: ${balance} THP`,
};
}
// Setup transaction parameters with retry
const gasPrice = await this.retryOperation(() => this.getSafeGasPrice());
logger.info(
colors.style(
`Using gas price: ${this.web3.utils.fromWei(gasPrice, "gwei")} gwei`,
"info"
)
);
const account = this.web3.eth.accounts.privateKeyToAccount(privateKey);
this.web3.eth.accounts.wallet.add(account);
// Check if reward is available with improved error handling
try {
await this.contract.methods.claimReward().call({ from: address });
} catch (error) {
if (error.message.toLowerCase().includes('revert') ||
error.message.toLowerCase().includes('execution reverted')) {
return {
success: false,
error: "Reward not available or already claimed",
};
}
return {
success: false,
error: `Contract call failed: ${error.message}`,
};
}
// Estimate gas limit with retry
let gasLimit;
try {
gasLimit = await this.retryOperation(async () => {
const estimate = await this.contract.methods.claimReward().estimateGas({
from: address,
gasPrice: gasPrice,
});
return Math.floor(
Number(estimate) * CONSTANTS.GAS_LIMIT_MULTIPLIER
).toString();
});
} catch (error) {
logger.warn(
colors.style("Gas estimation failed, using default value", "warning")
);
gasLimit = CONSTANTS.DEFAULT_GAS_LIMIT;
}
// Check if enough balance for gas
if (!await this.hasEnoughBalanceForGas(address, gasLimit, gasPrice)) {
return {
success: false,
error: "Insufficient balance for gas fees"
};
}
// Get nonce with retry
const nonce = await this.getNonceWithRetry(address);
// Build transaction
const tx = {
from: address,
to: CONSTANTS.CONTRACT_ADDRESS,
gas: gasLimit,
gasPrice: gasPrice,
data: this.contract.methods.claimReward().encodeABI(),
nonce: nonce,
};
this.logTransactionDetails(tx, gasPrice);
// Sign and send transaction with timeout
const signedTx = await this.web3.eth.accounts.signTransaction(tx, privateKey);
const receipt = await Promise.race([
this.web3.eth.sendSignedTransaction(signedTx.rawTransaction),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Transaction timeout')), CONSTANTS.TRANSACTION_TIMEOUT)
)
]);
return receipt.status
? { success: true, txHash: receipt.transactionHash }
: { success: false, error: "Transaction failed" };
} catch (error) {
logger.error(colors.style(`Detailed error: ${error.message}`, "error"));
return { success: false, error: `Transaction failed: ${error.message}` };
}
}
async bridgeAssets(privateKey, address) {
try {
const balance = await this.getBalance(address);
if (parseFloat(balance) < CONSTANTS.MIN_BALANCE_FOR_BRIDGE) {
return {
success: false,
error: `Insufficient balance: ${balance} ETH`,
};
}
const gasPrice = await this.retryOperation(() => this.getSafeGasPrice());
logger.info(
colors.style(
`Using gas price: ${this.web3.utils.fromWei(gasPrice, "gwei")} gwei`,
"info"
)
);
const account = this.web3.eth.accounts.privateKeyToAccount(privateKey);
this.web3.eth.accounts.wallet.add(account);
const bridgeParams = {
destinationNetwork: 0,
destinationAddress: address,
amount: CONSTANTS.BRIDGE_AMOUNT,
token: "0x0000000000000000000000000000000000000000",
forceUpdateGlobalExitRoot: true,
permitData: "0x",
};
let gasLimit;
try {
gasLimit = await this.retryOperation(async () => {
const estimate = await this.bridgeContract.methods
.bridgeAsset(...Object.values(bridgeParams))
.estimateGas({
from: address,
value: bridgeParams.amount,
});
return Math.floor(
Number(estimate) * CONSTANTS.GAS_LIMIT_MULTIPLIER
).toString();
});
} catch (error) {
logger.warn(
colors.style("Gas estimation failed, using default value", "warning")
);
gasLimit = CONSTANTS.DEFAULT_GAS_LIMIT;
}
// Check if enough balance for gas
if (!await this.hasEnoughBalanceForGas(address, gasLimit, gasPrice)) {
return {
success: false,
error: "Insufficient balance for gas fees"
};
}
const nonce = await this.getNonceWithRetry(address);
const tx = {
from: address,
to: CONSTANTS.BRIDGE_CONTRACT,
gas: gasLimit,
gasPrice: gasPrice,
value: bridgeParams.amount,
data: this.bridgeContract.methods
.bridgeAsset(...Object.values(bridgeParams))
.encodeABI(),
nonce: nonce,
};
this.logBridgeDetails(tx, gasPrice, bridgeParams);
const signedTx = await this.web3.eth.accounts.signTransaction(tx, privateKey);
const receipt = await Promise.race([
this.web3.eth.sendSignedTransaction(signedTx.rawTransaction),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Transaction timeout')), CONSTANTS.TRANSACTION_TIMEOUT)
)
]);
return receipt.status
? { success: true, txHash: receipt.transactionHash }
: { success: false, error: "Transaction failed" };
} catch (error) {
logger.error(colors.style(`Detailed error: ${error.message}`, "error"));
return { success: false, error: `Transaction failed: ${error.message}` };
}
}
async main() {
displayBanner();
const wallets = await this.loadWallets();
while (true) {
for (let i = 0; i < wallets.length; i++) {
const { address, privateKey } = wallets[i];
const maskedAddress = this.maskAddress(address);
logger.info(
`${colors.style("Processing Wallet", "label")} ${colors.style(
(i + 1).toString(),
"value"
)} | ${colors.style(maskedAddress, "accountName")}`
);
const balance = await this.getBalance(address);
logger.info(
`${colors.style("Current balance:", "label")} ${colors.style(
`${balance} THP`,
"value"
)}`
);
// Claim THP
const claimResult = await this.claimTHP(address);
if (claimResult.success) {
logger.success(
`${colors.style(
"THP claim successful",
"txSuccess"
)} | ${colors.style("Txhash:", "label")} ${colors.style(
this.maskTxHash(claimResult.txHash),
"txHash"
)}`
);
} else {
logger.error(
`${colors.style("THP claim failed:", "txFailed")} ${colors.style(
claimResult.error,
"error"
)}`
);
}
await this.countdown(10);
// Claim Reward
const rewardResult = await this.claimReward(privateKey, address);
if (rewardResult.success) {
logger.success(
`${colors.style(
"Reward claim successful",
"txSuccess"
)} | ${colors.style("Txhash:", "label")} ${colors.style(
this.maskTxHash(rewardResult.txHash),
"txHash"
)}`
);
} else {
logger.error(
`${colors.style("Reward claim failed:", "txFailed")} ${colors.style(
rewardResult.error,
"error"
)}`
);
}
await this.countdown(3);
// Bridge Assets
const bridgeResult = await this.bridgeAssets(privateKey, address);
if (bridgeResult.success) {
logger.success(
`${colors.style(
"Asset bridge successful",
"txSuccess"
)} | ${colors.style("Txhash:", "label")} ${colors.style(
this.maskTxHash(bridgeResult.txHash),
"txHash"
)}`
);
} else {
logger.error(
`${colors.style("Asset bridge failed:", "txFailed")} ${colors.style(
bridgeResult.error,
"error"
)}`
);
}
logger.info(colors.style("Waiting for next wallet...", "waiting"));
await new Promise((resolve) =>
setTimeout(resolve, CONSTANTS.WAIT_BETWEEN_WALLETS)
);
}
logger.info(
colors.style(
"Completed processing all wallets. Waiting for next round...",
"complete"
)
);
await this.countdown(CONSTANTS.WAIT_BETWEEN_ROUNDS);
}
}
}
// Error handling wrapper for main execution
process.on("unhandledRejection", (error) => {
logger.error(
colors.style(`Unhandled promise rejection: ${error.message}`, "error")
);
process.exit(1);
});
// Initialize and run the client
const client = new HumanityClient();
client.main().catch((err) => {
logger.error(colors.style(err.message, "error"));
process.exit(1);
});