forked from DefiLlama/DefiLlama-Adapters
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mcv2-tvl.js
591 lines (534 loc) · 16.7 KB
/
mcv2-tvl.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
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
#!/usr/bin/env node
const { ENV_KEYS } = require("./projects/helper/env.js");
const path = require("path");
require("dotenv").config();
const {
util: {
blocks: { getCurrentBlocks },
humanizeNumber: { humanizeNumber },
},
} = require("@defillama/sdk");
const { util } = require("@defillama/sdk");
const sdk = require("@defillama/sdk");
const whitelistedExportKeys = require("./projects/helper/whitelistedExportKeys.json");
const chainList = require("./projects/helper/chains.json");
const handleError = require("./utils/handleError.js");
const {
log,
diplayUnknownTable,
sliceIntoChunks,
} = require("./projects/helper/utils.js");
const { normalizeAddress } = require("./projects/helper/tokenMapping.js");
const { PromisePool } = require("@supercharge/promise-pool");
const { Webhook, MessageBuilder } = require("discord-webhook-node");
const hook = new Webhook(process.env.DISCORD_MINT_CLUB_TVL_WEBHOOK);
const currentCacheVersion = sdk.cache.currentVersion; // load env for cache
// console.log(`Using cache version ${currentCacheVersion}`)
if (process.env.LLAMA_SANITIZE)
Object.keys(process.env).forEach((key) => {
if (key.endsWith("_RPC")) return;
if (
["TVL_LOCAL_CACHE_ROOT_FOLDER", "LLAMA_DEBUG_MODE", ...ENV_KEYS].includes(
key
) ||
key.includes("SDK")
)
return;
delete process.env[key];
});
const locks = [];
function getCoingeckoLock() {
return new Promise((resolve) => {
locks.push(resolve);
});
}
function releaseCoingeckoLock() {
const firstLock = locks.shift();
if (firstLock !== undefined) {
firstLock(null);
}
}
// Rate limit is 50 calls/min for coingecko's API
// So we'll release one every 1.2 seconds to match it
setInterval(() => {
releaseCoingeckoLock();
}, 2000);
const maxCoingeckoRetries = 5;
async function getTvl(
unixTimestamp,
ethBlock,
chainBlocks,
usdTvls,
tokensBalances,
usdTokenBalances,
tvlFunction,
isFetchFunction,
storedKey,
knownTokenPrices
) {
if (!isFetchFunction) {
const chain = storedKey.split("-")[0];
const block = chainBlocks[chain];
const api = new sdk.ChainApi({
chain,
block: chainBlocks[chain],
timestamp: unixTimestamp,
});
let tvlBalances = await tvlFunction(unixTimestamp, ethBlock, chainBlocks, {
api,
chain,
block,
storedKey,
});
if (!tvlBalances && Object.keys(api.getBalances()).length)
tvlBalances = api.getBalances();
const tvlResults = await computeTVL(
tvlBalances,
"now",
false,
knownTokenPrices,
getCoingeckoLock,
maxCoingeckoRetries
);
await diplayUnknownTable({ tvlResults, storedKey, tvlBalances });
usdTvls[storedKey] = tvlResults.usdTvl;
tokensBalances[storedKey] = tvlResults.tokenBalances;
usdTokenBalances[storedKey] = tvlResults.usdTokenBalances;
} else {
usdTvls[storedKey] = Number(
await tvlFunction(unixTimestamp, ethBlock, chainBlocks)
);
}
if (
typeof usdTvls[storedKey] !== "number" ||
Number.isNaN(usdTvls[storedKey])
) {
throw new Error(
`TVL for key ${storedKey} is not a number, instead it is ${usdTvls[storedKey]}`
);
}
}
function mergeBalances(key, storedKeys, balancesObject) {
if (balancesObject[key] === undefined) {
balancesObject[key] = {};
storedKeys.map((keyToMerge) => {
Object.entries(balancesObject[keyToMerge]).forEach((balance) => {
try {
util.sumSingleBalance(
balancesObject[key],
balance[0],
BigNumber(balance[1] || "0").toFixed(0)
);
} catch (e) {
console.log(e);
}
});
});
}
}
const originalCall = sdk.api.abi.call;
sdk.api.abi.call = async (...args) => {
try {
return await originalCall(...args);
} catch (e) {
console.log("sdk.api.abi.call errored with params:", args);
throw e;
}
};
(async () => {
const module = require("./projects/mint-club-v2/index.js");
const chains = Object.keys(module).filter(
(item) => typeof module[item] === "object" && !Array.isArray(module[item])
);
const unixTimestamp = Math.round(Date.now() / 1000) - 60;
const { chainBlocks } = await getCurrentBlocks([]); // fetch only ethereum block for local test
const ethBlock = chainBlocks.ethereum;
const usdTvls = {};
const tokensBalances = {};
const usdTokenBalances = {};
const chainTvlsToAdd = {};
const knownTokenPrices = {};
let tvlPromises = Object.entries(module).map(async ([chain, value]) => {
if (typeof value !== "object" || value === null) {
return;
}
return Promise.all(
Object.entries(value).map(async ([tvlType, tvlFunction]) => {
if (typeof tvlFunction !== "function") {
return;
}
let storedKey = `${chain}-${tvlType}`;
let tvlFunctionIsFetch = false;
if (tvlType === "tvl") {
storedKey = chain;
} else if (tvlType === "fetch") {
storedKey = chain;
tvlFunctionIsFetch = true;
}
await getTvl(
unixTimestamp,
ethBlock,
chainBlocks,
usdTvls,
tokensBalances,
usdTokenBalances,
tvlFunction,
tvlFunctionIsFetch,
storedKey,
knownTokenPrices
);
let keyToAddChainBalances = tvlType;
if (tvlType === "tvl" || tvlType === "fetch") {
keyToAddChainBalances = "tvl";
}
if (chainTvlsToAdd[keyToAddChainBalances] === undefined) {
chainTvlsToAdd[keyToAddChainBalances] = [storedKey];
} else {
chainTvlsToAdd[keyToAddChainBalances].push(storedKey);
}
})
);
});
if (module.tvl || module.fetch) {
let mainTvlIsFetch;
if (module.tvl) {
mainTvlIsFetch = false;
} else {
mainTvlIsFetch = true;
}
const mainTvlPromise = getTvl(
unixTimestamp,
ethBlock,
chainBlocks,
usdTvls,
tokensBalances,
usdTokenBalances,
mainTvlIsFetch ? module.fetch : module.tvl,
mainTvlIsFetch,
"tvl",
knownTokenPrices
);
tvlPromises.push(mainTvlPromise);
}
await Promise.all(tvlPromises);
Object.entries(chainTvlsToAdd).map(([tvlType, storedKeys]) => {
if (usdTvls[tvlType] === undefined) {
usdTvls[tvlType] = storedKeys.reduce(
(total, key) => total + usdTvls[key],
0
);
mergeBalances(tvlType, storedKeys, tokensBalances);
mergeBalances(tvlType, storedKeys, usdTokenBalances);
}
});
if (usdTvls.tvl === undefined) {
throw new Error(
"Protocol doesn't have total tvl, make sure to export a tvl key either on the main object or in one of the chains"
);
}
const embed = new MessageBuilder()
.setAuthor(
"Mint Club TVL Stats",
"https://mint.club/android-chrome-192x192.png",
"https://mint.club"
)
.setColor("#15E6B7")
.setURL("https://mint.club")
.setTimestamp();
const icons = {
ethereum: "<:eth:1080344679318560809>",
optimism: "<:op:1153261590586593331>",
arbitrum: "<:arb:1153261598555770941>",
avax: "<:avax:1202572161018101800>",
polygon: "<:polygon:1153261595556859924>",
bsc: "<:bsc:1154689724586397776>",
base: "<:base:1153261592427896832>",
};
const description = `
Fetched <t:${Math.floor(Date.now() / 1000)}:R>
\`\`\`
_ _
_ __ ___ (_)_ __ | |_
| '_ \` _ \\| | '_ \\| __|
| | | | | | | | | | |_
|_| |_| |_|_|_| |_|\\__|
(_)__| |_ _| |__
/ __| | | | | '_ \\
| (__| | |_| | |_) |
\\___|_|\\__,_|_.__/
Made with ❤️ by @0xggoma
\`\`\`
`;
embed.setDescription(description);
const tokens = [];
const networks = [];
const obj = {
tvl: "\n",
chainIcon: "\n",
symbol: "\n",
networkTvl: "\n",
networkIcon: "\n",
network: "\n",
};
Object.entries(usdTokenBalances).forEach(([chain, balances]) => {
if (chain !== "tvl") {
Object.entries(balances).forEach(([symbol, balance]) => {
tokens.push([chain, symbol, balance]);
});
// embed.addField(
// `${icons[chain]} ${chain[0].toUpperCase() + chain.slice(1)}`,
// `**$${humanizeNumber(usdTvls[chain])}**`,
// true
// );
networks.push([chain, usdTvls[chain]]);
}
});
tokens
.sort((a, b) => b[2] - a[2])
.forEach(([chain, symbol, balance]) => {
obj.symbol += `\n${icons[chain]} ${symbol} | $${humanizeNumber(balance)}`;
// obj.tvl += `\n$${humanizeNumber(balance)}`;
});
networks
.sort((a, b) => b[1] - a[1])
.forEach(([chain, balance]) => {
obj.network += `\n${icons[chain]} ${
chain[0].toUpperCase() + chain.slice(1)
} | $${humanizeNumber(usdTvls[chain])}`;
// obj.networkTvl += `\n$${humanizeNumber(usdTvls[chain])}`;
});
embed.setTitle("Total TVL $" + humanizeNumber(usdTvls.tvl));
embed.addField("Bonded Asset | TVL", obj.symbol, true);
// embed.addField("TVL", obj.tvl, true);
// embed.addField("\u200b", "\u200b", true);
embed.addField("\u200b", "\u200b");
embed.addField("Network | TVL", obj.network, true);
// embed.addField("TVL", obj.networkTvl, true);
// embed.addField("\u200b", "\u200b", true);
Object.entries(usdTokenBalances).forEach(([chain, balances]) => {
console.log(`--- ${chain} ---`);
Object.entries(balances)
.sort((a, b) => b[1] - a[1])
.forEach(([symbol, balance]) => {
console.log(symbol.padEnd(25, " "), humanizeNumber(balance));
});
console.log("Total:", humanizeNumber(usdTvls[chain]), "\n");
});
console.log(`------ TVL ------`);
Object.entries(usdTvls).forEach(([chain, usdTvl]) => {
if (chain !== "tvl") {
console.log(chain.padEnd(25, " "), humanizeNumber(usdTvl));
}
});
console.log("\ntotal".padEnd(25, " "), humanizeNumber(usdTvls.tvl), "\n");
// embed.setDescription(description);
console.log(description);
await hook.send(embed);
process.exit(0);
})();
function checkExportKeys(module, filePath, chains) {
filePath = filePath.split(path.sep);
filePath = filePath.slice(filePath.lastIndexOf("projects") + 1);
if (
filePath.length > 2 ||
(filePath.length === 1 &&
![".js", ""].includes(path.extname(filePath[0]))) || // matches .../projects/projectXYZ.js or .../projects/projectXYZ
(filePath.length === 2 &&
!(
(
["api.js", "index.js", "apiCache.js"].includes(filePath[1]) || // matches .../projects/projectXYZ/index.js
["treasury", "entities"].includes(filePath[0])
) // matches .../projects/treasury/project.js
))
)
process.exit(0);
const blacklistedRootExportKeys = [
"tvl",
"staking",
"pool2",
"borrowed",
"treasury",
"offers",
"vesting",
];
const rootexportKeys = Object.keys(module).filter(
(item) => typeof module[item] !== "object"
);
const unknownChains = chains.filter((chain) => !chainList.includes(chain));
const blacklistedKeysFound = rootexportKeys.filter((key) =>
blacklistedRootExportKeys.includes(key)
);
let exportKeys = chains.map((chain) => Object.keys(module[chain])).flat();
exportKeys.push(...rootexportKeys);
exportKeys = Object.keys(
exportKeys.reduce((agg, key) => ({ ...agg, [key]: 1 }), {})
); // get unique keys
const unknownKeys = exportKeys.filter(
(key) => !whitelistedExportKeys.includes(key)
);
const hallmarks = module.hallmarks || [];
if (hallmarks.length) {
const TIMESTAMP_LENGTH = 10;
hallmarks.forEach(([timestamp, text]) => {
const strTimestamp = String(timestamp);
if (strTimestamp.length !== TIMESTAMP_LENGTH) {
throw new Error(`
Incorrect time format for the hallmark: [${strTimestamp}, ${text}] ,please use unix timestamp
`);
}
});
}
if (unknownChains.length) {
throw new Error(`
Unknown chain(s): ${unknownChains.join(", ")}
Note: if you think that the chain is correct but missing from our list, please add it to 'projects/helper/chains.json' file
`);
}
if (blacklistedKeysFound.length) {
throw new Error(`
Please move the following keys into the chain: ${blacklistedKeysFound.join(
", "
)}
We have a new adapter export specification now where tvl and other chain specific information are moved inside chain export.
For example if your protocol is on ethereum and has tvl and pool2, the export file would look like:
module.exports = {
methodlogy: '...',
ethereum: {
tvl:
pool2:
}
}
`);
}
if (unknownKeys.length) {
throw new Error(`
Found export keys that were not part of specification: ${unknownKeys.join(
", "
)}
List of valid keys: ${["", "", ...whitelistedExportKeys].join("\n\t\t\t\t")}
`);
}
}
process.on("unhandledRejection", handleError);
process.on("uncaughtException", handleError);
const BigNumber = require("bignumber.js");
const axios = require("axios");
const ethereumAddress = "0x0000000000000000000000000000000000000000";
const weth = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2";
function fixBalances(balances) {
Object.entries(balances).forEach(([token, value]) => {
let newKey;
if (token.startsWith("0x")) newKey = `ethereum:${token}`;
else if (!token.includes(":")) newKey = `coingecko:${token}`;
if (newKey) {
delete balances[token];
sdk.util.sumSingleBalance(balances, newKey, BigNumber(value).toFixed(0));
}
});
}
const confidenceThreshold = 0.5;
async function computeTVL(balances, timestamp) {
fixBalances(balances);
Object.keys(balances).map((k) => {
const balance = balances[k];
delete balances[k];
if (+balance === 0) return;
const normalizedAddress = normalizeAddress(k, undefined, true);
sdk.util.sumSingleBalance(balances, normalizedAddress, balance);
});
const eth = balances[ethereumAddress];
if (eth !== undefined) {
balances[weth] = new BigNumber(balances[weth] ?? 0).plus(eth).toFixed(0);
delete balances[ethereumAddress];
}
const PKsToTokens = {};
const readKeys = Object.keys(balances)
.map((address) => {
const PK = address;
if (PKsToTokens[PK] === undefined) {
PKsToTokens[PK] = [address];
return PK;
} else {
PKsToTokens[PK].push(address);
return undefined;
}
})
.filter((item) => item !== undefined);
const unknownTokens = {};
let tokenData = [];
readKeys.forEach((i) => (unknownTokens[i] = true));
const { errors } = await PromisePool.withConcurrency(5)
.for(sliceIntoChunks(readKeys, 100))
.process(async (keys) => {
tokenData.push(
(
await axios.get(
`https://coins.llama.fi/prices/current/${keys.join(",")}`
)
).data.coins
);
});
if (errors && errors.length) throw errors[0];
let usdTvl = 0;
const tokenBalances = {};
const usdTokenBalances = {};
tokenData.forEach((response) => {
Object.keys(response).forEach((address) => {
delete unknownTokens[address];
const data = response[address];
const balance = balances[address];
if (data == undefined) tokenBalances[`UNKNOWN (${address})`] = balance;
if (
("confidence" in data && data.confidence < confidenceThreshold) ||
!data.price
)
return;
if (Math.abs(data.timestamp - Date.now() / 1e3) > 24 * 3600) {
console.log(`Price for ${address} is stale, ignoring...`);
return;
}
let amount, usdAmount;
if (address.includes(":") && !address.startsWith("coingecko:")) {
amount = new BigNumber(balance).div(10 ** data.decimals).toNumber();
usdAmount = amount * data.price;
} else {
amount = Number(balance);
usdAmount = amount * data.price;
}
if (usdAmount > 1e8) {
console.log(`-------------------
Warning: `);
console.log(
`Token ${address} has more than 100M in value (${
usdAmount / 1e6
} M) , price data: `,
data
);
console.log(`-------------------`);
}
tokenBalances[data.symbol] = (tokenBalances[data.symbol] ?? 0) + amount;
usdTokenBalances[data.symbol] =
(usdTokenBalances[data.symbol] ?? 0) + usdAmount;
usdTvl += usdAmount;
if (isNaN(usdTvl)) {
throw new Error(
`NaN usdTvl for ${address} with balance ${balance} and price ${data.price}`
);
}
});
});
Object.keys(unknownTokens).forEach(
(address) => (tokenBalances[`UNKNOWN (${address})`] = balances[address])
);
// console.log('--------token balances-------')
// console.table(tokenBalances)
return {
usdTvl,
tokenBalances,
usdTokenBalances,
};
}
setTimeout(() => {
console.log("Timeout reached, exiting...");
if (!process.env.NO_EXIT_ON_LONG_RUN_RPC) process.exit(1);
}, 10 * 60 * 1000); // 10 minutes