-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcoingecko.actions.ts
More file actions
181 lines (146 loc) · 4.65 KB
/
Copy pathcoingecko.actions.ts
File metadata and controls
181 lines (146 loc) · 4.65 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
'use server';
const baseUrl = process.env.COINGECKO_BASE_URL!;
const header = {
method: 'GET',
headers: {
'x-cg-pro-api-key': process.env.COINGECKO_API_KEY!,
},
cache: 'no-store' as RequestCache,
};
export async function getCoinList(page: number = 1, perPage: number = 50) {
const params = new URLSearchParams({
vs_currency: 'usd',
order: 'market_cap_desc',
per_page: perPage.toString(),
page: page.toString(),
sparkline: 'false',
locale: 'en',
price_change_percentage: '24h',
});
const res = await fetch(`${baseUrl}/coins/markets?${params}`, header);
if (!res.ok) throw new Error('Failed to fetch CoinGecko API data');
return res.json();
}
export async function getCategories() {
const res = await fetch(
`${baseUrl}/coins/categories`,
header
);
if (!res.ok) throw new Error('Failed to fetch top gainers/losers');
const data = await res.json();
return data.slice(0, 10) || [];
}
export async function getCoinDetails(id: string) {
const res = await fetch(`${baseUrl}/coins/${id}`, header);
if (!res.ok) throw new Error('Failed to fetch CoinGecko API data');
return res.json();
}
export async function getCoinOHLC(
id: string,
days: number | string,
currency?: string,
interval?: 'daily' | 'hourly',
precision?: 'full' | string
) {
const currencyParam = currency || 'usd';
const params = new URLSearchParams({
vs_currency: currencyParam,
days: days.toString(),
});
if (interval) params.append('interval', interval);
if (precision) params.append('precision', precision);
const res = await fetch(`${baseUrl}/coins/${id}/ohlc?${params}`, header);
if (!res.ok) throw new Error('Failed to fetch CoinGecko API data');
return res.json();
}
export async function getTrendingCoins() {
const res = await fetch(`${baseUrl}/search/trending`, header);
if (!res.ok) throw new Error('Failed to fetch trending coins');
const data = await res.json();
return data.coins || [];
}
export async function getTopGainersLosers() {
const res = await fetch(
`${baseUrl}/coins/top_gainers_losers?vs_currency=usd`,
header
);
if (!res.ok) throw new Error('Failed to fetch top gainers/losers');
const data = await res.json();
return {
top_gainers: data.top_gainers.slice(0, 4) || [],
top_losers: data.top_losers.slice(0, 4) || [],
};
}
export async function searchCoins(query: string): Promise<SearchCoin[]> {
if (!query || query.trim().length === 0) return [];
const res = await fetch(
`${baseUrl}/search?query=${encodeURIComponent(query)}`,
header
);
if (!res.ok) throw new Error('Failed to fetch search data');
const data = await res.json();
const coins = data.coins || [];
// Get price data for the search results (limit to first 10)
const coinIds = coins.slice(0, 10).map((coin: SearchCoin) => coin.id);
if (coinIds.length === 0) return [];
try {
const priceParams = new URLSearchParams({
vs_currency: 'usd',
ids: coinIds.join(','),
order: 'market_cap_desc',
per_page: '10',
page: '1',
sparkline: 'false',
});
const priceRes = await fetch(
`${baseUrl}/coins/markets?${priceParams}`,
header
);
if (priceRes.ok) {
const priceData = await priceRes.json();
// Create a map of coin prices
const priceMap = new Map<string, { price: number }>(
priceData.map((coin: CoinMarketData) => [
coin.id,
{
price: coin.current_price,
price_change_percentage_24h: coin.price_change_percentage_24h,
},
])
);
return coins.slice(0, 10).map((coin: SearchCoin) => ({
...coin,
data: priceMap.get(coin.id) || undefined,
}));
}
} catch (error) {
console.error('Failed to fetch price data for search results:', error);
}
return coins.slice(0, 10);
}
export async function fetchPools(
id: string
): Promise<{ id: string; address: string; name: string; network: string }> {
try {
// Fetch onchain data for the coin which includes pool information
const res = await fetch(
`${baseUrl}/onchain/search/pools?query=${encodeURIComponent(id)}`,
header
);
if (!res.ok) {
console.warn(`No pool data found for ${id}`);
return { id: '', address: '', name: '', network: '' };
}
const data = await res.json();
const pool = data.data[0];
return {
id: pool.id as string,
address: pool.attributes.address as string,
name: pool.attributes.name as string,
network: pool.id.split('_')[0] as string,
};
} catch (error) {
console.error('Failed to fetch pools', error);
return { id: '', address: '', name: '', network: '' };
}
}