crypull 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.ts DELETED
@@ -1,440 +0,0 @@
1
- #!/usr/bin/env node
2
- import { Command } from 'commander';
3
- import pc from 'picocolors';
4
- import * as asciichart from 'asciichart';
5
- import { crypull } from './index.js';
6
- import { intro, outro, select, text, isCancel } from '@clack/prompts';
7
-
8
- const program = new Command();
9
-
10
- program
11
- .name('crypull')
12
- .description('A human-friendly CLI to fetch crypto prices and info from multiple providers')
13
- .version('1.0.1');
14
-
15
- const handlePrice = async (query: string) => {
16
- console.log(pc.cyan(`\nFetching price for ${pc.bold(query)}...`));
17
-
18
- const data = await crypull.price(query);
19
-
20
- if (!data) {
21
- console.log(pc.red(`\n✖ Could not find price for "${query}".`));
22
- return;
23
- }
24
-
25
- console.log(pc.green(`\n✔ Success! Found via ${pc.bold(data.source)}`));
26
- console.log(pc.white(`----------------------------------------`));
27
- console.log(`${pc.gray('Symbol:')} ${pc.yellow(pc.bold(data.symbol))}`);
28
- console.log(`${pc.gray('Price:')} ${pc.green('$' + data.priceUsd.toLocaleString(undefined, { maximumFractionDigits: 6 }))}`);
29
- console.log(`${pc.gray('Updated:')} ${new Date(data.lastUpdated).toLocaleTimeString()}`);
30
- console.log(pc.white(`----------------------------------------\n`));
31
- };
32
-
33
- const handleInfo = async (query: string) => {
34
- console.log(pc.cyan(`\nFetching detailed info for ${pc.bold(query)}...`));
35
-
36
- const data = await crypull.info(query);
37
-
38
- if (!data) {
39
- console.log(pc.red(`\n✖ Could not find info for "${query}".`));
40
- return;
41
- }
42
-
43
- console.log(pc.green(`\n✔ Success! Found via ${pc.bold(data.source)}`));
44
- console.log(pc.white(`----------------------------------------`));
45
- console.log(`${pc.gray('Name:')} ${pc.white(pc.bold(data.name))}`);
46
- console.log(`${pc.gray('Symbol:')} ${pc.yellow(pc.bold(data.symbol))}`);
47
- console.log(`${pc.gray('Price:')} ${pc.green('$' + data.priceUsd.toLocaleString(undefined, { maximumFractionDigits: 6 }))}`);
48
-
49
- if (data.marketCap) {
50
- console.log(`${pc.gray('MarketCap:')} ${pc.white('$' + data.marketCap.toLocaleString())}`);
51
- }
52
- if (data.marketCapRank) {
53
- console.log(`${pc.gray('Rank:')} ${pc.magenta('#' + data.marketCapRank)}`);
54
- }
55
- if (data.fdv) {
56
- console.log(`${pc.gray('FDV:')} ${pc.white('$' + data.fdv.toLocaleString())}`);
57
- }
58
- if (data.circulatingSupply) {
59
- console.log(`${pc.gray('Circ. Sup:')} ${pc.white(data.circulatingSupply.toLocaleString())}`);
60
- }
61
- if (data.totalSupply) {
62
- console.log(`${pc.gray('Total Sup:')} ${pc.white(data.totalSupply.toLocaleString())}`);
63
- }
64
- if (data.maxSupply) {
65
- console.log(`${pc.gray('Max Sup:')} ${pc.white(data.maxSupply.toLocaleString())}`);
66
- }
67
- if (data.volume24h) {
68
- console.log(`${pc.gray('24h Vol:')} ${pc.white('$' + data.volume24h.toLocaleString())}`);
69
- }
70
- if (data.priceChangePercentage24h !== undefined) {
71
- const pc24 = data.priceChangePercentage24h;
72
- const color = pc24 >= 0 ? pc.green : pc.red;
73
- console.log(`${pc.gray('24h %:')} ${color(pc24.toFixed(2) + '%')}`);
74
- }
75
- if (data.liquidityUsd) {
76
- console.log(`${pc.gray('Liquidity:')} ${pc.white('$' + data.liquidityUsd.toLocaleString())}`);
77
- }
78
- if (data.ath) {
79
- console.log(`${pc.gray('ATH:')} ${pc.green('$' + data.ath.toLocaleString())} ${data.athDate ? pc.gray(`(${new Date(data.athDate).toLocaleDateString()})`) : ''}`);
80
- }
81
- if (data.atl) {
82
- console.log(`${pc.gray('ATL:')} ${pc.red('$' + data.atl.toLocaleString())} ${data.atlDate ? pc.gray(`(${new Date(data.atlDate).toLocaleDateString()})`) : ''}`);
83
- }
84
- if (data.network) {
85
- console.log(`${pc.gray('Network:')} ${pc.magenta(data.network)}`);
86
- }
87
- if (data.address) {
88
- console.log(`${pc.gray('Address:')} ${pc.gray(data.address)}`);
89
- }
90
-
91
- if (data.links && Object.values(data.links).some(l => !!l)) {
92
- console.log(pc.white(`\n--- Links ---`));
93
- if (data.links.website) console.log(`${pc.gray('Website:')} ${pc.blue(data.links.website)}`);
94
- if (data.links.twitter) console.log(`${pc.gray('Twitter:')} ${pc.blue(data.links.twitter)}`);
95
- if (data.links.telegram) console.log(`${pc.gray('Telegram:')} ${pc.blue(data.links.telegram)}`);
96
- if (data.links.discord) console.log(`${pc.gray('Discord:')} ${pc.blue(data.links.discord)}`);
97
- if (data.links.github) console.log(`${pc.gray('GitHub:')} ${pc.blue(data.links.github)}`);
98
- }
99
-
100
- if (data.description && data.description.length > 0) {
101
- console.log(pc.white(`\n--- Description ---`));
102
- // Truncate to 300 chars to not flood terminal
103
- const desc = data.description.replace(/(<([^>]+)>)/gi, ""); // strip html
104
- const truncated = desc.length > 300 ? desc.substring(0, 300) + '...' : desc;
105
- console.log(pc.gray(truncated));
106
- }
107
-
108
- if (data.pairs && data.pairs.length > 0) {
109
- console.log(pc.white(`\n--- Top Trading Pairs ---`));
110
- data.pairs.slice(0, 5).forEach((p, i) => {
111
- const title = `${p.baseTokenSymbol}/${p.quoteTokenSymbol}`;
112
- const priceStr = p.priceUsd ? `$${p.priceUsd.toLocaleString(undefined, { maximumFractionDigits: 6 })}` : 'N/A';
113
- const volStr = p.volume24h ? `$${p.volume24h.toLocaleString(undefined, { maximumFractionDigits: 0 })}` : 'N/A';
114
- console.log(`${pc.blue(String(i + 1) + '.')} ${pc.yellow(title.padEnd(12, ' '))} | ${pc.green(priceStr.padEnd(12, ' '))} | Vol: ${pc.white(volStr)} | DEX: ${pc.magenta(p.dexId)}`);
115
- });
116
- }
117
-
118
- console.log(pc.white(`\n----------------------------------------`));
119
- console.log(`${pc.gray('Updated:')} ${new Date(data.lastUpdated).toLocaleTimeString()}`);
120
- console.log(pc.white(`----------------------------------------\n`));
121
- };
122
-
123
- const handleTop = async () => {
124
- console.log(pc.cyan(`\nFetching top 50 cryptocurrencies...`));
125
-
126
- const results = await crypull.top();
127
-
128
- if (!results || results.length === 0) {
129
- console.log(pc.red(`\n✖ Could not fetch top coins at this time.`));
130
- return;
131
- }
132
-
133
- console.log(pc.green(`\n✔ Top 50 Cryptocurrencies:`));
134
- console.log(pc.white(`----------------------------------------`));
135
-
136
- results.forEach((res, i) => {
137
- const priceStr = res.priceUsd ? `$${res.priceUsd.toLocaleString(undefined, { maximumFractionDigits: 6 })}` : 'N/A';
138
- const mcapStr = res.marketCap ? `$${res.marketCap.toLocaleString()}` : 'N/A';
139
-
140
- let changeStr = '';
141
- if (res.priceChange24h !== undefined && res.priceChange24h !== null) {
142
- const color = res.priceChange24h >= 0 ? pc.green : pc.red;
143
- changeStr = color(`(${res.priceChange24h >= 0 ? '+' : ''}${res.priceChange24h.toFixed(2)}%)`);
144
- }
145
-
146
- console.log(`${pc.blue(String(i + 1).padStart(2, ' '))}. ${pc.yellow(pc.bold(res.symbol.padEnd(8, ' ')))} | ${pc.green(priceStr.padEnd(12, ' '))} ${changeStr.padEnd(15, ' ')} | Mcap: ${pc.white(mcapStr)}`);
147
- });
148
-
149
- console.log(pc.white(`----------------------------------------\n`));
150
- };
151
-
152
- const handleSearch = async (query: string) => {
153
- console.log(pc.cyan(`\nSearching for ${pc.bold(query)}...`));
154
-
155
- const results = await crypull.search(query);
156
-
157
- if (!results || results.length === 0) {
158
- console.log(pc.red(`\n✖ No results found for "${query}".`));
159
- return;
160
- }
161
-
162
- console.log(pc.green(`\n✔ Found ${results.length} results:`));
163
- console.log(pc.white(`----------------------------------------`));
164
-
165
- results.forEach((res, i) => {
166
- console.log(`${pc.blue(String(i + 1).padStart(2, ' '))}. ${pc.yellow(pc.bold(res.symbol.padEnd(8, ' ')))} | ${pc.white(res.name)} ${pc.gray(`(via ${res.source})`)}`);
167
- if (res.network) {
168
- console.log(` ${pc.gray('Network:')} ${pc.magenta(res.network)}`);
169
- }
170
- if (res.id && res.id.length > 20) {
171
- console.log(` ${pc.gray('Address:')} ${pc.gray(res.id)}`);
172
- }
173
- });
174
-
175
- console.log(pc.white(`----------------------------------------\n`));
176
- };
177
-
178
- const handleTrending = async () => {
179
- console.log(pc.cyan(`\nFetching top trending coins...`));
180
-
181
- const results = await crypull.trending();
182
-
183
- if (!results || results.length === 0) {
184
- console.log(pc.red(`\n✖ Could not fetch trending data at this time.`));
185
- return;
186
- }
187
-
188
- console.log(pc.green(`\n✔ Top 10 Trending Coins:`));
189
- console.log(pc.white(`----------------------------------------`));
190
-
191
- results.forEach((res, i) => {
192
- const priceStr = res.priceUsd ? `$${res.priceUsd.toLocaleString(undefined, { maximumFractionDigits: 6 })}` : 'N/A';
193
- let changeStr = '';
194
- if (res.priceChange24h !== undefined) {
195
- const color = res.priceChange24h >= 0 ? pc.green : pc.red;
196
- changeStr = color(`(${res.priceChange24h >= 0 ? '+' : ''}${res.priceChange24h.toFixed(2)}%)`);
197
- }
198
- const rankStr = res.marketCapRank ? pc.magenta(`#${res.marketCapRank}`) : '';
199
-
200
- console.log(`${pc.blue(String(i + 1).padStart(2, ' '))}. ${pc.yellow(pc.bold(res.symbol.padEnd(8, ' ')))} | ${pc.green(priceStr.padEnd(12, ' '))} ${changeStr.padEnd(15, ' ')} | ${rankStr}`);
201
- });
202
-
203
- console.log(pc.white(`----------------------------------------\n`));
204
- };
205
-
206
- const handleMarket = async () => {
207
- console.log(pc.cyan(`\nFetching global market data...`));
208
-
209
- const data = await crypull.market();
210
-
211
- if (!data) {
212
- console.log(pc.red(`\n✖ Could not fetch global market data at this time.`));
213
- return;
214
- }
215
-
216
- console.log(pc.green(`\n✔ Global Market Overview:`));
217
- console.log(pc.white(`----------------------------------------`));
218
- console.log(`${pc.gray('Total Market Cap:')} ${pc.white('$' + data.totalMarketCapUsd.toLocaleString())}`);
219
- console.log(`${pc.gray('24h Volume:')} ${pc.white('$' + data.totalVolume24hUsd.toLocaleString())}`);
220
- console.log(`${pc.gray('BTC Dominance:')} ${pc.yellow(data.bitcoinDominancePercentage.toFixed(2) + '%')}`);
221
- console.log(`${pc.gray('ETH Dominance:')} ${pc.blue(data.ethereumDominancePercentage.toFixed(2) + '%')}`);
222
- console.log(`${pc.gray('Active Coins:')} ${pc.white(data.activeCryptocurrencies.toLocaleString())}`);
223
- console.log(pc.white(`----------------------------------------`));
224
- console.log(`${pc.gray('Updated:')} ${new Date(data.lastUpdated).toLocaleTimeString()}`);
225
- console.log(pc.white(`----------------------------------------\n`));
226
- };
227
-
228
- const handleSentiment = async () => {
229
- console.log(pc.cyan(`\nFetching Fear & Greed Index...`));
230
-
231
- const data = await crypull.sentiment();
232
-
233
- if (!data) {
234
- console.log(pc.red(`\n✖ Could not fetch sentiment data at this time.`));
235
- return;
236
- }
237
-
238
- const value = data.value;
239
- let color = pc.white;
240
- if (value <= 25) color = pc.red;
241
- else if (value <= 45) color = pc.yellow;
242
- else if (value <= 55) color = pc.white;
243
- else if (value <= 75) color = pc.green;
244
- else color = pc.blue;
245
-
246
- console.log(pc.green(`\n✔ Current Market Sentiment:`));
247
- console.log(pc.white(`----------------------------------------`));
248
- console.log(`${pc.gray('Score:')} ${color(pc.bold(value.toString()) + ' / 100')}`);
249
- console.log(`${pc.gray('Classification:')} ${color(pc.bold(data.classification))}`);
250
- console.log(pc.white(`----------------------------------------\n`));
251
- };
252
-
253
- const handleGas = async () => {
254
- console.log(pc.cyan(`\nFetching network gas prices...`));
255
-
256
- const data = await crypull.gas();
257
-
258
- if (!data) {
259
- console.log(pc.red(`\n✖ Could not fetch gas prices at this time.`));
260
- return;
261
- }
262
-
263
- console.log(pc.green(`\n✔ ${data.network} Gas Tracker (Gwei):`));
264
- console.log(pc.white(`----------------------------------------`));
265
- console.log(`${pc.gray('Low (Safe):')} ${pc.green(data.low + ' gwei')}`);
266
- console.log(`${pc.gray('Average:')} ${pc.yellow(data.average + ' gwei')}`);
267
- console.log(`${pc.gray('High (Fast):')} ${pc.red(data.high + ' gwei')}`);
268
- if (data.baseFee) {
269
- console.log(`${pc.gray('Base Fee:')} ${pc.white(data.baseFee + ' gwei')}`);
270
- }
271
- console.log(pc.white(`----------------------------------------\n`));
272
- };
273
-
274
- const handleChart = async (query: string, options: { days: string }) => {
275
- const days = parseInt(options.days) || 7;
276
- console.log(pc.cyan(`\nFetching ${days}-day chart data for ${pc.bold(query)}...`));
277
-
278
- const data = await crypull.chart(query, days);
279
-
280
- if (!data || !data.prices || data.prices.length === 0) {
281
- console.log(pc.red(`\n✖ Could not fetch chart data for "${query}". Note: Charts may only be available for major coins.`));
282
- return;
283
- }
284
-
285
- // Determine color based on price action
286
- const firstPrice = data.prices[0];
287
- const lastPrice = data.prices[data.prices.length - 1];
288
- const isUp = lastPrice >= firstPrice;
289
-
290
- const chartConfig = {
291
- colors: [isUp ? asciichart.lightgreen : asciichart.lightred],
292
- height: 10
293
- };
294
-
295
- console.log(pc.green(`\n✔ ${days}-Day Chart for ${query.toUpperCase()}:`));
296
- console.log(pc.gray(`Min: $${data.minPrice.toLocaleString(undefined, { maximumFractionDigits: 6 })} | Max: $${data.maxPrice.toLocaleString(undefined, { maximumFractionDigits: 6 })}`));
297
- console.log(pc.white(`\n` + asciichart.plot(data.prices, chartConfig) + `\n`));
298
- };
299
-
300
- const handleDonate = () => {
301
- console.log(pc.cyan(`\n💖 Support the development of crypull:`));
302
- console.log(pc.white(`----------------------------------------`));
303
- console.log(`${pc.yellow('BTC:')} ${pc.white('bc1qj4zt3lva4r68xspayg0p8s4hyg40nhjz8fuhqq')}`);
304
- console.log(`${pc.blue('EVM (All):')} ${pc.white('0x63a875d0c4Dad8E18B95D844caE6FF915dF0a2BD')}`);
305
- console.log(`${pc.green('Solana:')} ${pc.white('8J5VvZu6ayQa4XnSAAzx4YX3QsXYyyNrP4Zr7JEx1KFY')}`);
306
- console.log(`${pc.red('TRX:')} ${pc.white('TPgZSrHUhKdjyMwaGd15utJvsbk85oBbit')}`);
307
- console.log(pc.white(`----------------------------------------\n`));
308
- };
309
-
310
- // Register commands
311
- program
312
- .command('price <query>')
313
- .description('Get the current price of a cryptocurrency (symbol or contract address)')
314
- .action(handlePrice);
315
-
316
- program
317
- .command('info <query>')
318
- .description('Get detailed info about a cryptocurrency (market cap, volume, FDV, etc.)')
319
- .action(handleInfo);
320
-
321
- program
322
- .command('top')
323
- .description('Show top 50 cryptocurrencies by market cap')
324
- .action(handleTop);
325
-
326
- program
327
- .command('search <query>')
328
- .description('Search for tokens or coins across multiple providers')
329
- .action(handleSearch);
330
-
331
- program
332
- .command('trending')
333
- .description('Show top 10 trending coins/tokens right now')
334
- .action(handleTrending);
335
-
336
- program
337
- .command('market')
338
- .description('Show global cryptocurrency market overview')
339
- .action(handleMarket);
340
-
341
- program
342
- .command('sentiment')
343
- .description('Show current Crypto Fear & Greed Index')
344
- .action(handleSentiment);
345
-
346
- program
347
- .command('gas')
348
- .description('Show current Ethereum network gas prices')
349
- .action(handleGas);
350
-
351
- program
352
- .command('chart <query>')
353
- .description('Draw a terminal ASCII chart of historical prices')
354
- .option('-d, --days <days>', 'Number of days to chart', '7')
355
- .action(handleChart);
356
-
357
- program
358
- .command('donate')
359
- .description('Show donation addresses to support development')
360
- .action(handleDonate);
361
-
362
- async function interactiveMode() {
363
- console.clear();
364
- intro(pc.bgCyan(pc.black(' crypull CLI ')));
365
-
366
- while (true) {
367
- const action = await select({
368
- message: 'What would you like to do?',
369
- options: [
370
- { value: 'price', label: '💰 Get token price' },
371
- { value: 'info', label: 'ℹ️ Get detailed token info' },
372
- { value: 'top', label: '🏆 Show top 50 cryptocurrencies' },
373
- { value: 'search', label: '🔍 Search for a token' },
374
- { value: 'trending', label: '🔥 Show trending coins' },
375
- { value: 'market', label: '🌍 Show global market overview' },
376
- { value: 'sentiment', label: '🎭 Show Fear & Greed Index' },
377
- { value: 'gas', label: '⛽ Show ETH gas prices' },
378
- { value: 'chart', label: '📈 Show historical price chart' },
379
- { value: 'donate', label: '💖 Donate / Support' },
380
- { value: 'exit', label: '❌ Exit' },
381
- ]
382
- });
383
-
384
- if (isCancel(action) || action === 'exit') {
385
- outro('Goodbye!');
386
- process.exit(0);
387
- }
388
-
389
- if (['price', 'info', 'search', 'chart'].includes(action as string)) {
390
- const query = await text({
391
- message: 'Enter token symbol or contract address:',
392
- placeholder: 'e.g., btc, ethereum, 0x...',
393
- validate: (value) => {
394
- if (!value) return 'Please enter a valid query.';
395
- }
396
- });
397
-
398
- if (isCancel(query)) {
399
- outro('Goodbye!');
400
- process.exit(0);
401
- }
402
-
403
- if (action === 'price') await handlePrice(query as string);
404
- else if (action === 'info') await handleInfo(query as string);
405
- else if (action === 'search') await handleSearch(query as string);
406
- else if (action === 'chart') {
407
- const days = await text({
408
- message: 'Enter number of days for the chart (default 7):',
409
- placeholder: '7',
410
- defaultValue: '7'
411
- });
412
- if (isCancel(days)) {
413
- outro('Goodbye!');
414
- process.exit(0);
415
- }
416
- await handleChart(query as string, { days: days as string });
417
- }
418
- } else {
419
- if (action === 'top') await handleTop();
420
- else if (action === 'trending') await handleTrending();
421
- else if (action === 'market') await handleMarket();
422
- else if (action === 'sentiment') await handleSentiment();
423
- else if (action === 'gas') await handleGas();
424
- else if (action === 'donate') handleDonate();
425
- }
426
-
427
- console.log(pc.gray('\n---\n'));
428
- }
429
- }
430
-
431
- if (process.argv.length <= 2) {
432
- // Run interactive mode
433
- interactiveMode().catch((err) => {
434
- console.error(pc.red('An error occurred:'), err);
435
- process.exit(1);
436
- });
437
- } else {
438
- // Use commander parsing
439
- program.parse(process.argv);
440
- }
package/src/index.ts DELETED
@@ -1,14 +0,0 @@
1
- export * from './types.js';
2
- export * from './Crypull.js';
3
- export * from './providers/coingecko.js';
4
- export * from './providers/dexscreener.js';
5
- export * from './providers/geckoterminal.js';
6
- export * from './providers/binance.js';
7
- export * from './providers/coinpaprika.js';
8
- export * from './providers/coincap.js';
9
- export * from './providers/cryptocompare.js';
10
-
11
- import { Crypull } from './Crypull.js';
12
-
13
- // Export a default instance for quick usage
14
- export const crypull = new Crypull();
@@ -1,74 +0,0 @@
1
- import { ICryptoProvider, PriceData, SearchResult, TokenInfo } from '../types.js';
2
-
3
- export class BinanceProvider implements ICryptoProvider {
4
- name = 'Binance';
5
- private baseUrl = 'https://api.binance.com/api/v3';
6
-
7
- async search(query: string): Promise<SearchResult[]> {
8
- try {
9
- // Binance doesn't have a direct "search" that returns symbols nicely for our format
10
- // We can fetch exchangeInfo, but it's large. For speed, we return a mock match if they query
11
- // or we just return an empty array and rely on other providers for search.
12
- // But let's try a quick hack: if query is short, construct a symbol.
13
- const symbol = query.toUpperCase();
14
- const res = await fetch(`${this.baseUrl}/ticker/price?symbol=${symbol}USDT`);
15
- if (res.ok) {
16
- return [{
17
- id: `${symbol}USDT`,
18
- name: symbol,
19
- symbol: symbol,
20
- source: this.name
21
- }];
22
- }
23
- return [];
24
- } catch (e) {
25
- return [];
26
- }
27
- }
28
-
29
- async getPrice(symbol: string): Promise<PriceData | null> {
30
- try {
31
- let querySymbol = symbol.toUpperCase();
32
- if (!querySymbol.endsWith('USDT') && !querySymbol.endsWith('BUSD') && !querySymbol.endsWith('BTC')) {
33
- querySymbol += 'USDT';
34
- }
35
-
36
- const res = await fetch(`${this.baseUrl}/ticker/price?symbol=${querySymbol}`);
37
- if (!res.ok) return null;
38
- const data = await res.json();
39
-
40
- return {
41
- symbol: symbol.toUpperCase(),
42
- priceUsd: parseFloat(data.price) || 0,
43
- source: this.name,
44
- lastUpdated: Date.now(),
45
- };
46
- } catch (e) {
47
- return null;
48
- }
49
- }
50
-
51
- async getTokenInfo(symbol: string): Promise<TokenInfo | null> {
52
- try {
53
- let querySymbol = symbol.toUpperCase();
54
- if (!querySymbol.endsWith('USDT') && !querySymbol.endsWith('BUSD') && !querySymbol.endsWith('BTC')) {
55
- querySymbol += 'USDT';
56
- }
57
-
58
- const res = await fetch(`${this.baseUrl}/ticker/24hr?symbol=${querySymbol}`);
59
- if (!res.ok) return null;
60
- const data = await res.json();
61
-
62
- return {
63
- name: symbol.toUpperCase(),
64
- symbol: symbol.toUpperCase(),
65
- priceUsd: parseFloat(data.lastPrice) || 0,
66
- volume24h: parseFloat(data.quoteVolume) || 0, // Quote volume in USDT roughly = USD volume
67
- source: this.name,
68
- lastUpdated: Date.now(),
69
- };
70
- } catch (e) {
71
- return null;
72
- }
73
- }
74
- }
@@ -1,65 +0,0 @@
1
- import { ICryptoProvider, PriceData, SearchResult, TokenInfo } from '../types.js';
2
-
3
- export class CoinCapProvider implements ICryptoProvider {
4
- name = 'CoinCap';
5
- private baseUrl = 'https://api.coincap.io/v2';
6
-
7
- async search(query: string): Promise<SearchResult[]> {
8
- try {
9
- const res = await fetch(`${this.baseUrl}/assets?search=${query}&limit=10`);
10
- if (!res.ok) return [];
11
- const data = await res.json();
12
-
13
- return (data.data || []).map((coin: any) => ({
14
- id: coin.id,
15
- name: coin.name,
16
- symbol: coin.symbol.toUpperCase(),
17
- source: this.name,
18
- }));
19
- } catch (e) {
20
- return [];
21
- }
22
- }
23
-
24
- async getPrice(symbolOrId: string): Promise<PriceData | null> {
25
- const info = await this.getTokenInfo(symbolOrId);
26
- if (!info) return null;
27
- return {
28
- symbol: info.symbol,
29
- priceUsd: info.priceUsd,
30
- source: this.name,
31
- lastUpdated: info.lastUpdated,
32
- };
33
- }
34
-
35
- async getTokenInfo(symbolOrId: string): Promise<TokenInfo | null> {
36
- try {
37
- let id = symbolOrId.toLowerCase();
38
-
39
- const searchRes = await this.search(id);
40
- const match = searchRes.find(s => s.symbol.toLowerCase() === id || s.id === id);
41
- if (match && match.id) {
42
- id = match.id;
43
- }
44
-
45
- const res = await fetch(`${this.baseUrl}/assets/${id}`);
46
- if (!res.ok) return null;
47
- const data = await res.json();
48
- const asset = data.data;
49
-
50
- if (!asset) return null;
51
-
52
- return {
53
- name: asset.name,
54
- symbol: asset.symbol.toUpperCase(),
55
- priceUsd: parseFloat(asset.priceUsd) || 0,
56
- marketCap: parseFloat(asset.marketCapUsd),
57
- volume24h: parseFloat(asset.volumeUsd24Hr),
58
- source: this.name,
59
- lastUpdated: Date.now(),
60
- };
61
- } catch (e) {
62
- return null;
63
- }
64
- }
65
- }
@@ -1,92 +0,0 @@
1
- import { ICryptoProvider, PriceData, SearchResult, TokenInfo } from '../types.js';
2
-
3
- export class CoinGeckoProvider implements ICryptoProvider {
4
- name = 'CoinGecko';
5
- private baseUrl = 'https://api.coingecko.com/api/v3';
6
-
7
- async search(query: string): Promise<SearchResult[]> {
8
- try {
9
- const res = await fetch(`${this.baseUrl}/search?query=${query}`);
10
- if (!res.ok) return [];
11
- const data = await res.json();
12
- return (data.coins || []).slice(0, 10).map((coin: any) => ({
13
- id: coin.id,
14
- name: coin.name,
15
- symbol: coin.symbol.toUpperCase(),
16
- source: this.name,
17
- }));
18
- } catch (e) {
19
- return [];
20
- }
21
- }
22
-
23
- async getPrice(symbolOrId: string): Promise<PriceData | null> {
24
- try {
25
- let id = symbolOrId.toLowerCase();
26
-
27
- const searchRes = await this.search(id);
28
- const match = searchRes.find(s => s.symbol.toLowerCase() === id || s.id === id);
29
- if (match && match.id) {
30
- id = match.id;
31
- }
32
-
33
- const res = await fetch(`${this.baseUrl}/simple/price?ids=${id}&vs_currencies=usd`);
34
- if (!res.ok) return null;
35
- const data = await res.json();
36
-
37
- if (!data[id] || typeof data[id].usd === 'undefined') return null;
38
-
39
- return {
40
- symbol: match ? match.symbol : id.toUpperCase(),
41
- priceUsd: data[id].usd,
42
- source: this.name,
43
- lastUpdated: Date.now(),
44
- };
45
- } catch (e) {
46
- return null;
47
- }
48
- }
49
-
50
- async getTokenInfo(id: string): Promise<TokenInfo | null> {
51
- try {
52
- // By default, assuming id is the coingecko internal ID (like "bitcoin")
53
- const res = await fetch(`${this.baseUrl}/coins/${id.toLowerCase()}?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false&sparkline=false`);
54
- if (!res.ok) return null;
55
- const data = await res.json();
56
-
57
- if (data.error) return null;
58
-
59
- return {
60
- name: data.name,
61
- symbol: data.symbol.toUpperCase(),
62
- description: data.description?.en,
63
- priceUsd: data.market_data?.current_price?.usd || 0,
64
- marketCap: data.market_data?.market_cap?.usd,
65
- marketCapRank: data.market_cap_rank,
66
- fdv: data.market_data?.fully_diluted_valuation?.usd,
67
- circulatingSupply: data.market_data?.circulating_supply,
68
- totalSupply: data.market_data?.total_supply,
69
- maxSupply: data.market_data?.max_supply,
70
- volume24h: data.market_data?.total_volume?.usd,
71
- priceChange24h: data.market_data?.price_change_24h,
72
- priceChangePercentage24h: data.market_data?.price_change_percentage_24h,
73
- priceChangePercentage7d: data.market_data?.price_change_percentage_7d,
74
- ath: data.market_data?.ath?.usd,
75
- athDate: data.market_data?.ath_date?.usd,
76
- atl: data.market_data?.atl?.usd,
77
- atlDate: data.market_data?.atl_date?.usd,
78
- links: {
79
- website: data.links?.homepage?.[0],
80
- twitter: data.links?.twitter_screen_name ? `https://twitter.com/${data.links.twitter_screen_name}` : undefined,
81
- telegram: data.links?.telegram_channel_identifier ? `https://t.me/${data.links.telegram_channel_identifier}` : undefined,
82
- discord: data.links?.chat_url?.find((url: string) => url.includes('discord')),
83
- github: data.links?.repos_url?.github?.[0],
84
- },
85
- source: this.name,
86
- lastUpdated: Date.now(),
87
- };
88
- } catch (e) {
89
- return null;
90
- }
91
- }
92
- }