-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
710 lines (587 loc) · 26.1 KB
/
index.js
File metadata and controls
710 lines (587 loc) · 26.1 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
const axios = require('axios');
const fs =require('fs');
const path = require('path');
const moment = require('moment');
const readline = require('readline');
const { clear } = require('console');
const { HttpsProxyAgent } = require('https-proxy-agent');
const { SocksProxyAgent } = require('socks-proxy-agent');
const https = require('https');
const API_BASE_URL = 'https://prod.interlinklabs.ai/api/v1';
const TOKEN_FILE_PATH = path.join(__dirname, 'token.txt');
const PROXIES_FILE_PATH = path.join(__dirname, 'proxies.txt');
const CLAIM_INTERVAL_MS = 4 * 60 * 60 * 1000; // 4 hours
// Enhanced color palette with gradients and special effects
const colors = {
// Primary colors
primary: '\x1b[38;5;39m', // Bright blue
secondary: '\x1b[38;5;198m', // Pink
accent: '\x1b[38;5;118m', // Bright green
warning: '\x1b[38;5;220m', // Gold
error: '\x1b[38;5;196m', // Bright red
success: '\x1b[38;5;46m', // Neon green
// Text colors
white: '\x1b[97m',
gray: '\x1b[38;5;245m',
darkGray: '\x1b[38;5;238m',
lightGray: '\x1b[38;5;252m',
// Special effects
bold: '\x1b[1m',
dim: '\x1b[2m',
italic: '\x1b[3m',
underline: '\x1b[4m',
blink: '\x1b[5m',
reverse: '\x1b[7m',
strikethrough: '\x1b[9m',
// Background colors
bgBlack: '\x1b[40m',
bgPrimary: '\x1b[48;5;39m',
bgSuccess: '\x1b[48;5;46m',
bgWarning: '\x1b[48;5;220m',
bgError: '\x1b[48;5;196m',
// Reset
reset: '\x1b[0m'
};
// Clean box drawing characters for better compatibility
const box = {
topLeft: '+',
topRight: '+',
bottomLeft: '+',
bottomRight: '+',
horizontal: '-',
vertical: '|',
cross: '+',
tee: {
down: '+',
up: '+',
right: '+',
left: '+'
}
};
const spinner = {
frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'],
current: 0,
interval: null,
start(message) {
this.stop();
process.stdout.write('\x1b[?25l'); // Hide cursor
this.interval = setInterval(() => {
process.stdout.write(`\r${colors.primary}${this.frames[this.current]} ${colors.white}${message}${colors.reset} `);
this.current = (this.current + 1) % this.frames.length;
}, 100);
},
stop() {
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
process.stdout.write('\r\x1b[K'); // Clear line
process.stdout.write('\x1b[?25h'); // Show cursor
}
}
};
const logger = {
info: (msg) => {
spinner.stop();
console.log(`${colors.primary} ${colors.white}${msg}${colors.reset}`);
},
wallet: (msg) => {
spinner.stop();
console.log(`${colors.warning} ${colors.white}${msg}${colors.reset}`);
},
warn: (msg) => {
spinner.stop();
console.log(`${colors.warning} ${colors.warning}${msg}${colors.reset}`);
},
error: (msg) => {
spinner.stop();
console.log(`${colors.error} ${colors.error}${msg}${colors.reset}`);
},
success: (msg) => {
spinner.stop();
console.log(`${colors.success} ${colors.success}${msg}${colors.reset}`);
},
loading: (msg) => {
spinner.start(msg);
},
step: (msg) => {
spinner.stop();
console.log(`${colors.secondary} ${colors.white}${msg}${colors.reset}`);
},
claim: (msg) => {
spinner.stop();
console.log(`${colors.accent} ${colors.accent}${colors.bold}${msg}${colors.reset}`);
},
banner: () => {
const width = 70; // Adjusted width to match cardWidth and divider length
const title = 'INTERLINK AUTO CLAIM BOT';
const subtitle = 'AUTOMATED BOT DESIGNED FOR CLAIM TOKEN EVERY 4 HOURS';
const version = 'Telegram: https://t.me/earningdropshub';
console.log();
// Clean banner with consistent borders
console.log(`${colors.primary}${box.topLeft}${box.horizontal.repeat(width - 2)}${box.topRight}${colors.reset}`);
console.log(`${colors.primary}${box.vertical}${' '.repeat(width - 2)}${box.vertical}${colors.reset}`);
// Title centered
const titlePadding = Math.floor((width - 2 - title.length) / 2);
const titleSpace = width - 2 - titlePadding - title.length;
console.log(`${colors.primary}${box.vertical}${' '.repeat(titlePadding)}${colors.accent}${colors.bold}${title}${colors.reset}${' '.repeat(titleSpace)}${colors.primary}${box.vertical}${colors.reset}`);
// Subtitle centered
const subtitlePadding = Math.floor((width - 2 - subtitle.length) / 2);
const subtitleSpace = width - 2 - subtitlePadding - subtitle.length;
console.log(`${colors.primary}${box.vertical}${' '.repeat(subtitlePadding)}${colors.secondary}${subtitle}${colors.reset}${' '.repeat(subtitleSpace)}${colors.primary}${box.vertical}${colors.reset}`);
console.log(`${colors.primary}${box.vertical}${' '.repeat(width - 2)}${box.vertical}${colors.reset}`);
// Version centered
const versionPadding = Math.floor((width - 2 - version.length) / 2);
const versionSpace = width - 2 - versionPadding - version.length;
console.log(`${colors.primary}${box.vertical}${' '.repeat(versionPadding)}${colors.gray}${colors.italic}${version}${colors.reset}${' '.repeat(versionSpace)}${colors.primary}${box.vertical}${colors.reset}`);
console.log(`${colors.primary}${box.vertical}${' '.repeat(width - 2)}${box.vertical}${colors.reset}`);
console.log(`${colors.primary}${box.bottomLeft}${box.horizontal.repeat(width - 2)}${box.bottomRight}${colors.reset}`);
console.log();
// Footer - Removed "Powered by Advanced Automation"
// const footerText = "Powered by Advanced Automation";
// const footerPadding = Math.floor((width - footerText.length) / 2);
// console.log(`${' '.repeat(footerPadding)}${colors.gray}${footerText}${colors.reset}`);
console.log(); // Keep an empty line for spacing if desired
},
divider: (char = '-', length = 70) => { // Default length matches cardWidth
console.log(`${colors.darkGray}${char.repeat(length)}${colors.reset}`);
},
section: (title) => {
console.log();
logger.divider('='); // Uses the default length for divider (70)
// Center the section title within the divider width
const titlePadding = Math.floor((70 - (title.length + 2)) / 2); // +2 for spaces around title
const titleSpace = 70 - (title.length + 2) - titlePadding;
console.log(`${colors.darkGray}${box.vertical}${' '.repeat(titlePadding)}${colors.accent}${colors.bold}${title.toUpperCase()}${colors.reset}${' '.repeat(titleSpace)}${colors.darkGray}${box.vertical}${colors.reset}`);
logger.divider('='); // Uses the default length for divider (70)
}
};
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function promptInput(question) {
return new Promise((resolve) => {
const prompt = `${colors.secondary} ${colors.white}${question}${colors.reset} `;
rl.question(prompt, (answer) => {
resolve(answer.trim());
});
});
}
async function sendOtp(apiClient, loginId, passcode, email) {
try {
const payload = { loginId, passcode, email };
logger.loading('Sending OTP to your email...');
const response = await apiClient.post('/auth/send-otp-email-verify-login', payload);
if (response.data.statusCode === 200) {
logger.success('OTP sent successfully!');
logger.info('Check your email inbox (and spam folder)');
console.log(`${colors.gray}${colors.italic}💡 Tip: If OTP doesn't arrive, restart the bot with Ctrl+C${colors.reset}`);
} else {
logger.error(`Failed to send OTP: ${JSON.stringify(response.data)}`);
}
} catch (error) {
logger.error(`Error sending OTP: ${error.response?.data?.message || error.message}`);
if (error.response?.data) {
logger.error(`Details: ${JSON.stringify(error.response.data)}`);
}
}
}
async function verifyOtp(apiClient, loginId, otp) {
try {
const payload = { loginId, otp };
logger.loading('Verifying OTP...');
const response = await apiClient.post('/auth/check-otp-email-verify-login', payload);
if (response.data.statusCode === 200) {
logger.success('OTP verified successfully!');
const token = response.data.data.jwtToken;
saveToken(token);
return token;
} else {
logger.error(`OTP verification failed: ${JSON.stringify(response.data)}`);
return null;
}
} catch (error) {
logger.error(`Error verifying OTP: ${error.response?.data?.message || error.message}`);
if (error.response?.data) {
logger.error(`Details: ${JSON.stringify(error.response.data)}`);
}
return null;
}
}
function saveToken(token) {
try {
fs.writeFileSync(TOKEN_FILE_PATH, token);
logger.info(`Token saved securely`);
} catch (error) {
logger.error(`Error saving token: ${error.message}`);
}
}
async function login(proxies) {
logger.section('Authentication Required');
const loginId = await promptInput('Enter your login ID (or email):');
const passcode = await promptInput('Enter your passcode:');
const email = await promptInput('Enter your email:');
let apiClient;
const proxy = getRandomProxy(proxies);
if (proxy) {
logger.step(`Using proxy: ${colors.gray}${proxy}${colors.reset}`);
apiClient = createApiClient(null, proxy);
} else {
logger.step('Connecting directly (no proxy)');
apiClient = createApiClient(null);
}
await sendOtp(apiClient, loginId, passcode, email);
const otp = await promptInput('Enter the OTP from your email:');
const token = await verifyOtp(apiClient, loginId, otp);
return token;
}
function readToken() {
try {
return fs.readFileSync(TOKEN_FILE_PATH, 'utf8').trim();
} catch (error) {
logger.warn('No saved token found - login required');
return null;
}
}
function readProxies() {
try {
if (!fs.existsSync(PROXIES_FILE_PATH)) {
logger.warn('No proxy file found - running without proxies');
return [];
}
const content = fs.readFileSync(PROXIES_FILE_PATH, 'utf8');
const proxies = content.split('\n')
.map(line => line.trim())
.filter(line => line && !line.startsWith('#'));
if (proxies.length > 0) {
logger.info(`Loaded ${proxies.length} proxies`);
}
return proxies;
} catch (error) {
logger.error(`Error reading proxies: ${error.message}`);
return [];
}
}
function getRandomProxy(proxies) {
if (!proxies.length) return null;
return proxies[Math.floor(Math.random() * proxies.length)];
}
function createProxyAgent(proxyUrl) {
if (!proxyUrl) return null;
if (proxyUrl.startsWith('socks://') || proxyUrl.startsWith('socks4://') || proxyUrl.startsWith('socks5://')) {
return new SocksProxyAgent(proxyUrl);
} else {
return new HttpsProxyAgent(proxyUrl);
}
}
function createApiClient(token, proxy = null) {
const config = {
baseURL: API_BASE_URL,
headers: {
'User-Agent': 'okhttp/4.12.0',
'Accept-Encoding': 'gzip'
},
timeout: 30000, // 30 seconds
httpsAgent: new https.Agent({
rejectUnauthorized: false // Added to bypass SSL verification if needed, be cautious with this in production
})
};
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
if (proxy) {
try {
const proxyAgent = createProxyAgent(proxy);
config.httpsAgent = proxyAgent;
config.proxy = false; // Axios needs this to be false when an agent is used
} catch (error) {
logger.error(`Proxy setup failed: ${error.message}`);
}
}
return axios.create(config);
}
function formatTimeRemaining(milliseconds) {
if (milliseconds <= 0) return '00:00:00';
const seconds = Math.floor((milliseconds / 1000) % 60);
const minutes = Math.floor((milliseconds / (1000 * 60)) % 60);
const hours = Math.floor((milliseconds / (1000 * 60 * 60)) % 24);
return [hours, minutes, seconds]
.map(val => val.toString().padStart(2, '0'))
.join(':');
}
async function getCurrentUser(apiClient) {
try {
const response = await apiClient.get('/auth/current-user');
return response.data.data;
} catch (error) {
logger.error(`Failed to get user info: ${error.response?.data?.message || error.message}`);
return null;
}
}
async function getTokenBalance(apiClient) {
try {
const response = await apiClient.get('/token/get-token');
return response.data.data;
} catch (error) {
logger.error(`Failed to get token balance: ${error.response?.data?.message || error.message}`);
return null;
}
}
async function checkIsClaimable(apiClient) {
try {
const response = await apiClient.get('/token/check-is-claimable');
return response.data.data;
} catch (error) {
logger.error(`Failed to check claim status: ${error.response?.data?.message || error.message}`);
// Return a default nextFrame far in the future to avoid rapid retries on error
return { isClaimable: false, nextFrame: Date.now() + 1000 * 60 * 5 };
}
}
async function claimAirdrop(apiClient) {
try {
const response = await apiClient.post('/token/claim-airdrop');
logger.claim('Airdrop claimed successfully!');
return response.data;
} catch (error) {
logger.error(`Claim failed: ${error.response?.data?.message || error.message}`);
return null;
}
}
function displayUserInfo(userInfo, tokenInfo) {
if (!userInfo || !tokenInfo) return;
console.log();
// User Information Card - Fixed width and clean borders
const cardWidth = 70; // Consistent width for cards
console.log(`${colors.primary}${box.topLeft}${box.horizontal.repeat(cardWidth - 2)}${box.topRight}${colors.reset}`);
// Adjusted padding for the title "USER PROFILE"
const userProfileTitle = "USER PROFILE";
const userProfileTitlePadding = Math.floor((cardWidth - 2 - userProfileTitle.length) / 2);
const userProfileTitleSpace = cardWidth - 2 - userProfileTitlePadding - userProfileTitle.length;
console.log(`${colors.primary}${box.vertical}${' '.repeat(userProfileTitlePadding)}${colors.accent}${colors.bold}${userProfileTitle}${colors.reset}${' '.repeat(userProfileTitleSpace)}${colors.primary}${box.vertical}${colors.reset}`);
console.log(`${colors.primary}${box.vertical}${box.horizontal.repeat(cardWidth - 2)}${box.vertical}${colors.reset}`);
// Username
const username = userInfo.username || 'N/A';
const usernameLine = ` Username: ${colors.accent}${username}${colors.reset}`;
const usernamePadding = cardWidth - 2 - (11 + username.length); // " Username: " is 11 chars + 2 for borders
console.log(`${colors.primary}${box.vertical}${colors.white}${usernameLine}${' '.repeat(Math.max(0, usernamePadding))}${colors.primary}${box.vertical}${colors.reset}`);
// Email
const email = userInfo.email || 'N/A';
const emailDisplay = email.length > (cardWidth - 15) ? `${email.slice(0, cardWidth - 18)}...` : email; // Adjust truncation based on new width
const emailLine = ` Email: ${colors.lightGray}${emailDisplay}${colors.reset}`;
const emailPadding = cardWidth - 2 - (8 + emailDisplay.length); // " Email: " is 8 chars + 2 for borders
console.log(`${colors.primary}${box.vertical}${colors.white}${emailLine}${' '.repeat(Math.max(0, emailPadding))}${colors.primary}${box.vertical}${colors.reset}`);
// User ID
const userId = userInfo.loginId ? userInfo.loginId.toString() : 'N/A';
const userIdLine = ` User ID: ${colors.gray}${userId}${colors.reset}`;
const userIdPadding = cardWidth - 2 - (10 + userId.length); // " User ID: " is 10 chars + 2 for borders
console.log(`${colors.primary}${box.vertical}${colors.white}${userIdLine}${' '.repeat(Math.max(0, userIdPadding))}${colors.primary}${box.vertical}${colors.reset}`);
// Wallet
const walletAddr = userInfo.connectedAccounts?.wallet?.address || 'Not connected';
const walletDisplay = walletAddr.length > (cardWidth - 15) ? `${walletAddr.slice(0, Math.floor((cardWidth - 15 - 3) / 2))}...${walletAddr.slice(-Math.ceil((cardWidth - 15 - 3) / 2))}` : walletAddr; // Adjust truncation
const walletLine = ` Wallet: ${colors.warning}${walletDisplay}${colors.reset}`;
const walletPadding = cardWidth - 2 - (9 + walletDisplay.length); // " Wallet: " is 9 chars + 2 for borders
console.log(`${colors.primary}${box.vertical}${colors.white}${walletLine}${' '.repeat(Math.max(0, walletPadding))}${colors.primary}${box.vertical}${colors.reset}`);
console.log(`${colors.primary}${box.bottomLeft}${box.horizontal.repeat(cardWidth - 2)}${box.bottomRight}${colors.reset}`);
console.log();
// Token Balance Card - Fixed width and clean borders
console.log(`${colors.secondary}${box.topLeft}${box.horizontal.repeat(cardWidth - 2)}${box.topRight}${colors.reset}`);
// Adjusted padding for the title "TOKEN PORTFOLIO"
const tokenPortfolioTitle = "TOKEN PORTFOLIO";
const tokenPortfolioTitlePadding = Math.floor((cardWidth - 2 - tokenPortfolioTitle.length) / 2);
const tokenPortfolioTitleSpace = cardWidth - 2 - tokenPortfolioTitlePadding - tokenPortfolioTitle.length;
console.log(`${colors.secondary}${box.vertical}${' '.repeat(tokenPortfolioTitlePadding)}${colors.warning}${colors.bold}${tokenPortfolioTitle}${colors.reset}${' '.repeat(tokenPortfolioTitleSpace)}${colors.secondary}${box.vertical}${colors.reset}`);
console.log(`${colors.secondary}${box.vertical}${box.horizontal.repeat(cardWidth - 2)}${box.vertical}${colors.reset}`);
// Token balances
const tokens = [
{ name: 'Gold Tokens', value: tokenInfo.interlinkGoldTokenAmount, color: colors.warning },
{ name: 'Silver Tokens', value: tokenInfo.interlinkSilverTokenAmount, color: colors.lightGray },
{ name: 'Diamond Tokens', value: tokenInfo.interlinkDiamondTokenAmount, color: colors.primary },
{ name: 'Interlink Tokens', value: tokenInfo.interlinkTokenAmount, color: colors.accent }
];
tokens.forEach(token => {
const valueStr = token.value !== undefined ? token.value.toString() : '0';
const tokenLine = ` ${token.name}: ${token.color}${colors.bold}${valueStr}${colors.reset}`;
// Adjusted padding: 2 for borders, 2 for leading spaces, 1 for colon and space after name
const tokenPadding = cardWidth - 2 - (token.name.length + valueStr.length + 4);
console.log(`${colors.secondary}${box.vertical}${colors.white}${tokenLine}${' '.repeat(Math.max(0, tokenPadding))}${colors.secondary}${box.vertical}${colors.reset}`);
});
console.log(`${colors.secondary}${box.vertical}${box.horizontal.repeat(cardWidth - 2)}${box.vertical}${colors.reset}`);
// Referral ID
const referralId = tokenInfo.userReferralId ? tokenInfo.userReferralId.toString() : 'N/A';
const refLine = ` Referral ID: ${colors.accent}${referralId}${colors.reset}`;
const refPadding = cardWidth - 2 - (14 + referralId.length); // " Referral ID: " is 14 chars + 2 for borders
console.log(`${colors.secondary}${box.vertical}${colors.white}${refLine}${' '.repeat(Math.max(0, refPadding))}${colors.secondary}${box.vertical}${colors.reset}`);
// Last claim
const lastClaim = tokenInfo.lastClaimTime ? moment(tokenInfo.lastClaimTime).format('MMM DD, HH:mm:ss') : 'N/A';
const claimLine = ` Last Claim: ${colors.gray}${lastClaim}${colors.reset}`;
const claimPadding = cardWidth - 2 - (13 + lastClaim.length); // " Last Claim: " is 13 chars + 2 for borders
console.log(`${colors.secondary}${box.vertical}${colors.white}${claimLine}${' '.repeat(Math.max(0, claimPadding))}${colors.secondary}${box.vertical}${colors.reset}`);
console.log(`${colors.secondary}${box.bottomLeft}${box.horizontal.repeat(cardWidth - 2)}${box.bottomRight}${colors.reset}`);
console.log();
}
async function tryConnect(token, proxies) {
let apiClient;
let userInfo = null;
let tokenInfo = null;
logger.step('Establishing connection...');
apiClient = createApiClient(token); // Try direct connection first
logger.loading('Retrieving user information...');
userInfo = await getCurrentUser(apiClient);
if (!userInfo && proxies.length > 0) {
let attempts = 0;
const maxAttempts = Math.min(proxies.length, 5); // Try up to 5 proxies or all if fewer
logger.warn('Direct connection failed, trying proxies...');
while (!userInfo && attempts < maxAttempts) {
const proxy = proxies[attempts]; // Use proxies in order or random
logger.step(`Proxy attempt ${attempts + 1}/${maxAttempts} using ${proxy}`);
apiClient = createApiClient(token, proxy);
logger.loading('Retrieving user information...');
userInfo = await getCurrentUser(apiClient);
attempts++;
if (!userInfo) {
logger.warn(`Proxy attempt ${attempts} failed, trying next...`);
}
}
}
if (userInfo) {
logger.loading('Retrieving token balance...');
tokenInfo = await getTokenBalance(apiClient); // Use the last successful apiClient
}
return { apiClient, userInfo, tokenInfo };
}
async function runBot() {
try {
clear(); // Clears the console
logger.banner();
// Initialize
logger.step('Initializing bot systems...');
const proxies = readProxies();
let token = readToken();
if (!token) {
token = await login(proxies);
if (!token) {
logger.error('Authentication failed - exiting');
process.exit(1);
}
}
// Connect and get user info
let { apiClient, userInfo, tokenInfo: initialTokenInfo } = await tryConnect(token, proxies);
if (!userInfo || !initialTokenInfo) {
logger.error('Connection failed, attempting re-authentication...');
if (fs.existsSync(TOKEN_FILE_PATH)) { // Check if token file exists before trying to delete
fs.unlinkSync(TOKEN_FILE_PATH); // Remove invalid token
}
token = await login(proxies);
if (!token) {
logger.error('Re-authentication failed - exiting');
process.exit(1);
}
const result = await tryConnect(token, proxies);
apiClient = result.apiClient;
userInfo = result.userInfo;
initialTokenInfo = result.tokenInfo;
if (!userInfo || !initialTokenInfo) {
logger.error('Unable to establish connection - check credentials and network');
process.exit(1);
}
}
let tokenInfo = initialTokenInfo;
// Success message
logger.success(`Connected as ${colors.accent}${colors.bold}${userInfo.username}${colors.reset}`);
logger.info(`Session started: ${colors.gray}${moment().format('YYYY-MM-DD HH:mm:ss')}${colors.reset}`);
displayUserInfo(userInfo, tokenInfo);
// Claim function
async function attemptClaim() {
let currentApiClient = apiClient; // Default to the initially successful client
if (proxies.length > 0) { // If proxies are available, pick one for the claim attempt
const randomProxy = getRandomProxy(proxies);
logger.step(`Attempting claim with proxy: ${randomProxy || 'direct connection'}`);
currentApiClient = createApiClient(token, randomProxy);
} else {
logger.step('Attempting claim with direct connection');
}
logger.loading('Checking claim availability...');
const claimCheck = await checkIsClaimable(currentApiClient);
if (claimCheck.isClaimable) {
logger.loading('Claiming airdrop...');
const claimResult = await claimAirdrop(currentApiClient);
if(claimResult){ // If claim was successful
logger.loading('Updating token information...');
const newTokenInfo = await getTokenBalance(currentApiClient); // Fetch updated balance
if (newTokenInfo) {
tokenInfo = newTokenInfo;
displayUserInfo(userInfo, tokenInfo); // Update display
}
}
} else {
logger.info('Airdrop not yet claimable');
}
return claimCheck.nextFrame; // Return the timestamp for the next possible claim
}
// Initial claim check
logger.section('Claim Status Check');
let nextClaimTime = await attemptClaim();
// Countdown display
const updateCountdown = () => {
const now = Date.now();
const timeRemaining = Math.max(0, nextClaimTime - now);
const timeStr = formatTimeRemaining(timeRemaining);
const countdownLine = `${colors.accent} Next claim in: ${colors.bold}${colors.warning}${timeStr}${colors.reset}`;
process.stdout.write(`\r${countdownLine}${' '.repeat(30)}`); // Increased padding to clear previous line fully
if (timeRemaining <= 0) {
process.stdout.write('\n'); // Move to next line before logging
logger.step('Claim time reached!');
attemptClaim().then(newNextFrame => {
nextClaimTime = newNextFrame;
// No need to call scheduleNextCheck here as setInterval handles the periodic checks
});
}
};
// Start countdown and periodic checks
// These variables need to be accessible in the SIGINT handler
let countdownIntervalId = setInterval(updateCountdown, 1000); // Update countdown every second
let claimTimeoutId;
// Schedule checks
const scheduleNextCheck = () => {
if (claimTimeoutId) clearTimeout(claimTimeoutId); // Clear existing timeout if any
const now = Date.now();
const timeUntilNextCheck = Math.max(1000, nextClaimTime - now); // Ensure at least 1s delay
claimTimeoutId = setTimeout(async () => {
logger.step('Executing scheduled claim check...');
nextClaimTime = await attemptClaim();
scheduleNextCheck(); // Reschedule for the next claim time
}, timeUntilNextCheck);
};
scheduleNextCheck(); // Start the first scheduled check
// Final status
logger.section('Bot Status');
logger.success('Auto-claim system is now active!');
logger.info('Claims will be processed automatically');
console.log(`${colors.gray}${colors.italic}💡 Press Ctrl+C to stop the bot${colors.reset}`);
console.log();
// Make interval and timeout IDs available for cleanup
global.botCountdownInterval = countdownIntervalId;
global.botClaimTimeout = claimTimeoutId;
} catch (error) {
spinner.stop();
logger.error(`Critical error: ${error.message}`);
// console.error(error.stack); // For more detailed debugging
process.exit(1);
}
}
// Graceful shutdown
process.on('SIGINT', () => {
spinner.stop();
console.log(`\n\n${colors.warning} ${colors.white}Bot stopped by user${colors.reset}`);
console.log(`${colors.gray}Thank you for using Interlink Auto Bot!${colors.reset}\n`);
if (rl) rl.close(); // Ensure readline interface is closed
// Clear any timers
if (typeof global.botCountdownInterval !== 'undefined') clearInterval(global.botCountdownInterval);
if (typeof global.botClaimTimeout !== 'undefined') clearTimeout(global.botClaimTimeout);
process.exit(0);
});
runBot().finally(() => {
if (rl) {
rl.close();
}
});