-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitquery-stream.js
More file actions
11346 lines (9740 loc) · 422 KB
/
bitquery-stream.js
File metadata and controls
11346 lines (9740 loc) · 422 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 * as fs from 'fs';
import * as path from 'path';
import fetch from 'node-fetch';
import { exec, execSync } from 'child_process';
import { fileURLToPath } from 'url';
import 'dotenv/config'
import inquirer from 'inquirer';
import readline from 'readline'; // Import readline for keyboard input
import clipboardy from 'clipboardy'; // Import clipboardy for clipboard access
import chalk from 'chalk'; // Import chalk for colored output
import Chart from 'cli-chart'; // Import cli-chart for drawing charts
import { stringifyQueryConfig } from './queries.js';
import { logToFile } from './logger.js';
// Removed unused import - using appState instance instead
import { colors } from './colors.js';
import { createKeyboardHandler } from './keyboardHandler.js';
import { rateLimiter, LoadingSpinner } from './utils.js';
import { Keypair, Connection, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js';
import bs58 from 'bs58';
import cliProgress from 'cli-progress';
import { pumpfunCrossMarketQuery, pumpTradesQuery, monitoringMoreQuery, graduatedQuery, fallbackQuery, tokensMin500TxQuery, trendingGainersQuery } from './queries.js';
// Jupiter analysis functions moved to modules/ai-enhanced-analyzer.js
import { aiEnhancedAnalyzer } from './modules/ai-enhanced-analyzer.js';
import { autoTrading } from './modules/auto-trading.js';
import { aiTradingIntegration } from './modules/ai-trading-integration.js';
import { QuickTrading } from './modules/quick-trading.js';
import {
getBestQuote,
getSwapTransaction,
performSwap,
getTokenBalance,
getSolBalance,
validateSwap,
getSwapHistory,
getTokenMetadata,
getAllTokenBalances,
getTokenInfo,
getTokenPrice,
getBatchTokenPrices,
calculateTokenPnL,
burnTokens,
canTokenBeSold,
closeTokenAccount,
sendToDeadAddress,
getQuickTokenDisplay,
getEnhancedTokenInfo,
clearTokenBalanceCache,
getRpcEndpoint,
performLiteSwap
} from './modules/jupiter-swap.js';
import { SettingsManager } from './modules/settings-manager.js';
import {
optimizedRateLimiter,
CacheManager,
PerformanceMonitor,
OptimizedDisplay,
parallelTokenAnalysis,
optimizedFetch,
performanceConfig
} from './utils.js';
import { trendingOptimizer } from './modules/performance-optimizer.js';
import { connectionManager } from './modules/connection-manager.js';
import { OptimizedAppState } from './state.js';
// Initialize optimized components
const performanceMonitor = new PerformanceMonitor();
const cacheManager = new CacheManager();
const optimizedDisplay = new OptimizedDisplay();
// Initialize settings manager
const settingsManager = new SettingsManager();
// Replace state initialization
let appState = new OptimizedAppState();
// Function to wait for Space key input
function waitForSpaceKey() {
return new Promise((resolve) => {
const originalRawMode = process.stdin.isRaw;
const originalEncoding = process.stdin.encoding;
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.setEncoding('utf8');
const onData = (data) => {
if (data === ' ') {
process.stdin.setRawMode(false);
process.stdin.pause();
process.stdin.setRawMode(originalRawMode);
process.stdin.setEncoding(originalEncoding);
process.stdin.removeListener('data', onData);
resolve();
}
};
process.stdin.on('data', onData);
});
}
// Helper function to handle wallet loading errors with options
async function handleWalletLoadError(walletName, returnFunction) {
console.log(`${colors.red}❌ Failed to load wallet: ${walletName}${colors.reset}`);
const { action } = await inquirer.prompt([
{
type: 'list',
name: 'action',
message: 'Wallet loading failed. What would you like to do?',
choices: [
{ name: '🔄 Try loading wallet again', value: 'retry' },
{ name: '💼 Select different wallet', value: 'select' },
{ name: '➕ Create new wallet', value: 'create' },
{ name: '❌ Go back to main menu', value: 'back' }
]
}
]);
if (action === 'retry') {
console.log(`${colors.cyan}🔄 Retrying wallet load...${colors.reset}`);
return await returnFunction(); // Recursive call
} else if (action === 'select') {
console.log(`${colors.cyan}💼 Opening wallet selector...${colors.reset}`);
await walletManagerMenu();
return await returnFunction(); // Recursive call
} else if (action === 'create') {
console.log(`${colors.cyan}➕ Opening wallet creation...${colors.reset}`);
await createWallet();
return await returnFunction(); // Recursive call
} else {
console.log(`${colors.yellow}⚠️ Returning to main menu${colors.reset}`);
return;
}
}
// Universal function to wait for Back key (B) or Space key
function waitForBackOrSpaceKey() {
return new Promise((resolve) => {
const originalRawMode = process.stdin.isRaw;
const originalEncoding = process.stdin.encoding;
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.setEncoding('utf8');
const onData = (data) => {
if (data === ' ' || data.toLowerCase() === 'b') {
process.stdin.setRawMode(false);
process.stdin.pause();
process.stdin.setRawMode(originalRawMode);
process.stdin.setEncoding(originalEncoding);
process.stdin.removeListener('data', onData);
resolve(data.toLowerCase() === 'b' ? 'back' : 'continue');
}
};
process.stdin.on('data', onData);
});
}
// Function to add Back option to menu choices
function addBackOption(choices, backText = 'Back to Main Menu') {
return [
...choices,
{ name: `${colors.yellow}⬅️ ${backText}${colors.reset}`, value: 'back' }
];
}
// Universal function to handle SPACE key for navigation
async function handleSpaceNavigation() {
console.log(`\n${colors.cyan}Press SPACE to go back${colors.reset}`);
await waitForSpaceKey();
}
// Function to show navigation help
function showNavigationHelp() {
console.log(`\n${colors.cyan}Navigation Keys:${colors.reset}`);
console.log(` ${colors.white}B${colors.reset} - Back to previous menu`);
console.log(` ${colors.white}SPACE${colors.reset} - Continue`);
console.log(` ${colors.white}Q${colors.reset} - Exit`);
console.log('');
}
// Create instances
const spinner = new LoadingSpinner();
// Get current directory with ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Create logs directory if it doesn't exist
const logsDir = path.join(__dirname, 'logs');
if (!fs.existsSync(logsDir)) {
fs.mkdirSync(logsDir);
}
// Add UI helper functions
function showConnectionStatus() {
const status = connectionStatus.getStatus();
const statusBar = [];
// BitQuery Status
const bitqueryColor = status.bitquery.status === 'connected' ? colors.green :
status.bitquery.status === 'error' ? colors.red : colors.yellow;
const bitqueryIcon = status.bitquery.status === 'connected' ? '●' :
status.bitquery.status === 'error' ? '✗' : '○';
statusBar.push(`${bitqueryColor}${bitqueryIcon} BitQuery${colors.reset}`);
// Jupiter Status
const jupiterColor = status.jupiter.status === 'connected' ? colors.green :
status.jupiter.status === 'error' ? colors.red : colors.yellow;
const jupiterIcon = status.jupiter.status === 'connected' ? '●' :
status.jupiter.status === 'error' ? '✗' : '○';
statusBar.push(`${jupiterColor}${jupiterIcon} Jupiter${colors.reset}`);
// Birdeye Status
const birdeyeColor = status.birdeye.status === 'connected' ? colors.green :
status.birdeye.status === 'error' ? colors.red : colors.yellow;
const birdeyeIcon = status.birdeye.status === 'connected' ? '●' :
status.birdeye.status === 'error' ? '✗' : '○';
statusBar.push(`${birdeyeColor}${birdeyeIcon} Birdeye${colors.reset}`);
console.log(`${colors.cyan}${colors.bright}🔗 Connection Status:${colors.reset} ${statusBar.join(' | ')}`);
// Show errors if any
const errors = [];
if (status.bitquery.error) errors.push(`BitQuery: ${status.bitquery.error}`);
if (status.jupiter.error) errors.push(`Jupiter: ${status.jupiter.error}`);
if (status.birdeye.error) errors.push(`Birdeye: ${status.birdeye.error}`);
if (errors.length > 0) {
console.log(`${colors.red}⚠️ Connection Issues:${colors.reset} ${errors.join(' | ')}`);
}
console.log(''); // Empty line for spacing
}
function showLogo() {
console.clear();
}
// Update mode descriptions
const modeDescriptions = {
pump: {
title: `${colors.green}Pump Detection${colors.reset}`,
description: [
'Monitors trades for potential pump signals and early entry opportunities.',
'Features:',
'• Real-time pump detection',
'• Early signal notifications',
'• Price movement analysis',
'• Volume spike detection'
]
},
pumpfunCrossMarket: {
title: `${colors.yellow}Pumpfun CrossMarket${colors.reset}`,
description: [
'Scans for cross-market asymmetry opportunities on Pumpfun.',
'Features:',
'• Finds tokens with price asymmetry ≤ 0.1',
'• Filters for recent, successful trades',
'• Shows top tokens by price'
]
},
graduated: {
title: `${colors.purple}Graduated${colors.reset}`,
description: [
'Monitors DEX pools with bonding curve progress.',
'Features:',
'• Tracks pool liquidity and bonding curves',
'• Shows bonding curve progress percentage',
'• Monitors pool balances and prices',
'• Real-time pool analytics'
]
},
dexscreenerBoosted: {
title: `${colors.blue}Dexscreener Boosted${colors.reset}`,
description: [
'Monitors boosted tokens from Dexscreener API.',
'Features:',
'• Real-time boosted token tracking',
'• Enhanced price and volume data',
'• Market sentiment analysis',
'• Interactive token selection',
'• Multi-source price verification'
]
},
min500tx: {
title: `${colors.green}Min 500 TX (Buy/Sell)${colors.reset}`,
description: [
'Monitors tokens with at least 500 buy/sell transactions in the last 60 minutes.',
'Features:',
'• Groups trades by token mint and applies tx count filter',
'• Shows high-activity tokens for potential momentum',
'• You can adjust the time window and threshold in the query variables'
]
}
};
// Update showInitialQueryMenu function
async function showInitialQueryMenu() {
const choices = [
{
name: `${colors.green}Pump Detection${colors.reset} - Monitor for potential pump signals`,
value: 'pump',
short: 'Pump Detection'
},
{
name: `${colors.yellow}Pumpfun CrossMarket${colors.reset} - Cross-market asymmetry scanner`,
value: 'pumpfunCrossMarket',
short: 'Pumpfun CrossMarket'
},
{
name: `${colors.purple}Graduated${colors.reset} - Monitor DEX pools with bonding curves`,
value: 'graduated',
short: 'Graduated'
},
{
name: `${colors.blue}Dexscreener Boosted${colors.reset} - Monitor boosted tokens from Dexscreener`,
value: 'dexscreenerBoosted',
short: 'Dexscreener Boosted'
},
{
name: `${colors.green}Min 500 TX (Buy/Sell)${colors.reset} - Tokens with at least 500 tx in last 60m`,
value: 'min500tx',
short: 'Min 500 TX'
},
{
name: `${colors.magenta}🔥 Trending & Gainers (5m)${colors.reset} - Monitor trending tokens in last 5 minutes`,
value: 'trending',
short: 'Trending & Gainers'
}
];
// Add option to use last selected mode if it exists and is different from default
if (settings.lastSelectedMode && settings.lastSelectedMode !== 'pump') {
const lastModeName = choices.find(c => c.value === settings.lastSelectedMode)?.short || settings.lastSelectedMode;
choices.unshift({
name: `${colors.cyan}Last Used: ${lastModeName}${colors.reset} - Continue with previous mode`,
value: settings.lastSelectedMode,
short: `Last: ${lastModeName}`
});
}
const { queryType } = await inquirer.prompt([
{
type: 'list',
name: 'queryType',
message: 'Select monitoring mode:',
prefix: '🔍',
choices: choices
}
]);
// Save the selected mode
settings.lastSelectedMode = queryType;
saveSettings();
return queryType;
}
// Add state object for managing trade data and display
// Remove global myHeaders definition
// Mode descriptions for display
const MODE_DESCRIPTIONS = {
pump: 'Monitor for potential pump signals and early entry opportunities',
pumpfunCrossMarket: 'Cross-market asymmetry scanner for Pumpfun',
graduated: 'Monitor DEX pools with bonding curves',
dexscreenerBoosted: 'Monitor boosted tokens from Dexscreener',
min500tx: 'Tokens with at least 500 transactions in last 60 minutes',
trending: 'Monitor trending and gaining tokens in last 5 minutes with Jupiter API integration'
};
// Add caching for trending token display
const trendingDisplayCache = new Map();
const TRENDING_CACHE_DURATION = 30000; // 30 seconds cache
// Fast loading indicator for trending mode
function showTrendingLoading() {
console.clear();
console.log(`${colors.cyan}🔥 Processing trending tokens...${colors.reset}`);
console.log(`${colors.yellow}⚡ Optimized for speed - please wait${colors.reset}`);
}
export function displayTrendingToken(index, trendingData) {
if (!trendingData || index >= trendingData.length) {
console.log(`${colors.red}❌ Invalid trending token index${colors.reset}`);
return;
}
const cacheKey = `trending_${index}_${trendingData.length}`;
const cached = trendingDisplayCache.get(cacheKey);
// Check if we have a valid cached version
if (cached && (Date.now() - cached.timestamp) < TRENDING_CACHE_DURATION) {
console.log(cached.display);
return;
}
const t = trendingData[index];
const m = t.metrics;
const j = m.jupiter;
// Build display string efficiently
let display = '';
// Header
display += `${colors.cyan}📊 Trending Token ${index + 1}/${trendingData.length}${colors.reset}\n`;
display += `${colors.white}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}\n`;
// Token name and momentum
const momentumColor = m.momentum >= 0 ? colors.green : colors.red;
const momentumSymbol = m.momentum >= 0 ? '🚀' : '📉';
display += `${colors.yellow}${t.token.Symbol}${colors.reset} ${momentumColor}${momentumSymbol} ${m.momentum.toFixed(2)}%${colors.reset}\n`;
// Token address
display += `${colors.blue}📍 Address: ${t.token.MintAddress}${colors.reset}\n`;
// Price and changes
const priceChangeColor = m.priceChange >= 0 ? colors.green : colors.red;
const priceChangeSymbol = m.priceChange >= 0 ? '↗' : '↘';
display += `💰 Price: $${m.currentPrice.toFixed(6)} ${priceChangeColor}${priceChangeSymbol} ${m.priceChange.toFixed(2)}%${colors.reset}\n`;
// Volume metrics
const volumeChangeColor = m.volumeChange >= 0 ? colors.green : colors.red;
const volumeChangeSymbol = m.volumeChange >= 0 ? '↗' : '↘';
display += `📊 Volume (5m): $${m.recentVolume.toLocaleString()} ${volumeChangeColor}${volumeChangeSymbol} ${m.volumeChange.toFixed(2)}%${colors.reset}\n`;
// Trade frequency
const freqChangeColor = m.freqChange >= 0 ? colors.green : colors.red;
const freqChangeSymbol = m.freqChange >= 0 ? '↗' : '↘';
display += `⚡ Trades/min: ${m.tradeFreq.toFixed(1)} ${freqChangeColor}${freqChangeSymbol} ${m.freqChange.toFixed(2)}%${colors.reset}\n`;
// Jupiter API data if available
if (j) {
display += `\n${colors.magenta}Jupiter Data:${colors.reset}\n`;
// Market cap and liquidity
if (j.marketCap) {
display += `🏦 MCap: $${j.marketCap.toLocaleString()}\n`;
}
if (j.liquidity) {
const liquidityColor = j.liquidityScore >= 75 ? colors.green :
j.liquidityScore >= 50 ? colors.yellow :
colors.red;
display += `💧 Liq: ${liquidityColor}$${j.liquidity.toLocaleString()}${colors.reset} (Score: ${j.liquidityScore})\n`;
}
// 24h changes
if (j.priceChange24h !== undefined) {
const price24hColor = j.priceChange24h >= 0 ? colors.green : colors.red;
const price24hSymbol = j.priceChange24h >= 0 ? '↗' : '↘';
display += `📈 24h Price: ${price24hColor}${price24hSymbol} ${j.priceChange24h.toFixed(2)}%${colors.reset}\n`;
}
if (j.volumeChange24h !== undefined) {
const vol24hColor = j.volumeChange24h >= 0 ? colors.green : colors.red;
const vol24hSymbol = j.volumeChange24h >= 0 ? '↗' : '↘';
display += `📊 24h Volume: ${vol24hColor}${vol24hSymbol} ${j.volumeChange24h.toFixed(2)}%${colors.reset}\n`;
}
// Holders
if (j.holderCount) {
display += `👥 Holders: ${j.holderCount.toLocaleString()}\n`;
}
}
display += `${colors.white}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}\n`;
display += `${colors.cyan}Navigation: W (Next) | S (Previous) | R (Menu) | Q (Exit)${colors.reset}`;
// Cache the display
trendingDisplayCache.set(cacheKey, {
display,
timestamp: Date.now()
});
// Clear old cache entries
const now = Date.now();
for (const [key, value] of trendingDisplayCache.entries()) {
if (now - value.timestamp > TRENDING_CACHE_DURATION) {
trendingDisplayCache.delete(key);
}
}
console.clear();
console.log(display);
}
// Read the Birdeye API key from environment. If not provided, default to
// an empty string. This allows sensitive API keys to be stored in a
// `.env` file or environment variables instead of being hard‑coded.
const BIRDEYE_API_KEY = process.env.BIRDEYE_API_KEY || '';
// Add caching for token info
const tokenCache = {
data: new Map(),
maxAge: 6000, // 1 minute cache
set(key, value) {
this.data.set(key, {
value,
timestamp: Date.now()
});
},
get(key) {
const item = this.data.get(key);
if (!item) return null;
if (Date.now() - item.timestamp > this.maxAge) {
this.data.delete(key);
return null;
}
return item.value;
}
};
// Update fetchTokenInfo with better response validation and error handling
async function fetchTokenInfo(mintAddress) {
try {
// Check cache first
const cached = tokenCache.get(mintAddress);
if (cached) return cached;
// Add timeout to prevent hanging requests
const timeout = 5000; // 5 seconds
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
// Prepare both API requests with timeout
const v2Request = fetch(`https://public-api.birdeye.so/v2/tokens/solana/${mintAddress}`, {
method: 'GET',
headers: {
'X-API-KEY': BIRDEYE_API_KEY,
'Accept': 'application/json',
'Cache-Control': 'no-cache'
},
signal: controller.signal
});
const altRequest = fetch(`https://public-api.birdeye.so/v1/solana/token/meta/${mintAddress}`, {
method: 'GET',
headers: {
'X-API-KEY': BIRDEYE_API_KEY,
'Accept': 'application/json',
'Cache-Control': 'no-cache'
},
signal: controller.signal
});
// Run requests in parallel with timeout
const [v2Response, altResponse] = await Promise.all([
v2Request.catch(() => ({ ok: false })),
altRequest.catch(() => ({ ok: false }))
]);
clearTimeout(timeoutId);
// Process v2 response first
if (v2Response.ok && v2Response.headers?.get('content-type')?.includes('application/json')) {
try {
const v2Data = await v2Response.json();
if (v2Data?.success && v2Data?.data) {
const result = {
supply: v2Data.data?.supply || v2Data.data?.total_supply || '0',
buyTax: v2Data.data?.tax?.buy || 0,
sellTax: v2Data.data?.tax?.sell || 0,
liquidityLocked: Boolean(v2Data.data?.liquidity_locked),
marketCap: v2Data.data?.market_cap || 0
};
tokenCache.set(mintAddress, result);
return result;
}
} catch (e) {
console.error(`Error parsing v2 response: ${e.message}`);
}
}
// Try alt response if v2 failed
if (altResponse.ok && altResponse.headers?.get('content-type')?.includes('application/json')) {
try {
const altData = await altResponse.json();
if (altData?.success && altData?.data) {
const result = {
supply: altData.data?.supply || altData.data?.totalSupply || '0',
marketCap: altData.data?.marketCap || 0,
buyTax: 0,
sellTax: 0,
liquidityLocked: false
};
tokenCache.set(mintAddress, result);
return result;
}
} catch (e) {
console.error(`Error parsing alt response: ${e.message}`);
}
}
} catch (error) {
if (error.name === 'AbortError') {
console.error(`Request timeout for ${mintAddress}`);
} else {
console.error(`Network error for ${mintAddress}: ${error.message}`);
}
}
// Default response if both APIs fail
const defaultResult = {
supply: '0',
marketCap: 0,
buyTax: 0,
sellTax: 0,
liquidityLocked: false
};
tokenCache.set(mintAddress, defaultResult);
return defaultResult;
} catch (error) {
console.error(`Error fetching token info for ${mintAddress}: ${error.message}`);
return {
supply: '0',
marketCap: 0,
buyTax: 0,
sellTax: 0,
liquidityLocked: false
};
}
}
// Add token verification helper functions
async function verifyToken(token, trade) {
const warnings = [];
let score = 100; // Start with perfect score and deduct based on issues
// Check token metadata
if (!token.Name || !token.Symbol) {
warnings.push('⚠️ Missing token metadata');
score -= 20;
}
// Check decimals (most legitimate tokens use 6-9 decimals)
const decimals = parseInt(token.Decimals);
if (isNaN(decimals) || decimals < 6 || decimals > 12) {
warnings.push(`⚠️ Unusual decimal places: ${decimals}`);
score -= 15;
}
// Check token URI
if (!token.Uri) {
warnings.push('⚠️ No metadata URI');
score -= 10;
}
// Check if token is fungible
if (!token.Fungible) {
warnings.push('⚠️ Non-fungible token');
score -= 25;
}
// Check for honeypot indicators
const honeypotRisk = await checkHoneypotRisk(token.MintAddress);
if (honeypotRisk.isRisky) {
warnings.push(...honeypotRisk.warnings);
score -= 30;
}
return {
isVerified: score > 60,
score,
warnings,
riskLevel: getRiskLevel(100 - score)
};
}
// Enhanced token analysis using Jupiter API
async function analyzeTokenWithJupiter(tokenAddress) {
// Simple memoization layer: cache analysis results for 1 minute to avoid
// repeated calls for the same token. Cached results are invalidated
// after maxAge. This improves performance when users repeatedly check
// the same token via keyboard navigation.
const cacheKey = tokenAddress?.toLowerCase?.() || tokenAddress;
const maxAge = 60000; // 1 minute
if (!analyzeTokenWithJupiter.cache) {
analyzeTokenWithJupiter.cache = new Map();
}
const cached = analyzeTokenWithJupiter.cache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < maxAge) {
return cached.result;
}
try {
console.log(`${colors.cyan}🔍 Analyzing token with Jupiter API...${colors.reset}`);
// Get detailed analysis from Jupiter
const analysis = await getDetailedAnalysis(tokenAddress);
if (!analysis.success) {
console.log(`${colors.red}❌ Jupiter analysis failed: ${analysis.error}${colors.reset}`);
return null;
}
// Store in cache before returning
analyzeTokenWithJupiter.cache.set(cacheKey, { result: analysis, timestamp: Date.now() });
return analysis;
} catch (error) {
console.error(`${colors.red}Error in Jupiter analysis: ${error.message}${colors.reset}`);
return null;
}
}
// Real-time Jupiter token checking using v2 search API
async function checkJupiterTokenRealtime(tokenAddress) {
let retries = 0;
const maxRetries = 3;
while (retries <= maxRetries) {
try {
// Use rate limiting with backoff
if (rateLimiter.consecutiveFailures > 0) {
await rateLimiter.waitWithBackoff();
} else {
await rateLimiter.wait();
}
const response = await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${tokenAddress}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Cache-Control': 'no-cache',
'User-Agent': 'PrettySnipe/1.0.0'
},
signal: AbortSignal.timeout(10000)
});
if (response.status === 429) {
// Rate limited - increase backoff and retry
rateLimiter.recordFailure();
console.log(`${colors.yellow}⚠️ Rate limited by Jupiter API. Retrying in ${rateLimiter.minInterval/1000}s...${colors.reset}`);
retries++;
continue;
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
if (!data || !Array.isArray(data) || data.length === 0) {
throw new Error('Token not found or invalid response format');
}
// Find exact match for the token address
const exactMatch = data.find(token =>
token.id?.toLowerCase() === tokenAddress.toLowerCase()
);
if (!exactMatch) {
throw new Error('Token not found in search results');
}
// Extract real-time data from the token with enhanced calculations
const buyVolume = exactMatch.stats24h?.buyVolume || 0;
const sellVolume = exactMatch.stats24h?.sellVolume || 0;
const totalVolume = buyVolume + sellVolume;
// Calculate price change if we have historical data
let priceChange24h = 0;
if (exactMatch.priceChange24h !== undefined) {
priceChange24h = exactMatch.priceChange24h;
} else if (exactMatch.stats24h?.priceChange !== undefined) {
priceChange24h = exactMatch.stats24h.priceChange;
}
// Enhanced market cap calculation
let marketCap = exactMatch.mcap;
if (!marketCap && exactMatch.usdPrice && exactMatch.supply) {
marketCap = exactMatch.usdPrice * exactMatch.supply;
}
// Enhanced liquidity calculation
let liquidity = exactMatch.liquidity;
if (!liquidity && exactMatch.liquidityUSD) {
liquidity = exactMatch.liquidityUSD;
}
// Calculate volume trend
let volumeTrend = 'neutral';
if (buyVolume > sellVolume * 1.5) volumeTrend = 'bullish';
else if (sellVolume > buyVolume * 1.5) volumeTrend = 'bearish';
const realtimeData = {
price: exactMatch.usdPrice,
volume24h: totalVolume,
priceChange24h: priceChange24h,
marketCap: marketCap,
liquidity: liquidity,
name: exactMatch.name,
symbol: exactMatch.symbol,
decimals: exactMatch.decimals,
verified: exactMatch.isVerified,
hasLiquidity: liquidity > 0,
holderCount: exactMatch.holderCount,
organicScore: exactMatch.organicScore,
organicScoreLabel: exactMatch.organicScoreLabel,
volumeTrend: volumeTrend,
buyVolume: buyVolume,
sellVolume: sellVolume,
supply: exactMatch.supply,
fdv: exactMatch.fdv || (exactMatch.usdPrice * exactMatch.supply),
priceChange1h: exactMatch.stats1h?.priceChange || 0,
priceChange7d: exactMatch.stats7d?.priceChange || 0,
volumeChange24h: exactMatch.stats24h?.volumeChange || 0
};
rateLimiter.recordSuccess();
return {
success: true,
data: realtimeData,
timestamp: new Date().toISOString()
};
} catch (error) {
if (error.message.includes('HTTP 429') || error.message.includes('Too Many Requests')) {
rateLimiter.recordFailure();
console.log(`${colors.yellow}⚠️ Rate limited by Jupiter API. Retrying in ${rateLimiter.minInterval/1000}s...${colors.reset}`);
retries++;
continue;
}
return {
success: false,
error: error.message,
timestamp: new Date().toISOString()
};
}
}
// If we've exhausted all retries
return {
success: false,
error: 'Failed to fetch token data after multiple retries due to rate limiting',
timestamp: new Date().toISOString()
};
}
// Function to get Dexscreener boosted tokens
async function getDexscreenerBoostedTokens() {
try {
console.log(`${colors.cyan}🔄 Fetching Dexscreener boosted tokens...${colors.reset}`);
const response = await fetch('https://api.dexscreener.com/token-boosts/latest/v1', {
method: 'GET',
headers: {
"Accept": "*/*"
},
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
if (!data || !Array.isArray(data)) {
throw new Error('Invalid response format from Dexscreener API');
}
console.log(`${colors.green}✅ Found ${data.length} boosted tokens${colors.reset}`);
// Process and format the boosted tokens
const boostedTokens = data.map((token, index) => ({
index: index + 1,
name: token.name || 'Unknown Token',
symbol: token.symbol || 'UNKNOWN',
address: token.address,
chain: token.chain || 'Unknown',
price: token.price || 0,
priceChange24h: token.priceChange24h || 0,
volume24h: token.volume24h || 0,
marketCap: token.marketCap || 0,
liquidity: token.liquidity || 0,
boostType: token.boostType || 'Unknown',
boostReason: token.boostReason || 'No reason provided',
timestamp: token.timestamp || new Date().toISOString()
}));
return {
success: true,
data: boostedTokens,
count: boostedTokens.length
};
} catch (error) {
console.log(`${colors.red}❌ Failed to fetch Dexscreener boosted tokens: ${error.message}${colors.reset}`);
return {
success: false,
error: error.message,
data: []
};
}
}
// Function to display Dexscreener boosted tokens
function displayDexscreenerBoostedTokens(tokens) {
console.clear();
console.log(`${colors.cyan}🚀 Dexscreener Boosted Tokens${colors.reset}`);
console.log(`${colors.white}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}`);
console.log(`${colors.yellow}Found ${tokens.length} boosted tokens${colors.reset}\n`);
tokens.forEach((token, index) => {
const priceFormatted = token.price < 0.0001 ? token.price.toFixed(8) :
token.price < 0.01 ? token.price.toFixed(6) :
token.price < 1 ? token.price.toFixed(4) :
token.price.toFixed(2);
const volumeFormatted = token.volume24h >= 1000000 ?
`$${(token.volume24h / 1000000).toFixed(2)}M` :
token.volume24h >= 1000 ?
`$${(token.volume24h / 1000).toFixed(2)}K` :
`$${token.volume24h.toFixed(2)}`;
const mcapFormatted = token.marketCap >= 1000000 ?
`$${(token.marketCap / 1000000).toFixed(2)}M` :
token.marketCap >= 1000 ?
`$${(token.marketCap / 1000).toFixed(2)}K` :
`$${token.marketCap.toFixed(2)}`;
const changeColor = token.priceChange24h >= 0 ? colors.green : colors.red;
const changeSymbol = token.priceChange24h >= 0 ? '📈' : '📉';
console.log(`${colors.cyan}${token.index}.${colors.reset} ${colors.white}${token.symbol}${colors.reset} (${token.name})`);
console.log(` 🌐 Chain: ${colors.yellow}${token.chain}${colors.reset}`);
console.log(` 💰 Price: $${priceFormatted}`);
console.log(` ${changeSymbol} 24h Change: ${changeColor}${token.priceChange24h.toFixed(2)}%${colors.reset}`);
console.log(` 📊 Volume: ${volumeFormatted}`);
console.log(` 🏦 Market Cap: ${mcapFormatted}`);
console.log(` 💧 Liquidity: $${token.liquidity.toLocaleString()}`);
console.log(` 🚀 Boost Type: ${colors.magenta}${token.boostType}${colors.reset}`);
console.log(` 📝 Reason: ${colors.cyan}${token.boostReason}${colors.reset}`);
console.log(` 🔗 Address: ${colors.dim}${token.address}${colors.reset}`);
console.log('');
});
console.log(`${colors.cyan}⌨️ Hotkeys: Q=Quit | R=Refresh | [1-${tokens.length}]=Monitor Token${colors.reset}`);
}
// Enhanced function to get comprehensive token data from multiple sources
async function getEnhancedTokenData(tokenAddress) {
try {
// Try Jupiter Lite API first
const jupiterData = await checkJupiterTokenRealtime(tokenAddress);
if (jupiterData.success) {
// Try to get additional data from Birdeye API
try {
const birdeyeResponse = await fetch(`https://public-api.birdeye.so/public/price?address=${tokenAddress}`, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});
if (birdeyeResponse.ok) {
const birdeyeData = await birdeyeResponse.json();
if (birdeyeData.data && birdeyeData.data.value > 0) {
// Merge Birdeye data with Jupiter data
jupiterData.data.price = birdeyeData.data.value; // Use Birdeye price as it's often more accurate
jupiterData.data.priceChange24h = birdeyeData.data.change24h || jupiterData.data.priceChange24h;
jupiterData.data.volume24h = birdeyeData.data.volume24h || jupiterData.data.volume24h;
jupiterData.data.marketCap = birdeyeData.data.mc || jupiterData.data.marketCap;
}
}
} catch (birdeyeError) {
// Continue with Jupiter data if Birdeye fails
}
return jupiterData;
}
// Fallback to basic price check
const basicPrice = await getTokenPrice(tokenAddress, true);
if (basicPrice > 0.00000001) {
return {
success: true,
data: {
price: basicPrice,
volume24h: 0,
priceChange24h: 0,
marketCap: 0,
liquidity: 0,
name: 'Unknown',
symbol: tokenAddress.slice(0, 4).toUpperCase(),
decimals: 9,
verified: false,
hasLiquidity: false,
holderCount: 0,
organicScore: 0,
organicScoreLabel: 'Unknown',
volumeTrend: 'neutral',
buyVolume: 0,
sellVolume: 0,