-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
531 lines (452 loc) · 19.2 KB
/
index.js
File metadata and controls
531 lines (452 loc) · 19.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
/**
* 🐝 Buzz Token Scanner — Free OpenClaw Skill
*
* Multi-chain token discovery and 100-point scoring system.
* Scans DexScreener API for new/trending tokens, evaluates them
* against BD-ready criteria, and returns ranked prospects.
*
* Built by BuzzBD @ SolCex Exchange
* https://github.com/buzzbysolcex/buzz-token-scanner
*
* FREE to use. No API key required. No x402 payment needed.
* DexScreener API is public and free (60-300 req/min).
*
* Usage:
* const scanner = require('./index');
* const results = await scanner.scanLatest({ chain: 'solana', limit: 10 });
* const scored = await scanner.scoreToken('solana', 'TOKEN_ADDRESS');
*/
const DEXSCREENER_BASE = 'https://api.dexscreener.com';
// ═══════════════════════════════════════════════════════
// SCORING CONFIGURATION
// ═══════════════════════════════════════════════════════
const SCORING_WEIGHTS = {
marketCap: { weight: 20, thresholds: { excellent: 10_000_000, good: 1_000_000, acceptable: 500_000 } },
liquidity: { weight: 25, thresholds: { excellent: 500_000, good: 200_000, acceptable: 100_000 } },
volume24h: { weight: 20, thresholds: { excellent: 1_000_000, good: 500_000, acceptable: 100_000 } },
social: { weight: 15, thresholds: { excellent: 3, good: 2, acceptable: 1 } }, // platform count
tokenAge: { weight: 10, thresholds: { excellent: 90, good: 30, acceptable: 7 } }, // days
team: { weight: 10, thresholds: { excellent: 3, good: 2, acceptable: 1 } }, // transparency signals
};
const CATALYST_BONUSES = {
hackathonWin: +10,
mainnetLaunch: +10,
majorPartnership: +10,
cexListing: +8,
auditCompleted: +8,
multiSourceMatch: +5, // appears on multiple discovery sources
whaleActivity: +5,
kolBullish: +3,
};
const CATALYST_PENALTIES = {
delistingRisk: -15,
exploitHistory: -15,
rugpullAssociation: -15,
teamControversy: -10,
contractVuln: -10,
kolRiskFlag: -10,
alreadyOnMajorCex: -5,
};
const SCORE_CATEGORIES = {
HOT: { min: 85, max: 100, emoji: '🔥', action: 'Immediate outreach' },
QUALIFIED: { min: 70, max: 84, emoji: '✅', action: 'Priority queue' },
WATCH: { min: 50, max: 69, emoji: '👀', action: 'Monitor 48h' },
SKIP: { min: 0, max: 49, emoji: '❌', action: 'No action' },
};
const CHAIN_CONFIG = {
solana: { tag: '[SOL]', priority: 1, listingFee: 5000 },
ethereum: { tag: '[ETH]', priority: 2, listingFee: 7500 },
bsc: { tag: '[BSC]', priority: 3, listingFee: 7500 },
base: { tag: '[BASE]', priority: 4, listingFee: 7500 },
arbitrum: { tag: '[ARB]', priority: 5, listingFee: 7500 },
};
// ═══════════════════════════════════════════════════════
// HELPER FUNCTIONS
// ═══════════════════════════════════════════════════════
async function fetchJSON(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`DexScreener API error: ${response.status} ${response.statusText}`);
}
return response.json();
}
function calculateFactorScore(value, { weight, thresholds }) {
if (value == null || value <= 0) return 0;
if (value >= thresholds.excellent) return weight;
if (value >= thresholds.good) return Math.round(weight * 0.75);
if (value >= thresholds.acceptable) return Math.round(weight * 0.5);
return Math.round(weight * 0.25);
}
function countSocialPlatforms(links) {
if (!links || !Array.isArray(links)) return 0;
const platforms = new Set();
for (const link of links) {
const type = (link.type || link.label || '').toLowerCase();
if (type.includes('twitter') || type.includes('x.com')) platforms.add('twitter');
if (type.includes('telegram')) platforms.add('telegram');
if (type.includes('discord')) platforms.add('discord');
if (type.includes('website') || type.includes('http')) platforms.add('website');
if (type.includes('github')) platforms.add('github');
}
return platforms.size;
}
function getTokenAgeDays(pairCreatedAt) {
if (!pairCreatedAt) return 0;
const created = new Date(pairCreatedAt);
const now = new Date();
return Math.floor((now - created) / (1000 * 60 * 60 * 24));
}
function getTeamTransparencyScore(profile, pair) {
let score = 0;
if (profile?.links?.some(l => l.type === 'twitter')) score++;
if (profile?.links?.some(l => l.label === 'Website' || l.type === 'website')) score++;
if (profile?.description && profile.description.length > 50) score++;
if (profile?.links?.some(l => l.type === 'github')) score++;
return Math.min(score, 3);
}
function categorizeScore(score) {
for (const [category, config] of Object.entries(SCORE_CATEGORIES)) {
if (score >= config.min && score <= config.max) {
return { category, ...config };
}
}
return { category: 'SKIP', ...SCORE_CATEGORIES.SKIP };
}
// ═══════════════════════════════════════════════════════
// CORE SCORING ENGINE
// ═══════════════════════════════════════════════════════
/**
* Score a token based on the 100-point system
*
* @param {Object} pair - DexScreener pair data
* @param {Object} profile - DexScreener token profile (optional)
* @param {Array} catalysts - Array of catalyst strings (optional)
* @returns {Object} Scored token with breakdown
*/
function scoreToken(pair, profile = null, catalysts = []) {
const breakdown = {};
let totalScore = 0;
// Market Cap (20 pts)
const mcap = pair.marketCap || pair.fdv || 0;
breakdown.marketCap = calculateFactorScore(mcap, SCORING_WEIGHTS.marketCap);
totalScore += breakdown.marketCap;
// Liquidity (25 pts)
const liq = pair.liquidity?.usd || 0;
breakdown.liquidity = calculateFactorScore(liq, SCORING_WEIGHTS.liquidity);
totalScore += breakdown.liquidity;
// Volume 24h (20 pts)
const vol = pair.volume?.h24 || 0;
breakdown.volume24h = calculateFactorScore(vol, SCORING_WEIGHTS.volume24h);
totalScore += breakdown.volume24h;
// Social Metrics (15 pts)
const socialCount = countSocialPlatforms(profile?.links || pair.info?.socials || []);
breakdown.social = calculateFactorScore(socialCount, SCORING_WEIGHTS.social);
totalScore += breakdown.social;
// Token Age (10 pts)
const ageDays = getTokenAgeDays(pair.pairCreatedAt);
breakdown.tokenAge = calculateFactorScore(ageDays, SCORING_WEIGHTS.tokenAge);
totalScore += breakdown.tokenAge;
// Team Transparency (10 pts)
const teamScore = getTeamTransparencyScore(profile, pair);
breakdown.team = calculateFactorScore(teamScore, SCORING_WEIGHTS.team);
totalScore += breakdown.team;
// Catalyst Adjustments
let catalystAdjustment = 0;
const appliedCatalysts = [];
for (const catalyst of catalysts) {
if (CATALYST_BONUSES[catalyst]) {
catalystAdjustment += CATALYST_BONUSES[catalyst];
appliedCatalysts.push({ type: catalyst, points: CATALYST_BONUSES[catalyst] });
}
if (CATALYST_PENALTIES[catalyst]) {
catalystAdjustment += CATALYST_PENALTIES[catalyst];
appliedCatalysts.push({ type: catalyst, points: CATALYST_PENALTIES[catalyst] });
}
}
totalScore = Math.max(0, Math.min(100, totalScore + catalystAdjustment));
const { category, emoji, action } = categorizeScore(totalScore);
const chainConfig = CHAIN_CONFIG[pair.chainId] || { tag: `[${pair.chainId?.toUpperCase()}]`, priority: 9, listingFee: 7500 };
return {
// Token Identity
name: pair.baseToken?.name || 'Unknown',
symbol: pair.baseToken?.symbol || '???',
address: pair.baseToken?.address || '',
chain: pair.chainId,
chainTag: chainConfig.tag,
dexScreenerUrl: pair.url || `https://dexscreener.com/${pair.chainId}/${pair.baseToken?.address}`,
// Score
score: totalScore,
category,
emoji,
action,
listingFee: chainConfig.listingFee,
// Metrics
metrics: {
marketCap: mcap,
liquidity: liq,
volume24h: vol,
priceUsd: pair.priceUsd,
priceChange24h: pair.priceChange?.h24,
socialPlatforms: socialCount,
ageDays,
teamTransparency: teamScore,
},
// Breakdown
scoreBreakdown: breakdown,
catalysts: appliedCatalysts,
catalystAdjustment,
// Timestamp
scoredAt: new Date().toISOString(),
};
}
// ═══════════════════════════════════════════════════════
// API FUNCTIONS
// ═══════════════════════════════════════════════════════
/**
* Scan latest token profiles from DexScreener
*
* @param {Object} options
* @param {string} options.chain - Filter by chain ('solana', 'ethereum', 'bsc', 'base')
* @param {number} options.limit - Max results to return (default: 20)
* @param {number} options.minLiquidity - Minimum liquidity USD (default: 50000)
* @param {number} options.minScore - Minimum score threshold (default: 0)
* @returns {Array} Scored and ranked tokens
*/
async function scanLatest({ chain = null, limit = 20, minLiquidity = 50000, minScore = 0 } = {}) {
// Fetch latest token profiles
const profiles = await fetchJSON(`${DEXSCREENER_BASE}/token-profiles/latest/v1`);
// Filter by chain if specified
let filtered = chain
? profiles.filter(p => p.chainId === chain)
: profiles.filter(p => Object.keys(CHAIN_CONFIG).includes(p.chainId));
// Deduplicate by token address
const seen = new Set();
filtered = filtered.filter(p => {
const key = `${p.chainId}:${p.tokenAddress}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
// Batch fetch pair data (up to 30 per request)
const results = [];
const batches = {};
for (const profile of filtered.slice(0, 60)) {
if (!batches[profile.chainId]) batches[profile.chainId] = [];
batches[profile.chainId].push(profile);
}
for (const [chainId, chainProfiles] of Object.entries(batches)) {
const addresses = chainProfiles.map(p => p.tokenAddress).slice(0, 30);
try {
const tokenData = await fetchJSON(
`${DEXSCREENER_BASE}/tokens/v1/${chainId}/${addresses.join(',')}`
);
if (Array.isArray(tokenData)) {
for (const pair of tokenData) {
if (!pair.baseToken?.address) continue;
if ((pair.liquidity?.usd || 0) < minLiquidity) continue;
const profile = chainProfiles.find(
p => p.tokenAddress.toLowerCase() === pair.baseToken.address.toLowerCase()
);
const scored = scoreToken(pair, profile);
if (scored.score >= minScore) {
results.push(scored);
}
}
}
} catch (err) {
console.error(`Error fetching ${chainId} tokens:`, err.message);
}
}
// Sort by score descending, then by liquidity
results.sort((a, b) => b.score - a.score || b.metrics.liquidity - a.metrics.liquidity);
return results.slice(0, limit);
}
/**
* Scan trending/boosted tokens from DexScreener
*
* @param {Object} options
* @param {string} options.chain - Filter by chain
* @param {number} options.limit - Max results (default: 10)
* @param {number} options.minLiquidity - Min liquidity (default: 100000)
* @returns {Array} Scored trending tokens
*/
async function scanTrending({ chain = null, limit = 10, minLiquidity = 100000 } = {}) {
const boosted = await fetchJSON(`${DEXSCREENER_BASE}/token-boosts/top/v1`);
let filtered = chain
? boosted.filter(p => p.chainId === chain)
: boosted.filter(p => Object.keys(CHAIN_CONFIG).includes(p.chainId));
const seen = new Set();
filtered = filtered.filter(p => {
const key = `${p.chainId}:${p.tokenAddress}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
const results = [];
const batches = {};
for (const profile of filtered.slice(0, 30)) {
if (!batches[profile.chainId]) batches[profile.chainId] = [];
batches[profile.chainId].push(profile);
}
for (const [chainId, chainProfiles] of Object.entries(batches)) {
const addresses = chainProfiles.map(p => p.tokenAddress).slice(0, 30);
try {
const tokenData = await fetchJSON(
`${DEXSCREENER_BASE}/tokens/v1/${chainId}/${addresses.join(',')}`
);
if (Array.isArray(tokenData)) {
for (const pair of tokenData) {
if (!pair.baseToken?.address) continue;
if ((pair.liquidity?.usd || 0) < minLiquidity) continue;
const profile = chainProfiles.find(
p => p.tokenAddress.toLowerCase() === pair.baseToken.address.toLowerCase()
);
const scored = scoreToken(pair, profile, ['multiSourceMatch']);
results.push(scored);
}
}
} catch (err) {
console.error(`Error fetching ${chainId} trending:`, err.message);
}
}
results.sort((a, b) => b.score - a.score);
return results.slice(0, limit);
}
/**
* Score a specific token by address
*
* @param {string} chain - Chain ID ('solana', 'ethereum', 'bsc')
* @param {string} tokenAddress - Token contract address
* @param {Array} catalysts - Optional catalyst flags
* @returns {Object} Detailed score result
*/
async function scoreByAddress(chain, tokenAddress, catalysts = []) {
const tokenData = await fetchJSON(
`${DEXSCREENER_BASE}/tokens/v1/${chain}/${tokenAddress}`
);
if (!Array.isArray(tokenData) || tokenData.length === 0) {
throw new Error(`Token not found: ${chain}/${tokenAddress}`);
}
// Pick the pair with highest liquidity
const bestPair = tokenData.reduce((best, pair) =>
(pair.liquidity?.usd || 0) > (best.liquidity?.usd || 0) ? pair : best
);
// Try to get profile data
let profile = null;
try {
const profiles = await fetchJSON(`${DEXSCREENER_BASE}/token-profiles/latest/v1`);
profile = profiles.find(
p => p.chainId === chain && p.tokenAddress.toLowerCase() === tokenAddress.toLowerCase()
);
} catch (e) {
// Profile data is optional
}
return scoreToken(bestPair, profile, catalysts);
}
/**
* Search for tokens by name/symbol and score them
*
* @param {string} query - Search query (name or symbol)
* @param {Object} options
* @param {number} options.limit - Max results (default: 5)
* @param {number} options.minLiquidity - Min liquidity (default: 50000)
* @returns {Array} Scored search results
*/
async function searchAndScore(query, { limit = 5, minLiquidity = 50000 } = {}) {
const data = await fetchJSON(
`${DEXSCREENER_BASE}/latest/dex/search?q=${encodeURIComponent(query)}`
);
if (!data.pairs || data.pairs.length === 0) {
return [];
}
const results = [];
const seen = new Set();
for (const pair of data.pairs) {
if (!pair.baseToken?.address) continue;
if ((pair.liquidity?.usd || 0) < minLiquidity) continue;
if (!Object.keys(CHAIN_CONFIG).includes(pair.chainId)) continue;
const key = `${pair.chainId}:${pair.baseToken.address}`;
if (seen.has(key)) continue;
seen.add(key);
results.push(scoreToken(pair));
}
results.sort((a, b) => b.score - a.score);
return results.slice(0, limit);
}
/**
* Generate a formatted report from scan results
*
* @param {Array} tokens - Array of scored tokens
* @param {string} title - Report title
* @returns {string} Formatted markdown report
*/
function formatReport(tokens, title = 'Token Scan Report') {
const now = new Date().toISOString();
let report = `# 🐝 ${title}\n`;
report += `> Generated: ${now}\n`;
report += `> Powered by Buzz Token Scanner (FREE OpenClaw Skill)\n\n`;
if (tokens.length === 0) {
report += 'No tokens found matching criteria.\n';
return report;
}
// Summary
const hot = tokens.filter(t => t.category === 'HOT').length;
const qualified = tokens.filter(t => t.category === 'QUALIFIED').length;
const watch = tokens.filter(t => t.category === 'WATCH').length;
report += `## Summary\n`;
report += `| Category | Count |\n|----------|-------|\n`;
report += `| 🔥 HOT (85-100) | ${hot} |\n`;
report += `| ✅ QUALIFIED (70-84) | ${qualified} |\n`;
report += `| 👀 WATCH (50-69) | ${watch} |\n`;
report += `| Total Scanned | ${tokens.length} |\n\n`;
// Top prospects table
report += `## Top Prospects\n\n`;
report += `| # | Token | Chain | Score | MCap | Liq | Vol 24h | Action |\n`;
report += `|---|-------|-------|-------|------|-----|---------|--------|\n`;
tokens.forEach((t, i) => {
const mcap = t.metrics.marketCap >= 1e6 ? `$${(t.metrics.marketCap / 1e6).toFixed(1)}M` : `$${(t.metrics.marketCap / 1e3).toFixed(0)}K`;
const liq = t.metrics.liquidity >= 1e6 ? `$${(t.metrics.liquidity / 1e6).toFixed(1)}M` : `$${(t.metrics.liquidity / 1e3).toFixed(0)}K`;
const vol = t.metrics.volume24h >= 1e6 ? `$${(t.metrics.volume24h / 1e6).toFixed(1)}M` : `$${(t.metrics.volume24h / 1e3).toFixed(0)}K`;
report += `| ${i + 1} | ${t.emoji} ${t.symbol} ${t.chainTag} | ${t.chain} | **${t.score}** | ${mcap} | ${liq} | ${vol} | ${t.action} |\n`;
});
report += `\n`;
// Detailed breakdown for HOT tokens
const hotTokens = tokens.filter(t => t.category === 'HOT');
if (hotTokens.length > 0) {
report += `## 🔥 HOT Token Details\n\n`;
for (const t of hotTokens) {
report += `### ${t.symbol} ${t.chainTag} — Score: ${t.score}/100\n`;
report += `- **Address:** \`${t.address}\`\n`;
report += `- **DexScreener:** ${t.dexScreenerUrl}\n`;
report += `- **Market Cap:** $${t.metrics.marketCap.toLocaleString()}\n`;
report += `- **Liquidity:** $${t.metrics.liquidity.toLocaleString()}\n`;
report += `- **24h Volume:** $${t.metrics.volume24h.toLocaleString()}\n`;
report += `- **Price:** $${t.metrics.priceUsd}\n`;
report += `- **24h Change:** ${t.metrics.priceChange24h}%\n`;
report += `- **Age:** ${t.metrics.ageDays} days\n`;
report += `- **Listing Fee:** $${t.listingFee.toLocaleString()}\n`;
report += `- **Score Breakdown:** MCap ${t.scoreBreakdown.marketCap}/20 | Liq ${t.scoreBreakdown.liquidity}/25 | Vol ${t.scoreBreakdown.volume24h}/20 | Social ${t.scoreBreakdown.social}/15 | Age ${t.scoreBreakdown.tokenAge}/10 | Team ${t.scoreBreakdown.team}/10\n\n`;
}
}
report += `---\n`;
report += `*Built by BuzzBD @ SolCex Exchange | Free OpenClaw Skill | github.com/buzzbysolcex/buzz-token-scanner*\n`;
return report;
}
// ═══════════════════════════════════════════════════════
// EXPORTS
// ═══════════════════════════════════════════════════════
module.exports = {
// Core functions
scanLatest,
scanTrending,
scoreByAddress,
searchAndScore,
scoreToken,
formatReport,
// Configuration (for customization)
SCORING_WEIGHTS,
CATALYST_BONUSES,
CATALYST_PENALTIES,
SCORE_CATEGORIES,
CHAIN_CONFIG,
};