forked from sven-hash/ayin-price
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.html
394 lines (316 loc) · 12.8 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<title>Ayin DEX price tracker</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<style>
body.dark-mode {
background-color: #121212;
color: #e0e0e0;
}
.dark-mode h4,
.dark-mode p,
.dark-mode a {
color: #e0e0e0;
}
html,
body {
height: 100%;
}
html {
display: table;
margin: auto;
}
body {
display: table-cell;
vertical-align: middle;
font-family: "Consolas";
}
button.link {
background: none;
border: none;
}
table,
th,
td {
table-layout: fixed;
}
th,
td {
padding: 10px;
}
.dark-mode tr:nth-child(even) {
background-color: hsl(180, 83%, 16%);
}
tr:nth-child(even) {
background-color: hsl(180, 84%, 39%);
}
</style>
<script src="./tokens.js"></script>
<script>
const ALPH_DECIMALS = 18;
const EXPLORER_BASEURL = "https://explorer.mainnet.alephium.org"
//const BACKEND_BASEURL = "https://backend.mainnet.alephium.org"
const BACKEND_BASEURL = "https://explorer.alephium.notrustverify.ch"
document.addEventListener("DOMContentLoaded", async function (event) {
const alphUsd = await getAlphUsd()
document.getElementById("autoUpdate").checked = false
alphPriceText(alphUsd)
await textPrice(alphUsd)
document.getElementById("loading").remove()
});
function alphPriceText(alphUsd) {
document.getElementById("alphPrice").innerHTML = "<i>ALPH Price $" + alphUsd + "</i>"
}
async function textPrice(alphUsd) {
const tokenListElement = document.getElementById("tokenlisttable");
// Prepare to fetch all prices in parallel
const pricePromises = tokenList.map(async (value) => {
try {
const price = await getPrice(value["contractid"], value["tokenid"], value["decimals"]);
const alphBalance = price[0];
const tokenBalance = price[1];
const pricePerAlph = alphBalance / tokenBalance;
let supply = value['supply'] || 0;
let maxSupply = 0;
// Calculate circulating supply if address is provided
if (value["circulating_supply_address"] !== undefined) {
supply = await getCirculatingSupply(value["supply"], value["circulating_supply_address"], value["tokenid"], value["decimals"]);
maxSupply = value["supply"];
}
return {
...value,
priceText: value["symbol"],
pricePerAlph: pricePerAlph.toFixed(6),
priceUsd: pricePerAlph * alphUsd,
supply,
maxSupply
};
} catch (err) {
console.error(err);
return { ...value, priceText: "error, cannot fetch price" };
}
});
// Wait for all promises to resolve
const tokensWithPrices = await Promise.all(pricePromises);
tokensWithPrices.sort((a, b) => {
let keyA = a.supply * a.priceUsd
let keyB = b.supply * b.priceUsd
if (keyA > keyB) return -1;
if (keyA < keyB) return 1;
return 0;
});
let counterPos = 1
tokensWithPrices.forEach((value) => {
const explorerLink = `${EXPLORER_BASEURL}/addresses/${value['contractid']}`;
const tr = document.createElement("tr");
const trPos = document.createElement("td")
trPos.innerHTML = `<b>${counterPos++}</b>`
tr.appendChild(trPos)
tr.id = value["symbol"]
const symbol = document.createElement("td");
symbol.innerHTML = `<a target='_blank' rel='noopener noreferrer' title=${explorerLink} href=${explorerLink}>${value["symbol"]}</a>`;
tr.appendChild(symbol);
const tdPriceAlph = document.createElement("td")
tdPriceAlph.innerText = `ℵ${value.pricePerAlph}`
tdPriceAlph.id = `${value["symbol"]}pricealph`
const tdPriceUsd = document.createElement("td")
tdPriceUsd.innerText = `$${value.priceUsd.toFixed(6)}`
tdPriceUsd.id = `${value["symbol"]}priceusd`
tr.appendChild(tdPriceAlph)
tr.appendChild(tdPriceUsd)
// Supply and Market Cap
if (value["supply"] !== undefined) {
const paraMc = document.createElement("td");
paraMc.id = `${value["symbol"]}mc`
const paraSupply = document.createElement("td");
tr.appendChild(paraMc);
tr.appendChild(paraSupply);
paraSupply.innerHTML = formatNumber(value.supply);
const paraMaxSupply = document.createElement("td");
tr.appendChild(paraMaxSupply);
paraMaxSupply.innerHTML = value.maxSupply > 0 ? formatNumber(value.maxSupply) : formatNumber(value['supply']);
paraMc.innerHTML = "$" + formatNumber((value.supply * value.pricePerAlph * alphUsd).toFixed(0));
}
// Optional Dashboard Iframe
if (value["//url_dashboard"] !== undefined) {
const details = document.createElement("details");
const summary = document.createElement("summary");
const iframe = document.createElement("iframe");
iframe.src = value["//url_dashboard"];
iframe.style = "width: 450px; height: 200px; border: none;";
summary.innerText = "Historical data";
details.appendChild(summary);
details.appendChild(iframe);
tr.appendChild(details);
}
tokenListElement.appendChild(tr);
});
}
function formatNumber(number) {
const formatter = Intl.NumberFormat("en", { notation: "standard" });
return formatter.format(number);
}
function parseLocaleNumber(stringNumber, locale) {
var thousandSeparator = Intl.NumberFormat(locale).format(11111).replace(/\p{Number}/gu, '');
var decimalSeparator = Intl.NumberFormat(locale).format(1.1).replace(/\p{Number}/gu, '');
return parseFloat(stringNumber
.replace(new RegExp('\\' + thousandSeparator, 'g'), '')
.replace(new RegExp('\\' + decimalSeparator), '.')
);
}
async function updatePrices() {
// First, get the current ALPH/USD price to use for all tokens
const alphUsd = await getAlphUsd();
alphPriceText(alphUsd);
// Map each token to a promise that fetches its price and updates the UI
const updatePromises = tokenList.map(async (value) => {
try {
const [alphBalance, tokenBalance] = await getPrice(
value["contractid"],
value["tokenid"],
value["decimals"]
);
const pricePerAlph = alphBalance / tokenBalance;
const priceText = pricePerAlph.toFixed(6);
const priceUsd = pricePerAlph * alphUsd
let supply = 0
if (value["circulating_supply_address"] !== undefined) {
supply = await getCirculatingSupply(value["supply"], value["circulating_supply_address"], value["tokenid"], value["decimals"]);
}
const mc = supply > 0 ? supply * pricePerAlph * alphUsd : 0
return { symbol: value["symbol"], priceText, priceUsd, mc };
} catch (err) {
console.error(err);
return { symbol: value["symbol"], priceText: "error, cannot fetch price" };
}
});
// Wait for all the price update promises to resolve
const updatedPrices = await Promise.all(updatePromises);
// Update the UI for each token with the new price
updatedPrices.forEach(async ({ symbol, priceText, priceUsd, mc }) => {
const priceP = document.getElementById(`${symbol}pricealph`);
const pricePusd = document.getElementById(`${symbol}priceusd`);
const mcTable = document.getElementById(`${symbol}mc`)
if (priceP && mc > 0) {
priceP.innerText = `ℵ${priceText}`;
pricePusd.innerText = `$${priceUsd.toFixed(6)}`;
mcTable.innerText = `$${formatNumber(mc.toFixed(0))}`
}
});
}
function updateSelection(autoUpdateCheckBox) {
if (autoUpdateCheckBox.checked) {
updatePrices()
intervalUpdate = setInterval(updatePrices, 40000);
}
else {
if (typeof intervalUpdate !== 'undefined')
clearInterval(intervalUpdate);
}
};
async function getPrice(contractid, tokenid, decimals) {
const price = await Promise.all([
await fetch(
BACKEND_BASEURL + "/addresses/" +
contractid +
"/tokens/" +
tokenid +
"/balance"
).then((resp) => resp.json()),
await fetch(
BACKEND_BASEURL + "/addresses/" +
contractid +
"/balance"
).then((resp) => resp.json()),
]).then((allResponses) => {
tokenBalance =
parseFloat(allResponses[0]["balance"]) / Math.pow(10, decimals);
alphBalance =
parseFloat(allResponses[1]["balance"]) /
Math.pow(10, ALPH_DECIMALS);
return new Promise((resolve, reject) => {
resolve([alphBalance, tokenBalance]);
});
}).catch(err => { console.error(err) })
return price;
}
async function getAlphUsd() {
const priceUsd =
await fetch(
"https://api.coingecko.com/api/v3/simple/price?ids=alephium&vs_currencies=usd").then((resp) => resp.json()).then(data => { return data['alephium']['usd'] }).catch(error => {
console.error(error)
return 0
})
return priceUsd
}
async function getCirculatingSupply(supply, address, tokenid, decimals) {
const leftSupply =
await fetch(
BACKEND_BASEURL + "/addresses/" +
address +
"/tokens/" +
tokenid +
"/balance"
).then((resp) => resp.json()).then(data => { return data['balance'] }).catch(error => {
console.error(error)
return 0
}
)
return supply - (leftSupply / Math.pow(10, decimals))
}
document.addEventListener('DOMContentLoaded', function () {
const checkbox = document.getElementById('darkModeCheckbox');
checkbox.addEventListener('change', function () {
if (this.checked) {
document.body.classList.add('dark-mode');
} else {
document.body.classList.remove('dark-mode');
}
});
// Optional: Save dark mode preference in localStorage and read it on page load
const currentTheme = localStorage.getItem('darkMode') || 'light';
if (currentTheme === 'dark') {
document.body.classList.add('dark-mode');
checkbox.checked = true;
}
checkbox.addEventListener('change', function () {
if (this.checked) {
localStorage.setItem('darkMode', 'dark');
} else {
localStorage.setItem('darkMode', 'light');
}
});
});
</script>
<div id="dark-mode-toggle" style=" top: -.200em; right: 0; padding: 15px;">
<label>
<input type="checkbox" id="autoUpdate" onchange="updateSelection(this)">Auto update
</label>
<label>
<input type="checkbox" id="darkModeCheckbox"> Dark Mode
</label>
</div>
<p style="padding-left: 1em;margin-bottom: -1em;margin-top: 1.5em;" id="alphPrice"></p>
<div style="text-align: center;">
<h1>Prices of <a href="https://ayin.app">AYIN DEX</a> pairs</h1>
<p><small>Proposed to you by</small> <a href="https://notrustverify.ch"> No Trust Verify</a></p>
<p id="loading">Loading...</p>
<div style="overflow-x:auto;">
<table id="tokenlisttable">
<tr>
<td><b>#</b></td>
<td><b>Coin</b></td>
<td><b>Price</b></td>
<td><b>Price (USD)</b></td>
<td><b>Market Cap</b></td>
<td><b>Circ.</b></td>
<td><b>Total</b></td>
</tr>
</table>
</div>
</div>
</body>
</html>