Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
1045 lines (914 loc) · 38.2 KB
/
Copy pathindex.js
File metadata and controls
1045 lines (914 loc) · 38.2 KB
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ethers, FetchRequest } from "ethers";
import dotenv from "dotenv";
import * as fs from "fs/promises";
import path from "path";
import chalk from "chalk";
import { HttpsProxyAgent } from "https-proxy-agent";
import { SocksProxyAgent } from "socks-proxy-agent";
import { fileURLToPath } from "url";
import crypto from "crypto";
dotenv.config();
// Validate required environment variables
if (!process.env.PRIVATE_KEYS) {
console.error(chalk.bgRed.white.bold("❌ PRIVATE_KEYS environment variable is not set!"));
process.exit(1);
}
// Define __dirname equivalent for ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const LOG_DIR = __dirname;
// ==========================
// ✅ Resource & Error Safety
// ==========================
/**
* Tracks and logs memory usage at regular intervals.
*/
setInterval(() => {
const used = process.memoryUsage();
const rssMB = (used.rss / 1024 / 1024).toFixed(1);
const heapMB = (used.heapUsed / 1024 / 1024).toFixed(1);
console.log(chalk.cyan(`[Monitor] RSS: ${rssMB} MB | Heap: ${heapMB} MB`));
}, 10 * 60 * 1000);
/**
* Handles graceful shutdown by flushing logs and saving state.
* @param {number} code - The exit code.
*/
async function safeExit(code = 0) {
console.log(chalk.yellow.bold("[Exit] Flushing logs & saving state..."));
try {
await flushTxLog();
await savePersonas();
await saveInactive();
} catch (err) {
console.error(chalk.red.bold("[Exit Error]"), err.message);
}
process.exit(code);
}
process.on("SIGINT", () => {
console.log(chalk.yellow.bold("\n[Signal] Caught SIGINT (Ctrl+C)."));
safeExit(0);
});
process.on("SIGTERM", () => {
console.log(chalk.yellow.bold("\n[Signal] Caught SIGTERM."));
safeExit(0);
});
// Catch uncaught errors without crashing
process.on("uncaughtException", (err) => {
console.error(chalk.bgRed.white.bold("[Uncaught Exception]"), err);
});
process.on("unhandledRejection", (reason, promise) => {
console.error(chalk.bgRed.white.bold("[Unhandled Rejection]"), reason);
});
// === FIXED: In-Memory Encryption Helper Functions ===
const ALGO = "aes-256-gcm";
const IV_LENGTH = 12;
// --- Master Keys ---
const MASTER_KEY = process.env.MASTER_KEY;
const BACKUP_KEYS = (process.env.BACKUP_KEYS || "")
.split(",")
.map(k => k.trim())
.filter(Boolean);
if (!MASTER_KEY) {
console.error(chalk.bgRed.white.bold("❌ MASTER_KEY environment variable is not set!"));
process.exit(1);
}
const ALL_MASTER_KEYS = [MASTER_KEY, ...BACKUP_KEYS];
/**
* Derives a cryptographic key from a master key and a salt.
* @param {string} masterKey - The master key for key derivation.
* @param {Buffer} salt - The salt for key derivation.
* @returns {Buffer} The derived key as a Buffer.
*/
function deriveKey(masterKey, salt) {
return crypto.scryptSync(masterKey, salt, 32);
}
/**
* Encrypts a private key using a master key.
* @param {string} privateKey - The private key to encrypt.
* @param {string} masterKey - The master key for encryption.
* @returns {string} The encrypted key string in the format "salt:iv:authTag:encrypted".
*/
function encryptPrivateKey(privateKey, masterKey) {
const salt = crypto.randomBytes(16); // Generate unique salt for this encryption
const iv = crypto.randomBytes(IV_LENGTH);
const derivedKey = deriveKey(masterKey, salt);
const cipher = crypto.createCipheriv(ALGO, derivedKey, iv);
let encrypted = cipher.update(privateKey, "utf8", "hex");
encrypted += cipher.final("hex");
const authTag = cipher.getAuthTag().toString("hex");
// IMPORTANT: Store salt with the encrypted data
return `${salt.toString("hex")}:${iv.toString("hex")}:${authTag}:${encrypted}`;
}
/**
* Decrypts an encrypted private key.
* @param {string} encrypted - The encrypted key string.
* @param {string} masterKey - The master key for decryption.
* @returns {string} The decrypted private key.
*/
function decryptPrivateKey(encrypted, masterKey) {
const [saltHex, ivHex, authTagHex, data] = encrypted.split(":");
const salt = Buffer.from(saltHex, "hex"); // Extract salt from encrypted data
const iv = Buffer.from(ivHex, "hex");
const authTag = Buffer.from(authTagHex, "hex");
const derivedKey = deriveKey(masterKey, salt); // Use the original salt
const decipher = crypto.createDecipheriv(ALGO, derivedKey, iv);
decipher.setAuthTag(authTag);
let decrypted = decipher.update(data, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
}
/**
* Attempts to decrypt an encrypted key with any of the available master keys.
* This provides resilience if a new master key is rolled out.
* @param {string} encrypted - The encrypted key string.
* @returns {string} The decrypted private key.
* @throws {Error} If decryption fails with all keys.
*/
function decryptWithAnyKey(encrypted) {
for (const key of ALL_MASTER_KEYS) {
try {
return decryptPrivateKey(encrypted, key);
} catch {
continue;
}
}
throw new Error("❌ Failed to decrypt private key with all available master keys");
}
// === CONFIG ===
// List of public RPCs for Celo.
const RPCS = [
"https://rpc.ankr.com/celo",
"https://celo.drpc.org",
"https://forno.celo.org",
"https://1rpc.io/celo"
];
// Gas tracking RPCs (for gas price monitoring)
const GAS_RPC_URLS = [
"https://forno.celo.org"
];
// Gas tolerance threshold (in Gwei) - transactions will only be sent if gas is below this value
// Set this in your .env file as GAS_TOLERANCE_THRESHOLD=30 for 30 Gwei threshold
const GAS_TOLERANCE_THRESHOLD = process.env.GAS_TOLERANCE_THRESHOLD ?
parseFloat(process.env.GAS_TOLERANCE_THRESHOLD) : 51; // Default: 50 Gwei
const GAS_LIMIT = 21000;
const keysFile = "key.txt";
let lastKey = null;
// --- Key loader (env only, one key per line inside PRIVATE_KEYS) ---
// Now stores encrypted keys
let ENCRYPTED_KEYS = [];
let ALL_WALLETS = [];
/**
* Normalizes a private key string, ensuring it's 0x-prefixed.
* @param {string} k - The key string to normalize.
* @returns {string|null} The normalized key or null if invalid.
*/
function normalizeKey(k) {
if (!k) return null;
k = String(k).trim();
if (!k) return null;
return k.startsWith("0x") ? k : "0x" + k;
}
/**
* Validates a private key by attempting to construct an ethers.Wallet.
* @param {string} k - The key to validate.
* @returns {boolean} True if the key is valid, false otherwise.
*/
function isValidPrivateKey(k) {
try {
new ethers.Wallet(k);
return true;
} catch {
return false;
}
}
/**
* Loads and encrypts private keys from the PRIVATE_KEYS environment variable.
*/
async function loadKeysInline() {
const envKeys = process.env.PRIVATE_KEYS || "";
// split by newlines, trim, filter empties
const keys = envKeys
.split(/\r?\n/)
.map(normalizeKey)
.filter(Boolean);
const validKeys = keys.filter(isValidPrivateKey);
if (validKeys.length === 0) {
console.error(chalk.bgRed.white.bold("❌ No valid private keys found in PRIVATE_KEYS (env). Each key should be on its own line."));
process.exit(1);
}
// Encrypt keys and store them (each with its own salt)
ENCRYPTED_KEYS = validKeys.map(k => encryptPrivateKey(k, MASTER_KEY));
// Create ALL_WALLETS list using decrypted keys just once at startup
ALL_WALLETS = validKeys.map(k => new ethers.Wallet(k).address);
console.log(chalk.cyan(`🔐 Loaded ${ALL_WALLETS.length} wallets (encrypted in memory with individual salts)`));
}
// === NEW: Device Agent Generation ===
/**
* Generates a random device agent profile to simulate human-like network traffic.
* @returns {{userAgent: string, latency: number}} An object containing a user agent string and a simulated network latency in ms.
*/
function generateDeviceAgent() {
const browsers = ["Chrome", "Firefox", "Edge", "Safari"];
const os = ["Windows NT 10.0", "Macintosh; Intel Mac OS X 13_0", "Linux x86_64"];
const browser = browsers[Math.floor(Math.random() * browsers.length)];
const system = os[Math.floor(Math.random() * os.length)];
const version = `${Math.floor(Math.random() * 100)}.0.${Math.floor(Math.random() * 1000)}`;
// Simulated network latency per wallet (in ms)
const latency = 50 + Math.floor(Math.random() * 200); // 50ms to 250ms
return {
userAgent: `${browser}/${version} (${system})`,
latency
};
}
// --- Wallet Persona Management ---
const personaFile = "personas.json";
let walletProfiles = {};
let lastPersonaSave = 0;
const PERSONA_SAVE_DEBOUNCE_MS = 5_000; // coalesce multiple writes into one
/**
* Loads wallet personas from a JSON file.
*/
async function loadPersonas() {
try {
const data = await fs.readFile(personaFile, "utf-8");
walletProfiles = JSON.parse(data);
console.log(chalk.cyan("🎭 Loaded existing personas"));
} catch (e) {
if (e.code === 'ENOENT') {
console.log(chalk.yellow("🎭 Personas file not found, starting fresh."));
} else {
console.error(chalk.bgRed.white.bold("❌ Error parsing personas.json, starting fresh."));
}
walletProfiles = {};
}
}
// Debounced save to avoid frequent blocking disk writes
async function savePersonas() {
try {
const now = Date.now();
if (now - lastPersonaSave < PERSONA_SAVE_DEBOUNCE_MS) {
setTimeout(async () => {
try { await fs.writeFile(personaFile, JSON.stringify(walletProfiles, null, 2)); lastPersonaSave = Date.now(); }
catch (e) { console.error("failed saving personas:", e.message); }
}, PERSONA_SAVE_DEBOUNCE_MS);
return;
}
await fs.writeFile(personaFile, JSON.stringify(walletProfiles, null, 2));
lastPersonaSave = now;
} catch (e) {
console.error("failed saving personas:", e.message);
}
}
/**
* Ensures a wallet has a persona profile, creating a new one if it doesn't exist.
* @param {ethers.Wallet} wallet - The wallet instance.
* @returns {object} The wallet's persona profile.
*/
function ensurePersona(wallet) {
if (!walletProfiles[wallet.address]) {
const deviceAgent = generateDeviceAgent();
walletProfiles[wallet.address] = {
idleBias: Math.random() * 0.25,
pingBias: Math.random() * 0.25,
minAmount: 0.00005 + Math.random() * 0.0001,
maxAmount: 0.015 + Math.random() * 0.005,
activeHours: [2 + Math.floor(Math.random() * 4), 22 + Math.floor(Math.random() * 3)], // 2-5 to 22-24 UTC
cooldownAfterFail: 60 + Math.floor(Math.random() * 120), // 1-3 min
avgWait: 30 + Math.floor(Math.random() * 40), // base wait time 30-70 sec
retryBias: Math.random() * 0.5, // 0-50% chance to retry
// dynamic per-wallet nonce retirement
maxNonce: 520 + Math.floor(Math.random() * 80),
// failure tracking
failCount: 0,
lastFailAt: null,
deviceAgent // store User-Agent + latency
};
savePersonas();
}
return walletProfiles[wallet.address];
}
// === NEW: Inactive Wallet Management ===
const inactiveFile = "inactive.json";
let inactiveWallets = new Set();
/**
* Loads the list of inactive wallets from a file.
*/
async function loadInactive() {
try {
const data = await fs.readFile(inactiveFile, "utf-8");
inactiveWallets = new Set(JSON.parse(data));
console.log(chalk.gray(`📂 Loaded ${inactiveWallets.size} inactive wallets`));
} catch (e) {
if (e.code === 'ENOENT') {
console.log(chalk.yellow("📂 Inactive file not found, starting empty."));
} else {
console.error("❌ Failed parsing inactive.json, starting empty");
}
inactiveWallets = new Set();
}
}
/**
* Saves the list of inactive wallets to a file.
*/
async function saveInactive() {
try {
await fs.writeFile(inactiveFile, JSON.stringify([...inactiveWallets], null, 2));
} catch (e) {
console.error("❌ Failed saving inactive.json:", e.message);
}
}
// --- Dynamic Log File Management (Daily Rotation) ---
// This function returns the log file path for the current day.
function getLogFile() {
const today = new Date().toISOString().split("T")[0]; // YYYY-MM-DD format
return path.join(__dirname, `tx_log_${today}.csv`);
}
/**
* Initializes the log file for the current day, adding a header if it doesn't exist.
* @returns {Promise<string>} The path to the log file.
*/
async function initLogFile() {
const logFile = getLogFile();
try {
await fs.access(logFile);
} catch (e) {
// File doesn't exist, create it with a header
await fs.writeFile(
logFile,
"timestamp,wallet,tx_hash,nonce,gas_used,gas_price_gwei,fee_celo,status,action\n"
);
}
return logFile;
}
// --- Tx Log Buffer ---
let txBuffer = [];
const FLUSH_INTERVAL = 300 * 1000;
/**
* Buffers a transaction log entry.
* @param {string} entry - The log entry string.
*/
function bufferTxLog(entry) {
txBuffer.push(entry);
}
/**
* Flushes the transaction log buffer to the daily log file.
*/
async function flushTxLog() {
if (txBuffer.length === 0) return;
const logFile = await initLogFile();
await fs.appendFile(logFile, txBuffer.join("\n") + "\n");
console.log(chalk.gray(`📝 Flushed ${txBuffer.length} tx logs to disk`));
txBuffer = [];
}
// Periodic flusher
setInterval(flushTxLog, FLUSH_INTERVAL);
// Periodic gas price monitoring (every 5 minutes)
setInterval(async () => {
try {
const gasData = await getAverageGasPrice(false); // Less verbose periodic monitoring
if (gasData) {
const { avgGasPriceGwei } = gasData;
if (!isGasPriceAcceptable(avgGasPriceGwei)) {
console.log(chalk.yellow(`⛽ High gas prices detected: ${avgGasPriceGwei.toFixed(2)} Gwei (threshold: ${GAS_TOLERANCE_THRESHOLD} Gwei)`));
}
}
} catch (err) {
// Silently ignore gas monitoring errors
}
}, 5 * 60 * 1000); // 5 minutes
// --- Pick random key (with small chance of reusing last key) ---
// Now pickRandomKey() will work correctly because each encrypted key
// includes its own salt for decryption
function pickRandomKey() {
const idx = Math.floor(Math.random() * ENCRYPTED_KEYS.length);
const encrypted = ENCRYPTED_KEYS[idx];
const privateKey = decryptWithAnyKey(encrypted);
return privateKey;
}
// --- Proxy Variables ---
let proxies = [];
// --- Proxy Functions ---
/**
* Loads proxies from `proxy.txt`.
*/
async function loadProxies() {
try {
const fileContent = await fs.readFile("proxy.txt", "utf8");
proxies = fileContent.split("\n").map(proxy => proxy.trim()).filter(proxy => proxy);
if (proxies.length === 0) {
console.log(chalk.cyan(`[${new Date().toISOString()}] ⟐ No proxy found in proxy.txt. Running without proxy.`));
} else {
console.log(chalk.green(`[${new Date().toISOString()}] ✔ Loaded ${proxies.length} proxies from proxy.txt`));
}
} catch (error) {
if (error.code === 'ENOENT') {
console.log(chalk.cyan(`[${new Date().toISOString()}] ⟐ No proxy.txt found, running without proxy.`));
} else {
console.error(chalk.red(`[${new Date().toISOString()}] ✖ Failed to load proxy: ${error.message}`));
}
proxies = [];
}
}
// Auto-refresh proxies every 15 minutes
setInterval(async () => {
try {
const fileContent = await fs.readFile("proxy.txt", "utf8");
const fresh = fileContent
.split("\n")
.map(p => p.trim())
.filter(p => p.length > 0);
if (fresh.length > 0) {
// Only update and log if the proxy list has actually changed
if (JSON.stringify(proxies) !== JSON.stringify(fresh)) {
proxies = fresh;
console.log(chalk.green(`[Proxy] Reloaded ${proxies.length} proxies from file ✅`));
}
} else {
console.warn(chalk.yellow("[Proxy] proxy.txt is empty, keeping old list."));
}
} catch (err) {
// Silently ignore if file doesn't exist, log other errors
if (err.code !== 'ENOENT') {
console.error(chalk.red("[Proxy Refresh Error]"), err.message);
}
}
}, 15 * 60 * 1000);
function createAgent(proxyUrl) {
if (!proxyUrl) return null;
if (proxyUrl.startsWith("socks")) {
return new SocksProxyAgent(proxyUrl);
} else {
return new HttpsProxyAgent(proxyUrl);
}
}
// --- Provider with proxy and User-Agent support ---
function getProvider(rpcUrl, agent, userAgent) {
const network = {
chainId: 42220,
name: "celo"
};
const req = new FetchRequest(rpcUrl);
if (userAgent) {
req.setHeader("User-Agent", userAgent);
}
if (agent) {
req.agent = agent;
}
return new ethers.JsonRpcProvider(req, network);
}
/**
* Fetches current gas price from a specific RPC endpoint
* @param {string} rpcUrl - The RPC endpoint URL
* @returns {Promise<bigint|null>} The gas price in wei, or null if failed
*/
async function getGasPriceFromRpc(rpcUrl, proxyUrl = null, userAgent = null) {
try {
const agent = proxyUrl ? createAgent(proxyUrl) : null;
const provider = getProvider(rpcUrl, agent, userAgent);
const feeData = await provider.getFeeData();
// Prioritize EIP-1559 maxFeePerGas, fallback to legacy gasPrice
return feeData.maxFeePerGas || feeData.gasPrice || null;
} catch (err) {
// Silently ignore gas price fetching errors to reduce verbosity
return null;
}
}
/**
* Gets average gas price from multiple RPCs
* @returns {Promise<{avgGasPriceGwei: number, gasPricesGwei: number[]}|null>} Average gas price and individual prices
*/
async function getAverageGasPrice(verbose = true, proxyUrl = null, userAgent = null) {
if (verbose) {
console.log(chalk.cyan("🔍 Checking gas prices from multiple RPCs..."));
}
// Fetch gas prices from all RPCs concurrently
const gasPricePromises = GAS_RPC_URLS.map(url => getGasPriceFromRpc(url, proxyUrl, userAgent));
const gasPrices = await Promise.all(gasPricePromises);
// Filter out null values
const validGasPrices = gasPrices.filter(price => price !== null);
if (validGasPrices.length === 0) {
console.error(chalk.red("❌ Failed to get gas prices from any RPC"));
return null;
}
// Convert to Gwei for easier comparison
const gasPricesGwei = validGasPrices.map(price =>
parseFloat(ethers.formatUnits(price, "gwei"))
);
// Calculate average
const sum = gasPricesGwei.reduce((acc, price) => acc + price, 0);
const avgGasPriceGwei = sum / gasPricesGwei.length;
if (verbose) {
console.log(chalk.cyan(`📊 Gas prices: ${gasPricesGwei.map(p => p.toFixed(2)).join(", ")} Gwei (avg: ${avgGasPriceGwei.toFixed(2)} Gwei)`));
}
return {
avgGasPriceGwei,
gasPricesGwei
};
}
/**
* Checks if current gas price is below tolerance threshold
* @param {number} avgGasPriceGwei - Average gas price in Gwei
* @returns {boolean} True if gas price is acceptable
*/
function isGasPriceAcceptable(avgGasPriceGwei) {
const isAcceptable = avgGasPriceGwei <= GAS_TOLERANCE_THRESHOLD;
if (!isAcceptable) {
console.log(chalk.yellow(`⛽ Gas price ${avgGasPriceGwei.toFixed(2)} Gwei exceeds threshold of ${GAS_TOLERANCE_THRESHOLD} Gwei`));
}
return isAcceptable;
}
/**
* Simulates micro-behaviors of real user devices during transaction processing
* @returns {Promise<void>}
*/
async function simulateMicroBehaviors() {
// 80-180ms signing delay
const signingDelay = 80 + Math.floor(Math.random() * 101);
await new Promise(resolve => setTimeout(resolve, signingDelay));
// 20-90ms network preparation delay
const networkDelay = 20 + Math.floor(Math.random() * 71);
await new Promise(resolve => setTimeout(resolve, networkDelay));
// 40-200ms hesitation before broadcasting
const broadcastDelay = 40 + Math.floor(Math.random() * 161);
await new Promise(resolve => setTimeout(resolve, broadcastDelay));
}
/**
* Implements random hesitation when gas prices spike (simulating human behavior)
* @param {number} avgGasPriceGwei - Average gas price in Gwei
* @param {number[]} gasPricesGwei - Individual gas prices from different RPCs
* @param {string} proxyUrl - The proxy URL being used
* @param {string} userAgent - The user agent being used
* @returns {Promise<boolean>} True if should proceed with transaction
*/
async function shouldProceedWithGasSpike(avgGasPriceGwei, gasPricesGwei, proxyUrl, userAgent) {
// Calculate standard deviation to detect price volatility
const variance = gasPricesGwei.reduce((acc, price) => acc + Math.pow(price - avgGasPriceGwei, 2), 0) / gasPricesGwei.length;
const stdDev = Math.sqrt(variance);
// If there's high volatility or gas price is above 80% of threshold, consider hesitating
const volatilityThreshold = GAS_TOLERANCE_THRESHOLD * 0.8;
const isVolatile = stdDev > 5 || avgGasPriceGwei > volatilityThreshold;
if (isVolatile) {
console.log(chalk.yellow("⚠️ Gas price volatility detected, simulating human hesitation..."));
// Random hesitation time between 3-10 seconds
const hesitationTime = 3 + Math.floor(Math.random() * 7);
console.log(chalk.yellow(`⏳ Hesitating for ${hesitationTime} seconds...`));
await new Promise(resolve => setTimeout(resolve, hesitationTime * 1000));
// After hesitation, check gas prices again (less verbose)
const updatedGasData = await getAverageGasPrice(false, proxyUrl, userAgent);
if (updatedGasData && isGasPriceAcceptable(updatedGasData.avgGasPriceGwei)) {
console.log(chalk.green("✅ Gas prices improved after hesitation"));
return true;
} else {
console.log(chalk.red("❌ Gas prices still high after hesitation"));
return false;
}
}
return true;
}
/**
* Attempts to connect to an RPC endpoint.
* @returns {Promise<{provider: ethers.JsonRpcProvider, url: string, proxyUrl: string, userAgent: string}|null>} The working provider and its URL, or null if all fail.
*/
async function tryProviders(profile) {
console.log(chalk.hex("#00FFFF").bold("🔍 Searching for a working RPC endpoint..."));
for (const url of RPCS) {
try {
const proxyUrl = proxies.length > 0 ? proxies[Math.floor(Math.random() * proxies.length)] : null;
const agent = createAgent(proxyUrl);
const userAgent = profile.deviceAgent.userAgent;
const provider = getProvider(url, agent, userAgent);
const network = await Promise.race([
provider.getNetwork(),
new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), 5000))
]);
// Only log successful connections to reduce verbosity
return { provider, url, proxyUrl, userAgent };
} catch (e) {
// Silently ignore failed connections to reduce verbosity
}
}
return null;
}
/**
* Iterates through the list of RPCs and returns the first one that successfully connects.
* @returns {Promise<{provider: ethers.JsonRpcProvider, url: string, proxyUrl: string, userAgent: string}>} The working provider and its URL.
*/
async function getWorkingProvider(profile) {
return await tryProviders(profile);
}
function randomDelay(minSec, maxSec) {
const ms = (Math.floor(Math.random() * (maxSec - minSec + 1)) + minSec) * 1000;
return new Promise(resolve => setTimeout(resolve, ms));
}
function isWithinActiveHours(profile) {
const nowUTC = new Date().getUTCHours();
return nowUTC >= profile.activeHours[0] && nowUTC <= profile.activeHours[1];
}
// === NEW: Active Hours Check ===
function checkActive(wallet, profile) {
if (isWithinActiveHours(profile)) {
if (inactiveWallets.has(wallet.address)) {
inactiveWallets.delete(wallet.address);
saveInactive();
console.log(chalk.green(`✅ Wallet ${wallet.address} re-activated`));
}
return true;
} else {
if (!inactiveWallets.has(wallet.address)) {
inactiveWallets.add(wallet.address);
saveInactive();
console.log(chalk.gray(`🛌 Wallet ${wallet.address} marked inactive`));
}
return false;
}
}
/**
* Sends a transaction from a wallet to itself.
* @param {ethers.Wallet} wallet - The wallet instance.
* @param {ethers.JsonRpcProvider} provider - The RPC provider.
* @param {object} profile - The wallet's persona profile.
* @param {string} url - The URL of the RPC being used.
* @param {string} proxyUrl - The proxy URL being used.
* @param {string} userAgent - The user agent being used.
* @throws {Error} If the transaction fails.
*/
async function sendTx(wallet, provider, profile, url, proxyUrl, userAgent) {
try {
if (Math.random() < profile.idleBias) {
console.log(chalk.hex("#808080").italic("\n😴 Persona idle mode, skipping this cycle..."));
return;
}
// === NEW: Simulate Network Latency ===
console.log(chalk.hex("#FFA500").bold(`🌐 Simulating network latency: ${profile.deviceAgent.latency}ms...`));
await new Promise(res => setTimeout(res, profile.deviceAgent.latency));
const balance = await provider.getBalance(wallet.address);
await randomDelay(2, 4);
const walletNonce = await provider.getTransactionCount(wallet.address);
await randomDelay(2, 4); // Another short delay
const maxNonce = profile.maxNonce;
if (walletNonce >= maxNonce) {
console.warn(chalk.bgYellow.black.bold(`\n🟡 Wallet: ${wallet.address} nonce ${walletNonce} >= ${maxNonce}. Skipping.`));
return;
}
console.log(chalk.hex("#1E90FF").bold.underline(`\n🎲 Wallet: ${wallet.address}`));
console.log(chalk.hex("#1E90FF").bold(`Using RPC: ${url}`));
console.log(chalk.hex("#FFD700").bold(`Balance: ${ethers.formatEther(balance)} CELO`));
console.log(chalk.hex("#FFD700").bold(`Nonce: ${walletNonce}`));
if (balance < ethers.parseEther("0.01")) {
console.warn(chalk.hex("#FFA500").bold("⚠️ Not enough balance, skipping..."));
return;
}
// === NEW: Dynamic Gas Pricing Check ===
// Check gas prices before transaction (less verbose)
const gasData = await getAverageGasPrice(true, proxyUrl, userAgent); // Verbose for initial check
if (!gasData) {
console.error(chalk.red("❌ Failed to get gas price data, skipping transaction"));
return;
}
const { avgGasPriceGwei, gasPricesGwei } = gasData;
// Check if gas price is within tolerance
if (!isGasPriceAcceptable(avgGasPriceGwei)) {
console.log(chalk.yellow(`⛽ Gas price ${avgGasPriceGwei.toFixed(2)} Gwei exceeds threshold, skipping transaction`));
return;
}
// Check for gas price spikes and implement human-like hesitation
const shouldProceed = await shouldProceedWithGasSpike(avgGasPriceGwei, gasPricesGwei, proxyUrl, userAgent);
if (!shouldProceed) {
console.log(chalk.yellow("⏳ Skipping transaction due to gas price conditions"));
return;
}
// Get updated gas data after any hesitation (less verbose)
const finalGasData = await getAverageGasPrice(false, proxyUrl, userAgent);
if (!finalGasData || !isGasPriceAcceptable(finalGasData.avgGasPriceGwei)) {
console.log(chalk.yellow(`⛽ Gas price ${finalGasData?.avgGasPriceGwei?.toFixed(2) || 'N/A'} Gwei above threshold after hesitation, skipping transaction`));
return;
}
console.log(chalk.green(`✅ Gas price ${finalGasData.avgGasPriceGwei.toFixed(2)} Gwei is acceptable, proceeding with transaction`));
// === Decide action: normal send vs ping ===
let action = "normal";
let value;
if (Math.random() < profile.pingBias) {
action = "ping";
value = 0n; // 0 CELO, just burns gas
} else {
const amount = profile.minAmount + Math.random() * (profile.maxAmount - profile.minAmount);
value = ethers.parseEther(amount.toFixed(6));
}
// Determine recipient address
let toAddress = wallet.address;
let pingType = "self";
if (action === "ping") {
const rand = Math.random();
if (rand < 0.5) {
toAddress = wallet.address; // self
pingType = "self";
} else if (rand < 0.7) {
toAddress = "0x0000000000000000000000000000000000000000"; // dead address
pingType = "dead";
} else {
const randomWallet = ethers.Wallet.createRandom();
toAddress = randomWallet.address; // random generated
pingType = "random";
}
}
// Simulate micro-behaviors before sending transaction
console.log(chalk.gray("📱 Simulating device micro-behaviors before transaction..."));
await simulateMicroBehaviors();
const tx = await wallet.sendTransaction({
to: toAddress,
value: value,
gasLimit: GAS_LIMIT
});
console.log(chalk.hex("#7FFF00").bold(`✅ Sent tx: ${tx.hash}`));
// Safely log the gas price, accounting for EIP-1559 transactions.
const gasPrice = tx.gasPrice ?? tx.maxFeePerGas ?? 0n;
if (gasPrice > 0n) {
console.log(chalk.hex("#FF69B4").bold(`⛽ Gas Price (RPC): ${ethers.formatUnits(gasPrice, "gwei")} gwei`));
}
console.log(chalk.dim(`Explorer link: https://celoscan.io/tx/${tx.hash}`));
// Initialize variables outside of the try block to ensure scope
let status = "pending", gasUsed = "", feeCELO = "", gasPriceGwei = "", txNonce = tx.nonce;
try {
// Use Promise.race with a timeout that resolves to null
const receipt = await Promise.race([
tx.wait(),
new Promise(resolve => setTimeout(() => resolve(null), 30000)) // returns null on timeout
]);
if (receipt) {
// Only access receipt properties if it's not null/undefined
status = "confirmed";
// Safely handle potentially missing gasPrice or gasUsed
const gasPriceUsed = receipt?.effectiveGasPrice ?? receipt?.gasPrice ?? 0n;
gasUsed = (receipt?.gasUsed ?? 0n).toString();
gasPriceGwei = ethers.formatUnits(gasPriceUsed, "gwei");
feeCELO = ethers.formatEther(gasPriceUsed * (receipt?.gasUsed ?? 0n));
console.log(chalk.bgGreen.white.bold("🟢 Confirmed!"));
console.log(`Nonce: ${txNonce}`);
console.log(chalk.hex("#ADFF2F").bold(`Gas Used: ${gasUsed}`));
console.log(chalk.hex("#FFB6C1").bold(`Gas Price: ${gasPriceGwei} gwei`));
console.log(chalk.hex("#FFD700").bold(`Fee Paid: ${feeCELO} CELO`));
} else {
console.warn(chalk.bgYellow.white.bold("🟡 No confirmation in 30s, moving on..."));
status = "timeout";
}
} catch (err) {
console.error(chalk.bgRed.white.bold("❌ Error fetching receipt:", err.message));
status = "error";
}
// === Buffer to CSV (daily rotation) ===
const detailedAction = action === "ping" ? `${action}_${pingType}` : action;
const line = [
new Date().toISOString(),
wallet.address,
tx.hash,
txNonce,
gasUsed,
gasPriceGwei,
feeCELO,
status,
detailedAction
].join(",");
bufferTxLog(line);
} catch (err) {
console.error(chalk.bgRed.white.bold("❌ Error in sendTx:", err.message));
throw err; // Re-throw to be caught by safeSendTx for cooldown logic
}
}
/**
* Safely sends a transaction, including retry and cooldown logic.
* @param {ethers.Wallet} wallet - The wallet instance.
* @param {ethers.JsonRpcProvider} provider - The RPC provider.
* @param {object} profile - The wallet's persona profile.
* @param {string} url - The URL of the RPC being used.
* @param {string} proxyUrl - The proxy URL being used.
* @param {string} userAgent - The user agent being used.
*/
async function safeSendTx(wallet, provider, profile, url, proxyUrl, userAgent) {
try {
await sendTx(wallet, provider, profile, url, proxyUrl, userAgent);
} catch (err) {
console.warn(chalk.hex("#FFA500").bold("⚠️ Transaction failed. Checking persona retry bias..."));
// NEW LOGIC: Check retry bias and apply cooldown
if (Math.random() > profile.retryBias) {
console.warn(chalk.hex("#FF8C00")(`⏸ Persona ${wallet.address} cooling down after fail...`));
// Add a small jitter to the cooldown period
const cooldownSec = profile.cooldownAfterFail + Math.floor(Math.random() * 60);
await randomDelay(cooldownSec, cooldownSec);
return;
}
console.warn(chalk.hex("#FFA500").bold("⚠️ Retrying after error..."));
await randomDelay(5, 10);
try { await sendTx(wallet, provider, profile, url, proxyUrl, userAgent); } catch (retryErr) {
console.error(chalk.bgRed.white.bold("❌ Error on retry:", retryErr.message));
}
}
}
// === NEW: Refresh inactive wallets every 30 minutes ===
setInterval(async () => {
console.log(chalk.cyan("🔄 Refreshing inactive wallets..."));
for (const addr of [...inactiveWallets]) {
const profile = walletProfiles[addr];
if (profile && isWithinActiveHours(profile)) {
inactiveWallets.delete(addr);
console.log(chalk.green(`🌅 Wallet ${addr} is now inside active hours`));
}
}
await saveInactive();
}, 30 * 60 * 1000);
/**
* Deletes log files older than 3 days.
*/
async function cleanupOldLogs() {
console.log(chalk.cyan("🗑️ Running scheduled log cleanup..."));
try {
const files = await fs.readdir(LOG_DIR);
const cutoff = Date.now() - (3 * 24 * 60 * 60 * 1000); // 3 days
for (const file of files) {
const filePath = path.join(LOG_DIR, file);
// Skip directories and non-log files
const stats = await fs.stat(filePath);
if (!stats.isFile() || !file.startsWith("tx_log_") || !file.endsWith(".csv")) {
continue;
}
if (stats.mtimeMs < cutoff) {
await fs.unlink(filePath);
console.log(chalk.gray(`[Logs] Deleted old log: ${file}`));
}
}
console.log(chalk.green('✅ Log cleanup complete.'));
} catch (err) {
console.error(chalk.bgRed.white.bold('[Logs] Cleanup error:'), err.message);
}
}
async function main() {
// Check for a `--clear-logs` flag on startup
if (process.argv.includes('--clear-logs')) {
console.log(chalk.yellow.bold(`🗑️ --clear-logs flag detected. Deleting all old log files...`));
try {
const files = await fs.readdir(__dirname);
const logFiles = files.filter(file => /^tx_log_\d{4}-\d{2}-\d{2}\.csv$/.test(file));
for (const file of logFiles) {
await fs.unlink(path.join(__dirname, file));
console.log(chalk.gray(`- Deleted ${file}`));
}
console.log(chalk.green('✅ Old logs cleared successfully.'));
} catch (err) {
console.error(chalk.bgRed.white.bold('❌ Error while clearing old logs:'), err.message);
}
}
// Load keys (env primary, file fallback)
await loadKeysInline();
await loadPersonas();
await loadInactive();
await loadProxies();
// === Initial log file creation and cleanup ===
await initLogFile();
await cleanupOldLogs();
while (true) {
// Pick a wallet and its persona
let key = pickRandomKey();
let wallet = new ethers.Wallet(key);
const profile = ensurePersona(wallet);
// === NEW LOGIC: Check if all wallets are inactive and sleep if so ===
if (inactiveWallets.size >= ALL_WALLETS.length) {
console.warn(chalk.yellow("😴 All wallets are currently inactive. Sleeping for 5 minutes..."));
await randomDelay(240, 360); // 5 minutes
continue;
}