-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
239 lines (205 loc) · 7.31 KB
/
index.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
// Calculate rarity scores and ranks for GOGOs using TZKT on Tezos Blockchain
//
// Created by PRIME Dev & Kevin Elliott
//
// Github: https://github.com/veDEMIRP/gogos-rankings
// Twitter: https://twitter.com/DosEsposas
// Twitter: https://twitter.com/kevinelliott
import { bytes2Char } from '@taquito/utils';
import axios from 'axios';
import fs from 'fs';
// SETTINGS
const IPFS_BASE_URL = 'https://cloudflare-ipfs.com/ipfs';
const TZKT_BASE_URL = 'https://api.tzkt.io/v1';
const GOGOS_TOKEN_CONTRACT = 'KT1SyPgtiXTaEfBuMZKviWGNHqVrBBEjvtfQ';
const GOGOS_TZKT_URL = `${TZKT_BASE_URL}/contracts/${GOGOS_TOKEN_CONTRACT}/bigmaps/token_metadata/keys?active=true&select=value&limit=10000`;
const COLLECTION_TOTAL = 5555;
const DEBUG = false;
// INITIALIZATIONS
let tokens = {};
let attributeNames = [];
let attributeValues = {};
let attributeCounts = {};
let attributeRarityScores = {};
let attributeRarityPercentages = {};
let tokensSortedById = [];
let tokensSortedByRank = [];
// FUNCTIONS
async function getGogosIPFSList() {
console.log('Getting token info for all GOGOs from TZKT');
const response = await axios.get(GOGOS_TZKT_URL);
const tokens = response.data;
console.log(`Discovered ${tokens.length} GOGOs`);
const list = [];
for (const token of tokens) {
const tokenId = token.token_id;
const ipfsUri = bytes2Char(token.token_info['']);
list.push({ tokenId: tokenId, ipfsUri: ipfsUri });
}
return list;
}
async function getTokenMetadataFromIPFS(ipfsUri) {
const ipfsUrl = ipfsUri.replace('ipfs://', IPFS_BASE_URL + '/');
const response = await axios.get(ipfsUrl);
return response.data;
}
async function cacheData(data, filename) {
if (fs.existsSync(filename)) {
console.log(`Skipping. Cached token metadata exists already at ${filename}`);
} else {
const json = JSON.stringify(data);
fs.writeFileSync(filename, json);
}
}
const sleep = (ms) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
async function loadCacheOrGetTokenMetadataFromIPFS(item) {
const filename = `ipfs_cache/gogo_${item.tokenId}.json`;
let tokenMetadata;
if (fs.existsSync(filename)) {
tokenMetadata = JSON.parse(fs.readFileSync(filename));
console.log(`Loading token metadata from cache for Token ID ${item.tokenId}`);
if (tokenMetadata.attributes.length == 1 && tokenMetadata.attributes[0].name == 'Vital Signs' && tokenMetadata.attributes[0].value == 'Normal') {
console.log(`Cache contains stale data from pre-hatch for Token ID ${item.tokenId}.`);
console.log(tokenMetadata.attributes);
fs.unlinkSync(filename);
await sleep(1000);
console.log(`Refetching token metadata from IPFS for Token ID ${item.tokenId}`);
tokenMetadata = await getTokenMetadataFromIPFS(item.ipfsUri);
console.log(tokenMetadata.attributes);
await cacheData(tokenMetadata, filename);
}
} else {
console.log(`Retrieving token metadata from IPFS for Token ID ${item.tokenId}`);
tokenMetadata = await getTokenMetadataFromIPFS(item.ipfsUri);
await cacheData(tokenMetadata, filename);
}
return tokenMetadata;
}
function incrementAttribute(attribute) {
if (attributeNames.indexOf(`${attribute.name}`) < 0) {
attributeNames.push(`${attribute.name}`);
}
if (!!!attributeValues[`${attribute.name}`]) {
attributeValues[`${attribute.name}`] = [];
}
if (attributeValues[`${attribute.name}`].indexOf(`${attribute.value}`) < 0) {
attributeValues[`${attribute.name}`].push(`${attribute.value}`);
}
if (!!!attributeCounts[`${attribute.name}`]) {
attributeCounts[`${attribute.name}`] = {};
}
if (!!!attributeCounts[`${attribute.name}`][`${attribute.value}`]) {
attributeCounts[`${attribute.name}`][`${attribute.value}`] = 0;
}
attributeCounts[`${attribute.name}`][`${attribute.value}`] = attributeCounts[`${attribute.name}`][`${attribute.value}`] + 1;
}
function calculateAttributeRarityScores(totals) {
for (const name of attributeNames) {
for (const value of attributeValues[`${name}`]) {
const itemsWithTraitCount = attributeCounts[`${name}`][`${value}`];
attributeRarityScores[`${name} - ${value}`] = 1 / (itemsWithTraitCount / COLLECTION_TOTAL);
}
}
}
function calculateAttributeRarityPercentages(totals) {
for (const name of attributeNames) {
for (const value of attributeValues[`${name}`]) {
const itemsWithTraitCount = attributeCounts[`${name}`][`${value}`];
attributeRarityPercentages[`${name} - ${value}`] = itemsWithTraitCount / COLLECTION_TOTAL;
}
}
}
function calculateTokenRarityScores() {
tokens = Object.values(tokens).map((token) => {
let rarityScore = 0;
for (const attr of token.attributes) {
rarityScore += attributeRarityScores[`${attr.name} - ${attr.value}`];
}
token.rarityScore = rarityScore;
return token;
});
}
function sortTokensById() {
tokensSortedById = Object.keys(tokens).map((key) => {
const token = tokens[key];
return token;
});
tokensSortedById = tokensSortedById.sort((a, b) => a.id - b.id);
}
function sortTokensByRank() {
tokensSortedByRank = Object.keys(tokens).map((key) => {
const token = tokens[key];
return token;
});
tokensSortedByRank = tokensSortedByRank.sort((a, b) => b.rarityScore - a.rarityScore);
}
function exportTokenRanksToCsv() {
const filename = 'gogos-by-rank.csv';
const csvLines = ['rank,id,score'];
for (const [i, token] of tokensSortedByRank.entries()) {
csvLines.push(`${i+1},${String(token.id).padStart(4, '0')},${token.rarityScore}`);
}
fs.writeFileSync(filename, csvLines.join('\n'));
}
function exportTokensToCsv() {
const filename = 'gogos-by-id.csv';
const csvLines = ['id,rank,score'];
for (const [i, token] of tokensSortedByRank.entries()) {
csvLines.push(`${String(token.id).padStart(4, '0')},${i+1},${token.rarityScore}`);
}
fs.writeFileSync(filename, csvLines.join('\n'));
}
// MAIN
const ipfsList = await getGogosIPFSList();
const items = [];
let ids = ipfsList.map(i => parseInt(i.tokenId));
ids = ids.sort((a, b) => a - b);
for (const id of ids) {
const item = ipfsList.find(i => i.tokenId == id);
const tokenMetadata = await loadCacheOrGetTokenMetadataFromIPFS(item);
// console.log(tokenMetadata);
const attributes = [];
for (const attr of tokenMetadata.attributes) {
const attribute = {
name: attr.name,
value: attr.value
};
attributes.push(attribute);
incrementAttribute(attribute);
}
const rankingDetail = {
id: item.tokenId,
rank: 0,
score: 0,
name: tokenMetadata.name,
displayUri: tokenMetadata.displayUri,
attributes: attributes
};
tokens[`${item.tokenId}`] = rankingDetail;
}
// CALCULATIONS
calculateAttributeRarityScores();
calculateAttributeRarityPercentages();
calculateTokenRarityScores();
sortTokensById();
sortTokensByRank();
// SUMMARY DEBUG OUTPUT
if (DEBUG) {
console.log('');
console.log('Attribute Counts');
console.log(JSON.stringify(attributeCounts));
console.log('');
console.log('Attribute Rarity Scores');
console.log(JSON.stringify(attributeRarityScores));
console.log('');
console.log('Attribute Rarity Percentages');
console.log(JSON.stringify(attributeRarityPercentages));
console.log('Tokens (By rarity scores)');
console.log(JSON.stringify(tokens));
console.log('Token (By rank)');
console.log(JSON.stringify(tokensSortedByRank));
}
exportTokensToCsv();
exportTokenRanksToCsv();