-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathgetTokenInfo.mjs
342 lines (276 loc) · 8.14 KB
/
getTokenInfo.mjs
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
import fetch from 'cross-fetch';
let swapLineBreak = false;
let verbose = false;
let testnet = false;
let serialsCheck = false;
let imgOnly = false;
let scrapeOutput = false;
// global variable
const ipfsGateways = ['https://cloudflare-ipfs.com/ipfs/', 'https://ipfs.eternum.io/ipfs/', 'https://ipfs.io/ipfs/', 'https://ipfs.eth.aragon.network/ipfs/'];
const maxRetries = 5;
async function fetchJson(url, depth = 0, retries = maxRetries) {
if (depth >= retries) return null;
depth++;
try {
const res = await fetchWithTimeout(url);
if (res.status != 200) {
await sleep(500 * depth);
return await fetchJson(url, depth);
}
return res.json();
}
catch (err) {
await sleep(500 * depth);
return await fetchJson(url, depth);
}
}
/**
*
* @param {string} ipfsUrl
* @param {number=} depth
* @param {number=} seed
* @returns {*}
*/
async function fetchIPFSJson(ipfsUrl, depth = 0, seed = 0) {
if (depth >= maxRetries) return null;
if (depth > 0 && verbose) console.log('Attempt: ', depth + 1);
depth++;
const url = ipfsUrl.toLowerCase().startsWith('http') ? ipfsUrl : `${ipfsGateways[seed % ipfsGateways.length]}${ipfsUrl}`;
if (verbose) {console.log('Fetch: ', url, depth);}
seed += 1;
try {
const res = await fetch(url);
if (res.status != 200) {
await sleep(12 * depth * seed % 100);
return await fetchIPFSJson(ipfsUrl, depth, seed);
}
return res.json();
}
catch (err) {
console.error('Caught error when accessing', depth, url, err);
await sleep(12 * depth * seed % 100);
return await fetchIPFSJson(ipfsUrl, depth, seed);
}
}
async function getTokenInfo(tokenId, serialsList) {
let url;
if (testnet) {
url = `https://testnet.mirrornode.hedera.com/api/v1/tokens/${tokenId}`;
}
else {
url = `https://mainnet-public.mirrornode.hedera.com/api/v1/tokens/${tokenId}`;
}
if (verbose) { console.log(url); }
const token = await fetchJson(url, 0, 2);
if (token == null) {
console.log(`Error looking up ID: ${tokenId}`);
return null;
}
// console.log(Inspect.properties(u));
const customFees = token.custom_fees;
// console.log(customFees);
let royaltiesStr = '';
if (customFees.royalty_fees !== undefined) {
// console.log(customFees);
const royalties = customFees.royalty_fees;
royalties.forEach((item) => {
const numerator = item.amount.numerator;
const denom = item.amount.denominator || 0;
let fallbackAmt;
try {
fallbackAmt = item.fallback_fee.amount / 100000000;
}
catch (error) {
fallbackAmt = 'N/A';
}
let percentage;
if (denom == 0) {
percentage = 'N/A';
}
else {
percentage = `${numerator / denom * 100}%`;
}
royaltiesStr += ` amount ${percentage}, fallback ${fallbackAmt}, paid to ${item.collector_account_id || 'N/A'}`;
});
}
else {
royaltiesStr = 'NONE';
}
if (verbose) console.log(royaltiesStr);
const tS = token.total_supply;
const mS = token.max_supply;
const type = token.type;
let symbol = token.symbol;
const name = token.name;
const decimals = token.decimals;
const tsryAcc = token.treasury_account_id;
const deleted = token.deleted;
const pause = token.pause_status;
const supply_type = token.supply_type;
// check if metadata in the symbol
if (symbol.includes('IPFS')) {
symbol = await getMetadata(symbol);
}
console.log(url);
console.log(`token: ${tokenId}, total supply: ${tS}`);
console.log(`name: ${name}, decimal: ${decimals}`);
console.log(`symbol: ${symbol}`);
console.log(`tsry: ${tsryAcc}, max supply: ${mS}`);
console.log(`type: ${type}, supply type: ${supply_type}`);
console.log(`deleted: ${deleted}, pause: ${pause}`);
console.log(royaltiesStr);
if (serialsCheck) {
for (let c = 0; c < serialsList.length; c++) {
const result = await getNFTSerialMetadata(`${url}/nfts/${serialsList[c]}`, serialsList[c]);
console.log(`Serial #${serialsList[c]}`, result);
}
}
}
async function getNFTSerialMetadata(url) {
if (verbose) { console.log(url); }
const u = await fetchJson(url);
const metadataString = atob(u.metadata);
if (verbose) { console.log('translated metadata string: ', metadataString); }
const ipfsRegEx = /ipfs:?\/\/?(.+)/i;
let ipfsString;
try {
ipfsString = metadataString.match(ipfsRegEx)[1];
}
catch (_err) {
// likely string did not have IPFS in it...default use the whole string
ipfsString = metadataString;
}
if (verbose) { console.log('regexed metadata string: ', ipfsString); }
const metadataJSON = await fetchIPFSJson(ipfsString, 0, randomNumber(0, ipfsGateways.length));
const name = metadataJSON.name;
let desc = metadataJSON.description;
let img = metadataJSON.image;
try {
if (verbose) console.log('IMG:', img);
if (img.description) {
img = img.description;
}
img = img.replace(/ipfs:\/\//gi, `${ipfsGateways[0]}`);
}
catch (err) {
console.log('error obtaining the image', img, err);
}
let attribs = '';
try {
metadataJSON.attributes.forEach((item) => {
attribs += `\n${item.trait_type} = ${item.value}`;
});
if (scrapeOutput) {
attribs += '\n=========';
metadataJSON.attributes.forEach((item) => {
attribs += `\nattribIndex.set('${item.trait_type.toLowerCase()}', ++attIdx);`;
});
}
}
catch {
// if no attributes
attribs = 'NONE';
}
if (swapLineBreak) {
desc = desc.replace(/ \/ /gi, '\n');
}
if (imgOnly) {
return ` - ${img}`;
}
else {
return `\nName: ${name}\nDESC: ${desc} \nCreator: ${metadataJSON.creator} Compiler: ${metadataJSON.compiler}\nIMG: ${img}\nAttribs: ${attribs}`;
}
}
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
async function getMetadata(path) {
const splitURI = path.split('/');
const ifpsString = splitURI[splitURI.length - 1];
const metadataJSON = await fetchIPFSJson(ifpsString, 0, randomNumber(0, ipfsGateways.length));
let desc = metadataJSON.description.description;
if (swapLineBreak) {
desc = desc.replace(/ \/ /gi, '\n');
}
return `\nDESC: ${desc} \nIMG: ${metadataJSON.image.description}`;
}
function getArg(arg) {
const customIndex = process.argv.indexOf(`-${arg}`);
let customValue;
if (customIndex > -1) {
// Retrieve the value after --custom
customValue = process.argv[customIndex + 1];
}
return customValue;
}
function getArgFlag(arg) {
const customIndex = process.argv.indexOf(`-${arg}`);
if (customIndex > -1) {
return true;
}
return false;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fetchWithTimeout(resource, options = {}) {
const { timeout = 5000 } = options;
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
const response = await fetch(resource, {
...options,
signal: controller.signal,
});
clearTimeout(id);
return response;
}
async function main() {
const help = getArgFlag('h');
if (help) {
console.log('Usage: node getTokenInfo.mjs -t <token> [-v] [-swap] [-testnet] [-s <serial>] [-img]');
console.log(' -t <token>');
console.log(' -s <serial>');
console.log(' -img gets images only');
console.log(' -swap swaps out line breaks in metadata found');
console.log(' -testnet');
console.log(' -v verbose [debug]');
return;
}
verbose = getArgFlag('v');
let tokenId = getArg('t');
if (tokenId === undefined) {
console.log('**MUST** specify token -> Usage: node getTokenInfo.mjs -h');
return;
}
swapLineBreak = getArgFlag('swap');
testnet = getArgFlag('testnet');
imgOnly = getArgFlag('img');
scrapeOutput = getArgFlag('scrape');
const serialsArg = getArg('s');
let serialsList = [];
if (serialsArg !== undefined) {
serialsCheck = true;
// format csv or '-' for range
if (serialsArg.includes('-')) {
// inclusive range
const rangeSplit = serialsArg.split('-');
for (let i = rangeSplit[0]; i <= rangeSplit[1]; i++) {
serialsList.push(`${i}`);
}
}
else if (serialsArg.includes(',')) {
serialsList = serialsArg.split(',');
}
else {
// only one serial to check
serialsList = [serialsArg];
}
}
const tokenList = [tokenId];
for (let i = 0; i < tokenList.length; i++) {
tokenId = tokenList[i];
if (verbose) {console.log(`processing token: ${tokenId}`);}
await getTokenInfo(tokenId, serialsList);
}
}
main();