@defillama/sdk 2.3.126 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,375 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (_) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- var __importDefault = (this && this.__importDefault) || function (mod) {
39
- return (mod && mod.__esModule) ? mod : { "default": mod };
40
- };
41
- Object.defineProperty(exports, "__esModule", { value: true });
42
- exports.chainToCoingeckoId = void 0;
43
- var abi_1 = require("../abi");
44
- var humanizeNumber_1 = require("./humanizeNumber");
45
- var prices_1 = require("./prices");
46
- var node_fetch_1 = __importDefault(require("node-fetch"));
47
- var generalUtil_1 = require("../generalUtil");
48
- var index_1 = require("./../util/index");
49
- function tokenMulticall(addresses, abi, chain) {
50
- return abi_1.multiCall({
51
- abi: abi,
52
- calls: addresses.map(function (address) { return ({
53
- target: address,
54
- params: [],
55
- }); }),
56
- chain: chain,
57
- });
58
- }
59
- function addTokenBalance(balances, symbol, amount) {
60
- balances[symbol] = (balances[symbol] || 0) + amount;
61
- }
62
- function historicalCoingeckoUrls(chain) {
63
- if (chain === 'coingecko') {
64
- return "https://api.coingecko.com/api/v3/coins";
65
- }
66
- var platformId = exports.chainToCoingeckoId[chain];
67
- if (platformId !== undefined) {
68
- return "https://api.coingecko.com/api/v3/coins/" + platformId + "/contract";
69
- }
70
- throw new Error("Chain not supported");
71
- }
72
- exports.chainToCoingeckoId = {
73
- bsc: "binance-smart-chain",
74
- ethereum: "ethereum",
75
- polygon: "polygon-pos",
76
- avax: "avalanche",
77
- fantom: "fantom",
78
- xdai: "xdai",
79
- heco: "huobi-token",
80
- okexchain: "okex-chain",
81
- harmony: "harmony-shard-0",
82
- kcc: "kucoin-community-chain",
83
- celo: "celo",
84
- arbitrum: "arbitrum-one",
85
- iotex: "iotex",
86
- moonriver: "moonriver",
87
- solana: "solana",
88
- terra: "terra",
89
- tron: "tron",
90
- waves: "waves",
91
- klaytn: "klay-token",
92
- osmosis: "osmosis",
93
- kava: "kava",
94
- icon: "icon",
95
- optimism: "optimistic-ethereum",
96
- eos: "eos",
97
- secret: "secret",
98
- rsk: "rootstock",
99
- neo: "neo",
100
- tezos: "tezos",
101
- wan: "wanchain",
102
- ontology: "ontology",
103
- algorand: "algorand",
104
- zilliqa: "zilliqa",
105
- kardia: "kardiachain",
106
- cronos: "cronos",
107
- aurora: "aurora",
108
- boba: "boba",
109
- metis: "metis-andromeda",
110
- telos: "telos",
111
- moonbeam: "moonbeam",
112
- meter: "meter",
113
- sx: "sx-network",
114
- velas: "velas",
115
- milkomeda: "milkomeda-cardano",
116
- };
117
- var chains = Object.keys(exports.chainToCoingeckoId);
118
- function getHistoricalChainPrices(ids, timestamp, knownTokenPrices, getCoingeckoLock, coingeckoMaxRetries) {
119
- return __awaiter(this, void 0, void 0, function () {
120
- var chainPrices, _i, _a, chain, _b, _c;
121
- return __generator(this, function (_d) {
122
- switch (_d.label) {
123
- case 0:
124
- chainPrices = {};
125
- _i = 0, _a = chains.concat(["coingecko"]);
126
- _d.label = 1;
127
- case 1:
128
- if (!(_i < _a.length)) return [3 /*break*/, 5];
129
- chain = _a[_i];
130
- if (!(ids[chain].length === 0)) return [3 /*break*/, 2];
131
- chainPrices[chain] = {};
132
- return [3 /*break*/, 4];
133
- case 2:
134
- _b = chainPrices;
135
- _c = chain;
136
- return [4 /*yield*/, prices_1.getHistoricalTokenPrices(ids[chain], historicalCoingeckoUrls(chain), timestamp, getCoingeckoLock, coingeckoMaxRetries)];
137
- case 3:
138
- _b[_c] = _d.sent();
139
- _d.label = 4;
140
- case 4:
141
- _i++;
142
- return [3 /*break*/, 1];
143
- case 5: return [2 /*return*/, chainPrices];
144
- }
145
- });
146
- });
147
- }
148
- function getChainSymbolsAndDecimals(ids, maxRetries) {
149
- return __awaiter(this, void 0, void 0, function () {
150
- var allCoins, i, response;
151
- return __generator(this, function (_a) {
152
- switch (_a.label) {
153
- case 0:
154
- allCoins = Object.entries(ids).map(function (chain) {
155
- return chain[1].map(function (coin) { return chain[0] === "coingecko" ? coin.toLowerCase() : chain[0] + ":" + coin.toLowerCase(); });
156
- })
157
- .reduce(function (acc, coins) {
158
- coins.forEach(function (coin) {
159
- acc.add(coin);
160
- });
161
- return acc;
162
- }, new Set([]));
163
- i = 0;
164
- _a.label = 1;
165
- case 1:
166
- if (!(i < maxRetries)) return [3 /*break*/, 4];
167
- return [4 /*yield*/, node_fetch_1.default('https://api.llama.fi/coins', {
168
- method: 'POST',
169
- body: JSON.stringify({
170
- coins: Array.from(allCoins)
171
- })
172
- }).then(function (response) { return response.json(); })];
173
- case 2:
174
- response = _a.sent();
175
- if (Array.isArray(response)) {
176
- return [2 /*return*/, response];
177
- }
178
- _a.label = 3;
179
- case 3:
180
- i++;
181
- return [3 /*break*/, 1];
182
- case 4: throw new Error("api.llama.fi/coins failed");
183
- }
184
- });
185
- });
186
- }
187
- function default_1(rawBalances, timestamp, verbose, knownTokenPrices, getCoingeckoLock, coingeckoMaxRetries) {
188
- if (verbose === void 0) { verbose = false; }
189
- if (knownTokenPrices === void 0) { knownTokenPrices = {}; }
190
- if (getCoingeckoLock === void 0) { getCoingeckoLock = function () { return Promise.resolve(); }; }
191
- if (coingeckoMaxRetries === void 0) { coingeckoMaxRetries = 3; }
192
- return __awaiter(this, void 0, void 0, function () {
193
- var balances, callTokenDecimals_1, chainIds, _i, chains_1, chain, normalizedBalances, _a, _b, tokenAddressOrName, normalizedAddressOrName, normalizedBalance, chain, symbolsAndDecimals, allChainTokenPrices, usdTokenBalances, tokenBalances, rawTokenBalances, usdAmounts, usdTvl;
194
- var _this = this;
195
- return __generator(this, function (_c) {
196
- switch (_c.label) {
197
- case 0:
198
- if (!(rawBalances instanceof Array)) return [3 /*break*/, 2];
199
- return [4 /*yield*/, abi_1.multiCall({
200
- abi: "erc20:decimals",
201
- calls: rawBalances.map(function (token) { return ({
202
- target: token.address,
203
- params: [],
204
- }); }),
205
- })];
206
- case 1:
207
- callTokenDecimals_1 = (_c.sent()).output;
208
- balances = rawBalances.reduce(function (acc, token, index) {
209
- var dec;
210
- if (callTokenDecimals_1[index].success) {
211
- dec = Number(callTokenDecimals_1[index].output);
212
- }
213
- else {
214
- if (token.address === "0x0000000000000000000000000000000000000000") {
215
- dec = 18;
216
- }
217
- else {
218
- dec = NaN;
219
- }
220
- }
221
- acc[token.address] = (Number(token.balance) * Math.pow(10, dec)).toString();
222
- return acc;
223
- }, {});
224
- return [3 /*break*/, 3];
225
- case 2:
226
- balances = rawBalances;
227
- _c.label = 3;
228
- case 3:
229
- chainIds = {
230
- coingecko: [],
231
- };
232
- for (_i = 0, chains_1 = chains; _i < chains_1.length; _i++) {
233
- chain = chains_1[_i];
234
- chainIds[chain] = [];
235
- }
236
- normalizedBalances = {};
237
- for (_a = 0, _b = Object.keys(balances); _a < _b.length; _a++) {
238
- tokenAddressOrName = _b[_a];
239
- normalizedAddressOrName = tokenAddressOrName;
240
- normalizedBalance = balances[tokenAddressOrName];
241
- if (tokenAddressOrName === "0x0000000000000000000000000000000000000000") {
242
- normalizedAddressOrName = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"; // Normalize ETH to WETH
243
- }
244
- if (typeof normalizedBalance === "object") {
245
- normalizedBalances[normalizedAddressOrName] = normalizedBalance.toFixed(); // Some adapters return a BigNumber from bignumber.js so the results must be normalized
246
- }
247
- else {
248
- generalUtil_1.sumSingleBalance(normalizedBalances, normalizedAddressOrName, normalizedBalance);
249
- }
250
- if (normalizedAddressOrName.startsWith("0x")) {
251
- chainIds.ethereum.push(normalizedAddressOrName);
252
- }
253
- else if (normalizedAddressOrName.includes(":")) {
254
- chain = normalizedAddressOrName.split(':')[0];
255
- chainIds[chain].push(normalizedAddressOrName.slice(chain.length + 1));
256
- }
257
- else {
258
- chainIds.coingecko.push(normalizedAddressOrName);
259
- }
260
- }
261
- return [4 /*yield*/, getChainSymbolsAndDecimals(chainIds, coingeckoMaxRetries)];
262
- case 4:
263
- symbolsAndDecimals = _c.sent();
264
- if (!(timestamp === "now")) return [3 /*break*/, 5];
265
- allChainTokenPrices = symbolsAndDecimals.reduce(function (prices, item) {
266
- var chain, address;
267
- if (item.coin.includes(":")) {
268
- chain = item.coin.split(':')[0];
269
- address = item.coin.split(':')[1];
270
- }
271
- else {
272
- chain = "coingecko";
273
- address = item.coin;
274
- }
275
- if (prices[chain] === undefined) {
276
- prices[chain] = {};
277
- }
278
- prices[chain][address] = { usd: item.price };
279
- return prices;
280
- }, {});
281
- return [3 /*break*/, 7];
282
- case 5: return [4 /*yield*/, getHistoricalChainPrices(chainIds, timestamp, knownTokenPrices, getCoingeckoLock, coingeckoMaxRetries)];
283
- case 6:
284
- allChainTokenPrices = _c.sent();
285
- _c.label = 7;
286
- case 7:
287
- usdTokenBalances = {};
288
- tokenBalances = {};
289
- rawTokenBalances = {};
290
- usdAmounts = Object.entries(normalizedBalances).map(function (_a) {
291
- var address = _a[0], balance = _a[1];
292
- return __awaiter(_this, void 0, void 0, function () {
293
- var amount, price, tokenSymbol, normalizedAddress_1, chainSelector_1, chainTokenPrices, chainAddress_1, coinData, tokenDecimals, usdAmount;
294
- var _b, _c, _d, _e;
295
- return __generator(this, function (_f) {
296
- try {
297
- if (address.startsWith("0x") || address.includes(":")) {
298
- normalizedAddress_1 = address;
299
- chainSelector_1 = "ethereum";
300
- chains.forEach(function (chain) {
301
- if (address.startsWith(chain)) {
302
- chainSelector_1 = chain;
303
- normalizedAddress_1 = index_1.normalizeAddress(address.slice(chain.length + 1));
304
- }
305
- });
306
- chainTokenPrices = (_b = allChainTokenPrices[chainSelector_1]) !== null && _b !== void 0 ? _b : {};
307
- chainAddress_1 = chainSelector_1 + ":" + normalizedAddress_1;
308
- coinData = symbolsAndDecimals.find(function (coin) { return coin.coin === chainAddress_1; });
309
- tokenSymbol = (_c = coinData === null || coinData === void 0 ? void 0 : coinData.symbol) === null || _c === void 0 ? void 0 : _c.toUpperCase();
310
- if (tokenSymbol === undefined || tokenSymbol === null) {
311
- tokenSymbol = "UNKNOWN (" + address + ")";
312
- }
313
- tokenDecimals = coinData === null || coinData === void 0 ? void 0 : coinData.decimals;
314
- if (tokenDecimals === undefined) {
315
- amount = 0;
316
- }
317
- else {
318
- amount = Number(balance) / Math.pow(10, Number(tokenDecimals));
319
- }
320
- price = (_d = chainTokenPrices[normalizedAddress_1]) === null || _d === void 0 ? void 0 : _d.usd;
321
- //addTokenBalance(rawTokenBalances, normalizedAddress, amount)
322
- }
323
- else {
324
- tokenSymbol = address;
325
- price = (_e = allChainTokenPrices["coingecko"][address.toLowerCase()]) === null || _e === void 0 ? void 0 : _e.usd;
326
- amount = Number(balance);
327
- //addTokenBalance(rawTokenBalances, `coingecko:${address.toLowerCase()}`, amount)
328
- }
329
- if (price === undefined) {
330
- if (verbose) {
331
- console.log("Token " + address + " is not on coingecko, it'll be ignored");
332
- }
333
- price = 0;
334
- }
335
- addTokenBalance(tokenBalances, tokenSymbol, amount);
336
- usdAmount = amount * price;
337
- addTokenBalance(usdTokenBalances, tokenSymbol, usdAmount);
338
- return [2 /*return*/, { usdAmount: usdAmount, tokenSymbol: tokenSymbol }];
339
- }
340
- catch (e) {
341
- console.error("Error on token " + address + ", we'll just assume it's price is 0...", e);
342
- return [2 /*return*/, {
343
- usdAmount: 0,
344
- tokenSymbol: "ERROR " + address,
345
- }];
346
- }
347
- return [2 /*return*/];
348
- });
349
- });
350
- });
351
- if (!verbose) return [3 /*break*/, 9];
352
- return [4 /*yield*/, Promise.all(usdAmounts)];
353
- case 8:
354
- (_c.sent())
355
- .sort(function (a, b) { return b.usdAmount - a.usdAmount; })
356
- .map(function (token) {
357
- console.log(token.tokenSymbol.padEnd(25, " "), humanizeNumber_1.humanizeNumber(token.usdAmount));
358
- });
359
- _c.label = 9;
360
- case 9: return [4 /*yield*/, Promise.all(usdAmounts)];
361
- case 10:
362
- usdTvl = (_c.sent()).reduce(function (sum, token) {
363
- return sum + token.usdAmount;
364
- }, 0);
365
- return [2 /*return*/, {
366
- usdTvl: usdTvl,
367
- usdTokenBalances: usdTokenBalances,
368
- tokenBalances: tokenBalances,
369
- //rawTokenBalances
370
- }];
371
- }
372
- });
373
- });
374
- }
375
- exports.default = default_1;