@defillama/sdk 5.0.177 → 5.0.179

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.
@@ -60,7 +60,8 @@ class LlamaProvider extends ethers_1.FallbackProvider {
60
60
  currentBlocks[url] = block;
61
61
  }
62
62
  catch (e) {
63
- (0, debugLog_1.debugLog)(`${_this.chainName} skipping RPC ${url} is not working, error: ${e.message}`);
63
+ if (env_1.logLlamaProviderCalls)
64
+ (0, debugLog_1.debugLog)(`${_this.chainName} skipping RPC ${url} is not working, error: ${e.message}`);
64
65
  _this._removeProvider(url);
65
66
  }
66
67
  }
@@ -0,0 +1,18 @@
1
+ type CoinsApiData = {
2
+ decimals: number;
3
+ price: number;
4
+ symbol: string;
5
+ timestamp: number;
6
+ PK?: string;
7
+ };
8
+ type McapsApiData = {
9
+ mcap: number;
10
+ timestamp: number;
11
+ };
12
+ export declare function getPrices(readKeys: string[], timestamp: number | "now"): Promise<{
13
+ [address: string]: CoinsApiData;
14
+ }>;
15
+ export declare function getMcaps(readKeys: string[], timestamp: number | "now"): Promise<{
16
+ [address: string]: McapsApiData;
17
+ }>;
18
+ export {};
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getPrices = getPrices;
7
+ exports.getMcaps = getMcaps;
8
+ const axios_1 = __importDefault(require("axios"));
9
+ const env_1 = require("./env");
10
+ const promisePool_1 = __importDefault(require("./promisePool"));
11
+ const common_1 = require("./common");
12
+ const coinsApiKey = (0, env_1.getEnvValue)("COINS_API_KEY");
13
+ const bodySize = 2; // 100;
14
+ function getBodies(readKeys, timestamp) {
15
+ const bodies = [];
16
+ for (let i = 0; i < readKeys.length; i += bodySize) {
17
+ const body = {
18
+ coins: readKeys.slice(i, i + bodySize),
19
+ };
20
+ if (timestamp !== "now")
21
+ body.timestamp = timestamp;
22
+ bodies.push(JSON.stringify(body));
23
+ }
24
+ return bodies;
25
+ }
26
+ async function restCallWrapper(request, retries = 3, name = "-") {
27
+ while (retries > 0) {
28
+ try {
29
+ const res = await request();
30
+ return res;
31
+ }
32
+ catch {
33
+ await (0, common_1.sleepRandom)(5000 + 10000, 5000);
34
+ restCallWrapper(request, retries--, name);
35
+ }
36
+ }
37
+ throw new Error(`couldnt work ${name} call after retries!`);
38
+ }
39
+ const priceCache = {
40
+ "coingecko:tether": {
41
+ price: 1,
42
+ symbol: "USDT",
43
+ timestamp: Math.floor(Date.now() / 1e3 + 3600), // an hour from script start time
44
+ },
45
+ };
46
+ async function getPrices(readKeys, timestamp) {
47
+ if (!readKeys.length)
48
+ return {};
49
+ const aggregatedRes = {};
50
+ // read data from cache where possible
51
+ readKeys = readKeys.filter((PK) => {
52
+ if (timestamp !== "now")
53
+ return true;
54
+ if (priceCache[PK]) {
55
+ aggregatedRes[PK] = { ...priceCache[PK], PK };
56
+ return false;
57
+ }
58
+ return true;
59
+ });
60
+ const bodies = getBodies(readKeys, timestamp);
61
+ const tokenData = [];
62
+ await (0, promisePool_1.default)({
63
+ items: bodies,
64
+ concurrency: 10,
65
+ processor: async (body) => {
66
+ const res = await restCallWrapper(() => axios_1.default.post(`https://coins.llama.fi/prices?source=internal${coinsApiKey ? `?apikey=${coinsApiKey}` : ""}`, body, {
67
+ headers: { "Content-Type": "application/json" },
68
+ params: { source: "internal", apikey: coinsApiKey },
69
+ }));
70
+ const data = (res.data.coins = Object.entries(res.data.coins).map(([PK, value]) => ({
71
+ ...value,
72
+ PK,
73
+ })));
74
+ tokenData.push(data);
75
+ },
76
+ });
77
+ const normalizedReadKeys = readKeys.map((k) => k.toLowerCase());
78
+ tokenData.map((batch) => {
79
+ batch.map((a) => {
80
+ if (!a.PK)
81
+ return;
82
+ const i = normalizedReadKeys.indexOf(a.PK.toLowerCase());
83
+ aggregatedRes[readKeys[i]] = a;
84
+ });
85
+ });
86
+ return aggregatedRes;
87
+ }
88
+ const mcapCache = {};
89
+ async function getMcaps(readKeys, timestamp) {
90
+ if (!readKeys.length)
91
+ return {};
92
+ const aggregatedRes = {};
93
+ // read data from cache where possible
94
+ readKeys = readKeys.filter((PK) => {
95
+ if (timestamp !== "now")
96
+ return true;
97
+ if (mcapCache[PK]) {
98
+ aggregatedRes[PK] = { ...mcapCache[PK], PK };
99
+ return false;
100
+ }
101
+ return true;
102
+ });
103
+ const bodies = getBodies(readKeys, timestamp);
104
+ const tokenData = [];
105
+ await (0, promisePool_1.default)({
106
+ items: bodies,
107
+ concurrency: 10,
108
+ processor: async (body) => {
109
+ const res = await restCallWrapper(() => axios_1.default.post(`https://coins.llama.fi/mcaps${coinsApiKey ? `?apikey=${coinsApiKey}` : ""}`, body, {
110
+ headers: { "Content-Type": "application/json" },
111
+ }));
112
+ tokenData.push(res.data);
113
+ },
114
+ });
115
+ const normalizedReadKeys = readKeys.map((k) => k.toLowerCase());
116
+ tokenData.map((batch) => {
117
+ Object.keys(batch).map((a) => {
118
+ if (!batch[a].mcap)
119
+ return;
120
+ const i = normalizedReadKeys.indexOf(a.toLowerCase());
121
+ aggregatedRes[readKeys[i]] = batch[a];
122
+ });
123
+ });
124
+ return aggregatedRes;
125
+ }
@@ -2,9 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.default = computeTVL;
4
4
  exports.getUnique = getUnique;
5
- const _1 = require(".");
6
- const common_1 = require("./common");
7
- const env_1 = require("./env");
5
+ const generalUtil_1 = require("../generalUtil");
6
+ const coinsApi_1 = require("./coinsApi");
8
7
  const currentPriceCache = {};
9
8
  const priceCaches = {};
10
9
  let lastPriceUpdate = 0;
@@ -35,7 +34,7 @@ async function computeTVL(balances, timestamp, { debug = false } = {}) {
35
34
  usdTvl += value;
36
35
  if (symbol === 'ETH')
37
36
  symbol = 'WETH';
38
- (0, common_1.sumSingleBalance)(usdTokenBalances, symbol, value);
37
+ (0, generalUtil_1.sumSingleBalance)(usdTokenBalances, symbol, value);
39
38
  if (debug && !isNaN(+value))
40
39
  debugData.tokenData.push({ symbol, value, token, price, confidence, balance, decimals, });
41
40
  });
@@ -70,24 +69,11 @@ async function updatePriceCache(keys, timestamp) {
70
69
  "confidence": 1
71
70
  };
72
71
  const missingKeys = keys.filter(key => !pricesCache[key.toLowerCase()]);
73
- const chunks = (0, _1.sliceIntoChunks)(missingKeys, 100);
74
- for (const chunk of chunks) {
75
- const coins = await getPrices(chunk);
76
- for (const [token, data] of Object.entries(coins)) {
77
- pricesCache[token.toLowerCase()] = data;
78
- }
79
- chunk.map(i => i.toLowerCase()).filter(i => !pricesCache[i]).forEach(i => pricesCache[i] = {});
80
- }
81
- async function getPrices(keys) {
82
- if (!timestamp) {
83
- const { coins } = await (0, common_1.fetchJson)(`https://coins.llama.fi/prices/current/${keys.join(',')}`);
84
- return coins;
85
- }
86
- // fetch post with timestamp in body
87
- const coinsApiKey = env_1.ENV_CONSTANTS['COINS_API_KEY'];
88
- const { coins } = await (0, common_1.postJson)("https://coins.llama.fi/prices?source=internal&apikey=" + coinsApiKey, { coins: keys, timestamp });
89
- return coins;
72
+ const coins = await (0, coinsApi_1.getPrices)(missingKeys, timestamp !== null && timestamp !== void 0 ? timestamp : "now");
73
+ for (const [token, data] of Object.entries(coins)) {
74
+ pricesCache[token.toLowerCase()] = data;
90
75
  }
76
+ missingKeys.map(i => i.toLowerCase()).filter(i => !pricesCache[i]).forEach(i => pricesCache[i] = {});
91
77
  }
92
78
  function getPriceCache(timestamp) {
93
79
  if (timestamp)
@@ -1,3 +1,5 @@
1
+ export declare const isDebugLevel3: boolean;
2
+ export declare const logLlamaProviderCalls: boolean;
1
3
  export declare const logGetBlockStats: boolean;
2
4
  export declare const logGetLogsErrors: boolean;
3
5
  export declare const logGetLogsDebug: boolean;
package/build/util/env.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  var _a;
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.ENV_CONSTANTS = exports.defaultShortenStringLength = exports.logGetLogsIndexer = exports.logGetLogsDebug = exports.logGetLogsErrors = exports.logGetBlockStats = void 0;
4
+ exports.ENV_CONSTANTS = exports.defaultShortenStringLength = exports.logGetLogsIndexer = exports.logGetLogsDebug = exports.logGetLogsErrors = exports.logGetBlockStats = exports.logLlamaProviderCalls = exports.isDebugLevel3 = void 0;
5
5
  exports.getChainId = getChainId;
6
6
  exports.getMaxParallelRequests = getMaxParallelRequests;
7
7
  exports.getParallelGetLogsLimit = getParallelGetLogsLimit;
@@ -19,10 +19,12 @@ const whitelistedEnvConstants = [
19
19
  'R2_ENDPOINT', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'TRON_PRO_API_KEY', 'COINS_API_KEY',
20
20
  'ELASTICSEARCH_CONFIG', 'GRAPH_API_KEY', 'LLAMA_INDEXER_ENDPOINT', 'LLAMA_INDEXER_API_KEY', 'LLAMA_INDEXER_V2_ENDPOINT', 'LLAMA_INDEXER_V2_API_KEY',
21
21
  ];
22
- exports.logGetBlockStats = process.env.LLAMA_SDK_LOG_GET_BLOCK_STATS === 'true' || false;
23
- exports.logGetLogsErrors = process.env.LLAMA_SDK_LOG_GET_LOGS_ERRORS === 'true' || false;
24
- exports.logGetLogsDebug = process.env.LLAMA_SDK_LOG_GET_LOGS_DEBUG === 'true' || false;
25
- exports.logGetLogsIndexer = process.env.LLAMA_SDK_LOG_GET_LOGS_INDEXER === 'true' || false;
22
+ exports.isDebugLevel3 = process.env.LLAMA_SDK_DEBUG_LEVEL_3 === 'true' || false;
23
+ exports.logLlamaProviderCalls = process.env.LLAMA_SDK_LOG_LLAMA_PROVIDER_CALLS === 'true' || exports.isDebugLevel3;
24
+ exports.logGetBlockStats = process.env.LLAMA_SDK_LOG_GET_BLOCK_STATS === 'true' || exports.isDebugLevel3;
25
+ exports.logGetLogsErrors = process.env.LLAMA_SDK_LOG_GET_LOGS_ERRORS === 'true' || exports.isDebugLevel3;
26
+ exports.logGetLogsDebug = process.env.LLAMA_SDK_LOG_GET_LOGS_DEBUG === 'true' || exports.isDebugLevel3;
27
+ exports.logGetLogsIndexer = process.env.LLAMA_SDK_LOG_GET_LOGS_INDEXER === 'true' || exports.isDebugLevel3;
26
28
  exports.defaultShortenStringLength = +((_a = process.env.LLAMA_SDK_DEFAULT_SHORTEN_STRING_LENGTH) !== null && _a !== void 0 ? _a : '120');
27
29
  const defaultEnvValues = {
28
30
  INTERNAL_SDK_CACHE_FILE: './cache.json',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defillama/sdk",
3
- "version": "5.0.177",
3
+ "version": "5.0.179",
4
4
  "description": "SDK for calculating TVL",
5
5
  "main": "build/index.js",
6
6
  "scripts": {