-
Notifications
You must be signed in to change notification settings - Fork 0
/
assets.js
355 lines (339 loc) · 15.2 KB
/
assets.js
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
const displayNameCache = {};
document.addEventListener('DOMContentLoaded', function() {
fetchBlockHeight()
.then(currentHeight => {
fetchBlockReward(currentHeight);
return Promise.all([
fetchCirculatingSupply(),
fetchDailyBlocks(),
]);
})
.then(() => {
calculateDailyQort();
})
.catch(error => {
console.error('An error occurred in the fetch chain:', error);
});
fetchAssets();
});
document.getElementById('search-button').addEventListener('click', handleSearch);
document.getElementById('search-input').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
handleSearch();
}
});
async function fetchAssets() {
document.getElementById('asset-details').textContent = 'Loading';
try {
const response = await fetch('/assets');
const results = await response.json();
let tableHtml = '<table>';
tableHtml += `
<tr>
<th>Name</th>
<th>Description</th>
<th>Owner</th>
<th>Quantity</th>
</tr>
`;
for (const result of results) {
let assetQuantity = (result.isDivisible === false) ? (result.quantity / 100000000) : result.quantity;
let assetOwner = await displayNameOrAddress(result.owner);
tableHtml += `<tr>
<td>${result.assetId}: ${result.name}</td>
<td>${result.description}</td>
<td>${assetOwner}</td>
<td>${assetQuantity}</td>
</tr>`;
}
tableHtml += '</table>';
document.getElementById('asset-details').innerHTML = tableHtml;
} catch (error) {
document.getElementById('asset-details').textContent = `Error fetching assets: ${error}`;
console.error('Error fetching assets:', error);
}
}
function fetchBlockHeight() {
document.getElementById('block-height').textContent = 'Loading';
return fetch('/blocks/height')
.then(response => response.text())
.then(data => {
document.getElementById('block-height').textContent = data;
return data;
})
.catch(error => {
document.getElementById('block-height').textContent = `Error fetching block height: ${error}`;
console.error('Error fetching block height:', error);
});
}
function fetchBlockReward(currentHeight) {
document.getElementById('block-reward').textContent = 'Loading';
let reward = 5;
const decreaseInterval = 259200;
if (currentHeight > decreaseInterval) {
reward -= Math.floor((currentHeight - 1) / decreaseInterval) * 0.25;
}
document.getElementById('block-reward').textContent = reward.toFixed(2);
}
function fetchCirculatingSupply() {
document.getElementById('total-supply').textContent = 'Loading';
return fetch('/stats/supply/circulating')
.then(response => response.text())
.then(data => {
document.getElementById('total-supply').textContent = parseFloat(data).toFixed(2);
return parseFloat(data);
})
.catch(error => {
document.getElementById('total-supply').textContent = `Error fetching circulating supply: ${error}`;
console.error('Error fetching circulating supply:', error);
throw error;
});
}
function fetchDailyBlocks() {
document.getElementById('blocks-past-day').textContent = 'Loading';
return fetch('/blocks/height')
.then(response => response.text())
.then(currentBlockHeight => {
return currentBlockHeight;
})
.then(currentBlockHeight => {
currentBlockHeight = parseInt(currentBlockHeight);
return fetch('/utils/timestamp')
.then(response => response.text())
.then(currentTimestamp => {
const oneDayAgoTimestamp = parseInt(currentTimestamp) - (24 * 60 * 60 * 1000);
return fetch('/blocks/timestamp/' + oneDayAgoTimestamp)
.then(response => response.json())
.then(data => {
const oneDayAgoBlockHeight = data.height;
const blocksInPastDay = currentBlockHeight - oneDayAgoBlockHeight;
document.getElementById('blocks-past-day').textContent = blocksInPastDay;
return blocksInPastDay;
});
});
})
.catch(error => {
console.error('Error in fetchDailyBlocks:', error);
});
}
function calculateDailyQort() {
document.getElementById('qort-per-day').textContent = 'Loading';
const blocksInPastDay = parseInt(document.getElementById('blocks-past-day').textContent);
const blockReward = parseFloat(document.getElementById('block-reward').textContent);
const dailyQort = blocksInPastDay * blockReward;
const totalCirculatingSupply = parseFloat(document.getElementById('total-supply').textContent);
const percentageOfTotal = (dailyQort / totalCirculatingSupply) * 100;
const dailyQortString = `${dailyQort.toFixed(2)} QORT (${percentageOfTotal.toFixed(2)}% of total)`;
document.getElementById('qort-per-day').textContent = dailyQortString;
}
function handleSearch() {
const searchQuery = document.getElementById('search-input').value;
if (!searchQuery) return;
if (searchQuery.startsWith('Q') && !searchQuery.includes('0') && !searchQuery.includes('O') && !searchQuery.includes('I') && !searchQuery.includes('l') && searchQuery.length >= 26 && searchQuery.length <= 35) {
validateAddress(searchQuery);
} else if (searchQuery.length >= 3 && searchQuery.length <= 40) {
searchByName(searchQuery);
}
}
function validateAddress(address) {
fetch('/addresses/validate/' + address)
.then(response => response.json())
.then(isValid => {
if (isValid) {
fetchAddressDetails(address);
} else {
alert('Invalid address.');
}
})
.catch(error => console.error('Error validating address:', error));
}
function fetchAddressDetails(address) {
document.getElementById('account-details').innerHTML = '<p>Loading</p>';
Promise.all([
fetch('/addresses/' + address).then(response => response.json()),
fetch('/addresses/balance/' + address).then(response => response.text()),
fetch('/names/address/' + address).then(response => response.json()),
fetch('/addresses/rewardshares?involving=' + address).then(response => response.json())
]).then(async ([addressDetails, balance, names, rewardShares]) => {
let tableHtml = '<table>';
if (names.length > 0) {
tableHtml += `<tr><th>Registered Name</th><th><img src="/arbitrary/THUMBNAIL/${names[0].name}/qortal_avatar"
style="width:48px;height:48px;"
onerror="this.style.display='none'"
>${names[0].name}</th></tr>`;
}
tableHtml += `
<tr><th>Address</th><th>${address}</th></tr>
<tr><td>Public Key</td><td>${addressDetails.publicKey}</td></tr>
<tr><td>Level</td><td>${addressDetails.level}${addressDetails.flags === 1 ? ' (Founder)' : ''}</td></tr>
<tr><td>Blocks Minted</td>
<td>
${addressDetails.blocksMinted}
${addressDetails.blocksMintedAdjustment > 0 ? ` +${addressDetails.blocksMintedAdjustment}` : ''}
${addressDetails.blocksMintedPenalty < 0 ? ` ${addressDetails.blocksMintedPenalty}` : ''}
${addressDetails.blocksMintedAdjustment > 0 || addressDetails.blocksMintedPenalty < 0 ?
` (Total: ${addressDetails.blocksMinted+addressDetails.blocksMintedAdjustment+addressDetails.blocksMintedPenalty})` : ''}
</td></tr>
<tr><td>Balance</td><td>${parseFloat(balance).toFixed(8)} QORT</td></tr>`;
let selfShare = '';
let shareList = [];
let shareHtml = '';
for (const share of rewardShares) {
if (share.recipient === share.mintingAccount) {
let displayName = await displayNameOrAddress(share.recipient);
selfShare = displayName;
} else if (address === share.mintingAccount) {
let displayName = await displayNameOrAddress(share.recipient);
let shareElement = `<span class="clickable-name" data-name="${share.recipient}">${displayName}</span>`;
shareList.push(shareElement);
} else if (address === share.recipient) {
let displayName = await displayNameOrAddress(share.mintingAccount);
let shareElement = `(from <span class="clickable-name" data-name="${share.mintingAccount}">${displayName}</span>)`;
shareList.push(shareElement);
}
}
shareHtml = (selfShare ? (shareList[0] ? `${selfShare} | ` : selfShare) : '') + shareList.join(' | ');
tableHtml += `<tr><td>Active Rewardshares</td><td>${shareHtml}</td></tr>`;
if (names.length > 0) {
const response = await fetch(`/arbitrary/resources/search?name=${names[0].name}&includemetadata=true&exactmatchnames=true&mode=ALL`);
const results = await response.json();
if (results.length > 0) {
let totalFiles = 0;
let totalSize = 0;
results.forEach(result => {
totalFiles += 1;
totalSize += result.size;
});
let totalSizeString = formatSize(totalSize);
tableHtml += `<tr><th>QDN Content</th><th>${totalFiles} Files</th></tr><tr><td>Total Size</td><td>${totalSizeString}</td></tr>`;
}
}
tableHtml += `</table>`;
document.getElementById('account-details').innerHTML = tableHtml;
document.querySelectorAll('.clickable-name').forEach(element => {
element.addEventListener('click', function() {
document.body.scrollTop = document.documentElement.scrollTop = 0;
let target = this.getAttribute('data-name');
fetchAddressDetails(target);
});
});
}).catch(error => console.error('Error fetching address details:', error));
}
/*
async function fetchContent(name) {
try {
document.getElementById('account-details').innerHTML += '<p>Loading QDN...</p>';
const response = await fetch(`/arbitrary/resources/search?name=${name}&includemetadata=true&exactmatchnames=true&mode=ALL`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const results = response.json();
if (results.length > 0) {
let totalFiles = 0;
let totalSize = 0;
results.forEach(result => {
totalFiles += 1;
totalSize += result.size;
let sizeString = formatSize(result.size);
});
let totalSizeString = formatSize(totalSize);
}
let tableHtml = `<table>
<tr><th>QDN Content</th><th>${totalFiles} Files</th></tr>
<tr><td>Total Size</td><td>${totalSizeString}</td></tr>
</table>`;
document.getElementById('account-details').innerHTML += tableHtml;
} catch (error) {
console.error('Error fetching content:', error);
}
}
*/
async function displayNameOrAddress(address) {
if (displayNameCache[address]) {
return displayNameCache[address];
}
try {
const response = await fetch(`/names/address/${address}`);
const names = await response.json();
if (names[0]) {
const displayName = `<img src="/arbitrary/THUMBNAIL/${names[0].name}/qortal_avatar"
style="width:24px;height:24px;"
onerror="this.style='display:none'"
>${names[0].name}`;
displayNameCache[address] = displayName;
return displayName;
} else {
displayNameCache[address] = address;
return address;
}
} catch (error) {
console.error('Error fetching name:', error);
displayNameCache[address] = address;
return address;
}
}
function searchByName(name) {
document.getElementById('account-details').innerHTML = '<p>Loading</p>';
document.getElementById('account-results').innerHTML = '<p>Loading</p>';
fetch('/names/search?query=' + name)
.then(response => response.json())
.then(results => {
if (results.length > 0) {
let tableHtml = '<table>';
tableHtml += `
<tr>
<th>Address</th>
<th>Name</th>
<th>For Sale</th>
<th>Data</th>
<th>Registered</th>
</tr>
`;
results.forEach(result => {
tableHtml += `
<tr>
<td>${result.owner}</td>
<td class="clickable-name" data-name="${result.owner}"><img src="/arbitrary/THUMBNAIL/${result.name}/qortal_avatar"
style="width:24px;height:24px;"
onerror="this.style='display:none'"
>${result.name}</td>
<td>${result.isForSale ? 'YES' : '-'}</td>
<td>${result.data}</td>
<td>${new Date(result.registered).toLocaleString()}</td>
</tr>
`;
});
tableHtml += '</table>';
document.getElementById('account-results').innerHTML = tableHtml;
document.querySelectorAll('.clickable-name').forEach(element => {
element.addEventListener('click', function() {
document.body.scrollTop = document.documentElement.scrollTop = 0;
let target = this.getAttribute('data-name');
fetchAddressDetails(target);
});
});
const exactMatch = results.find(r => r.name.toLowerCase() === name.toLowerCase());
if (exactMatch) {
fetchAddressDetails(exactMatch.owner);
} else {
document.getElementById('account-details').innerHTML = '<p>No exact match found.</p>';
}
} else {
document.getElementById('account-results').innerHTML = '<p>No results found.</p>';
}
})
.catch(error => console.error('Error searching by name:', error));
}
function formatSize(size) {
if (size > (1024*1024*1024*1024)) {
return (size / (1024*1024*1024*1024)).toFixed(2) + ' TB';
} else if (size > (1024*1024*1024)) {
return (size / (1024*1024*1024)).toFixed(2) + ' GB';
} else if (size > (1024*1024)) {
return (size / (1024*1024)).toFixed(2) + ' MB';
} else if (size > 1024) {
return (size / 1024).toFixed(2) + ' KB';
} else {
return size + ' B';
}
}