@defillama/sdk 5.0.173 → 5.0.177

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.
Files changed (53) hide show
  1. package/build/Balances.d.ts +2 -2
  2. package/build/ChainApi.d.ts +26 -14
  3. package/build/ChainApi.js +58 -28
  4. package/build/abi/abi2.js +23 -15
  5. package/build/abi/cachedABIs.d.ts +1 -1
  6. package/build/abi/convertResults.d.ts +4 -1
  7. package/build/abi/convertResults.js +20 -15
  8. package/build/abi/index.js +16 -39
  9. package/build/abi/multicall.js +6 -31
  10. package/build/abi/multicall3.js +36 -37
  11. package/build/abi/rpcCall.js +1 -2
  12. package/build/abi/tron.d.ts +5 -6
  13. package/build/abi/tron.js +79 -198
  14. package/build/api.js +17 -7
  15. package/build/api2.js +17 -7
  16. package/build/computeTVL/humanizeNumber.js +1 -2
  17. package/build/erc20/index.js +5 -6
  18. package/build/eth/index.d.ts +1 -0
  19. package/build/eth/index.js +39 -16
  20. package/build/general.js +2 -2
  21. package/build/generalUtil.d.ts +2 -24
  22. package/build/generalUtil.js +39 -246
  23. package/build/index.js +17 -7
  24. package/build/providers.json +1 -1
  25. package/build/util/LlamaProvider.js +8 -3
  26. package/build/util/blocks.js +17 -20
  27. package/build/util/cache.d.ts +11 -2
  28. package/build/util/cache.js +53 -9
  29. package/build/util/common.d.ts +33 -0
  30. package/build/util/common.js +352 -0
  31. package/build/util/computeTVL.js +6 -11
  32. package/build/util/cosmos.js +6 -9
  33. package/build/util/debugLog.js +3 -3
  34. package/build/util/elastic.d.ts +19 -0
  35. package/build/util/elastic.js +54 -6
  36. package/build/util/env.d.ts +7 -1
  37. package/build/util/env.js +28 -15
  38. package/build/util/graph.js +4 -8
  39. package/build/util/index.d.ts +1 -1
  40. package/build/util/index.js +17 -15
  41. package/build/util/indexer.js +29 -19
  42. package/build/util/internal-cache.js +22 -13
  43. package/build/util/logs.js +7 -7
  44. package/build/util/promisePool.d.ts +4 -1
  45. package/build/util/promisePool.js +22 -7
  46. package/build/util/r2.d.ts +0 -1
  47. package/build/util/r2.js +4 -9
  48. package/build/util/removeRedundantRPCs.js +2 -2
  49. package/build/util/transactions.js +1 -2
  50. package/build/util/updateProviderList.js +6 -6
  51. package/package.json +3 -1
  52. package/build/computeTVL/prices.d.ts +0 -9
  53. package/build/computeTVL/prices.js +0 -73
@@ -3,7 +3,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getProvider = exports.setProvider = exports.providers = exports.LlamaProvider = void 0;
6
+ exports.providers = exports.LlamaProvider = void 0;
7
+ exports.setProvider = setProvider;
8
+ exports.getProvider = getProvider;
7
9
  const ethers_1 = require("ethers");
8
10
  const providers_json_1 = __importDefault(require("../providers.json"));
9
11
  const env_1 = require("./env");
@@ -182,7 +184,6 @@ exports.providers = {};
182
184
  function setProvider(chain, provider) {
183
185
  exports.providers[chain] = provider;
184
186
  }
185
- exports.setProvider = setProvider;
186
187
  function getProvider(chain = "ethereum", _getArchivalNode = false) {
187
188
  var _a, _b;
188
189
  const rpcKey = chain === 'tron' ? 'tron_evm' : chain;
@@ -195,6 +196,11 @@ function getProvider(chain = "ethereum", _getArchivalNode = false) {
195
196
  // use RPC from env variable if set else use RPC from providers.json
196
197
  let rpcList = (0, env_1.getChainRPCs)(rpcKey, (_a = pList[chain]) === null || _a === void 0 ? void 0 : _a.rpc);
197
198
  let archivalRPCList = (0, env_1.getArchivalRPCs)(rpcKey);
199
+ let whitelistedRPCList = (0, env_1.getWhitelistedRPCs)(rpcKey);
200
+ if (whitelistedRPCList === null || whitelistedRPCList === void 0 ? void 0 : whitelistedRPCList.length) {
201
+ rpcList = [...whitelistedRPCList].join(',');
202
+ archivalRPCList = whitelistedRPCList;
203
+ }
198
204
  if (!rpcList) {
199
205
  // @ts-ignore (throwing error here would alter function behavior and have side effects)
200
206
  return null;
@@ -203,7 +209,6 @@ function getProvider(chain = "ethereum", _getArchivalNode = false) {
203
209
  exports.providers[chainKey] = createProvider(chain, rpcList, (_b = providers_json_1.default[chain]) === null || _b === void 0 ? void 0 : _b.chainId, archivalRPCList);
204
210
  return exports.providers[chainKey];
205
211
  }
206
- exports.getProvider = getProvider;
207
212
  function toHex(n) {
208
213
  if (typeof n === 'string')
209
214
  return n;
@@ -3,10 +3,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getTimestamp = exports.lookupBlock = exports.getLatestBlock = exports.getCurrentChainBlock = exports.getBlockNumber = exports.getBlock = exports.getCurrentBlocks = exports.getBlocks = exports.getChainBlocks = exports.chainsForBlocks = void 0;
6
+ exports.getLatestBlock = exports.chainsForBlocks = void 0;
7
+ exports.getChainBlocks = getChainBlocks;
8
+ exports.getBlocks = getBlocks;
9
+ exports.getCurrentBlocks = getCurrentBlocks;
10
+ exports.getBlock = getBlock;
11
+ exports.getBlockNumber = getBlockNumber;
12
+ exports.getCurrentChainBlock = getCurrentChainBlock;
13
+ exports.lookupBlock = lookupBlock;
14
+ exports.getTimestamp = getTimestamp;
7
15
  const general_1 = require("../general");
8
- const axios_1 = __importDefault(require("axios"));
9
- const generalUtil_1 = require("../generalUtil");
16
+ const common_1 = require("./common");
10
17
  const debugLog_1 = require("./debugLog");
11
18
  const cosmos_1 = require("./cosmos");
12
19
  const cache_1 = require("./cache");
@@ -21,7 +28,6 @@ async function getChainBlocks(timestamp, chains = defaultChains) {
21
28
  await Promise.all(chains.map(setBlock));
22
29
  return chainBlocks;
23
30
  }
24
- exports.getChainBlocks = getChainBlocks;
25
31
  async function getBlocks(timestamp, chains = undefined) {
26
32
  chains = chains === null || chains === void 0 ? void 0 : chains.filter(i => i !== 'ethereum');
27
33
  const [ethBlock, chainBlocks] = await Promise.all([getBlockNumber('ethereum', timestamp), getChainBlocks(timestamp, chains)]);
@@ -31,7 +37,6 @@ async function getBlocks(timestamp, chains = undefined) {
31
37
  chainBlocks,
32
38
  };
33
39
  }
34
- exports.getBlocks = getBlocks;
35
40
  async function getCurrentBlocks(chains = undefined) {
36
41
  if (chains)
37
42
  chains = chains.filter(i => i !== "ethereum");
@@ -44,7 +49,6 @@ async function getCurrentBlocks(chains = undefined) {
44
49
  chainBlocks,
45
50
  };
46
51
  }
47
- exports.getCurrentBlocks = getCurrentBlocks;
48
52
  async function getBlock(chain, timestamp, options = {}) {
49
53
  if (!timestamp)
50
54
  return getCurrentChainBlock(chain);
@@ -60,11 +64,9 @@ async function getBlock(chain, timestamp, options = {}) {
60
64
  }
61
65
  throw error;
62
66
  }
63
- exports.getBlock = getBlock;
64
67
  async function getBlockNumber(chain, timestamp) {
65
68
  return (await getBlock(chain, timestamp)).block;
66
69
  }
67
- exports.getBlockNumber = getBlockNumber;
68
70
  const refreshInterval = 1000 * 60 * 1; // 1 minute
69
71
  function getCurrentChainBlock(chain = 'ethereum') {
70
72
  const { timestamp, } = currentChainBlockCache[chain] || {};
@@ -90,22 +92,19 @@ function getCurrentChainBlock(chain = 'ethereum') {
90
92
  delete currentChainBlockCache[chain];
91
93
  if ((_b = (_a = e === null || e === void 0 ? void 0 : e.message) === null || _a === void 0 ? void 0 : _a.includes) === null || _b === void 0 ? void 0 : _b.call(_a, "Last block of chain"))
92
94
  throw e;
93
- throw (0, generalUtil_1.formError)(e);
95
+ throw (0, common_1.formError)(e);
94
96
  }
95
97
  }
96
98
  }
97
- exports.getCurrentChainBlock = getCurrentChainBlock;
98
99
  const algorandBlockProvider = {
99
100
  getBlock: async (height) => {
100
101
  if (height !== 'latest')
101
- return (0, axios_1.default)(`https://algoindexer.algoexplorerapi.io/v2/blocks/${height}`)
102
- .then((res) => res.data)
102
+ return (0, common_1.fetchJson)(`https://algoindexer.algoexplorerapi.io/v2/blocks/${height}`)
103
103
  .then((block) => ({
104
104
  number: block.round,
105
105
  timestamp: block.timestamp
106
106
  }));
107
- return (0, axios_1.default)('https://algoindexer.algoexplorerapi.io/health')
108
- .then((res) => res.data)
107
+ return (0, common_1.fetchJson)('https://algoindexer.algoexplorerapi.io/health')
109
108
  .then((block) => algorandBlockProvider.getBlock(block.round));
110
109
  }
111
110
  };
@@ -139,7 +138,7 @@ function validateCurrentBlock(block, chain = 'ethereum') {
139
138
  const now = Math.floor(Date.now() / 1000);
140
139
  const minutesDiff = Math.floor((now - block.timestamp) / 60);
141
140
  if (minutesDiff > 60)
142
- throw new Error(`Last block for ${chain} is ${minutesDiff} minutes behind (${new Date(block.timestamp * 1000)}). Provider is "${(0, generalUtil_1.getProviderUrl)(provider)}"`);
141
+ throw new Error(`Last block for ${chain} is ${minutesDiff} minutes behind (${new Date(block.timestamp * 1000)}). Provider is "${(0, common_1.getProviderUrl)(provider)}"`);
143
142
  }
144
143
  const chainLimiters = {};
145
144
  function getChainLimiter(chain) {
@@ -155,7 +154,6 @@ async function lookupBlock(timestamp, extraParams) {
155
154
  const limiter = getChainLimiter(chain);
156
155
  return limiter(() => _lookupBlock(timestamp, extraParams));
157
156
  }
158
- exports.lookupBlock = lookupBlock;
159
157
  async function _lookupBlock(timestamp, extraParams) {
160
158
  var _a, _b;
161
159
  const { allowedTimeRange = 5 * 60, acceptableBlockImprecision = 10 } = extraParams !== null && extraParams !== void 0 ? extraParams : {};
@@ -166,7 +164,7 @@ async function _lookupBlock(timestamp, extraParams) {
166
164
  }
167
165
  if (chain === 'waves') {
168
166
  const api = `https://nodes.wavesnodes.com/blocks/heightByTimestamp/${timestamp}`;
169
- const { data } = await (0, axios_1.default)(api);
167
+ const data = await (0, common_1.fetchJson)(api);
170
168
  return {
171
169
  timestamp,
172
170
  block: +data.height,
@@ -229,7 +227,7 @@ async function _lookupBlock(timestamp, extraParams) {
229
227
  ]);
230
228
  updateBlock(blocks);
231
229
  }
232
- if (i > 2)
230
+ if (i > 2 && env_1.logGetBlockStats)
233
231
  (0, debugLog_1.debugLog)(`chain: ${chain} block: ${block.number} #calls: ${i} imprecision: ${Number((imprecision) / 60).toFixed(2)} (min) Time Taken: ${Number((Date.now() - time) / 1000).toFixed(2)} (in sec)`);
234
232
  if (chain !== "bsc" && // this check is there because bsc halted the chain for few days
235
233
  Math.abs(block.timestamp - timestamp) > 3600) {
@@ -242,7 +240,7 @@ async function _lookupBlock(timestamp, extraParams) {
242
240
  };
243
241
  }
244
242
  catch (e) {
245
- throw (0, generalUtil_1.formError)(e);
243
+ throw (0, common_1.formError)(e);
246
244
  }
247
245
  function updateBlock(blocks = []) {
248
246
  blocks.forEach(addBlockToCache);
@@ -287,5 +285,4 @@ async function getTimestamp(height, chain) {
287
285
  const block = await provider.getBlock(height);
288
286
  return block.timestamp;
289
287
  }
290
- exports.getTimestamp = getTimestamp;
291
288
  const currentChainBlockCache = {};
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  export declare const currentVersion = "zlib-1.0";
3
2
  export declare function readCache(file: string, options?: ReadCacheOptions): Promise<any>;
4
3
  interface WriteCacheOptions {
@@ -14,7 +13,7 @@ interface ReadCacheOptions {
14
13
  }
15
14
  export declare function writeCache(file: string, data: any, options?: WriteCacheOptions): Promise<string | undefined>;
16
15
  export declare function parseCache(dataString: string | Buffer, options?: ReadCacheOptions): Promise<any>;
17
- export declare function compressCache(data: any, options?: WriteCacheOptions): Promise<string | Buffer>;
16
+ export declare function compressCache(data: any, options?: WriteCacheOptions): Promise<string | Buffer<ArrayBufferLike>>;
18
17
  export declare const ONE_WEEK: number;
19
18
  export declare function getTempLocalCache({ file, defaultData, clearAfter, returnWithSaveFunction }: {
20
19
  file: string;
@@ -32,4 +31,14 @@ expiryTimestamp, }: {
32
31
  expireAfter?: number;
33
32
  expiryTimestamp?: number;
34
33
  }): Promise<void>;
34
+ export declare function cachedFetch({ key, endpoint, postData, fetcher, fetchOptions, errorOnNoCache, writeCacheOptions, readCacheOptions, }: {
35
+ key: string;
36
+ endpoint?: string;
37
+ postData?: any;
38
+ fetcher?: () => Promise<any>;
39
+ fetchOptions?: any;
40
+ errorOnNoCache?: boolean;
41
+ writeCacheOptions?: WriteCacheOptions;
42
+ readCacheOptions?: ReadCacheOptions;
43
+ }): Promise<any>;
35
44
  export {};
@@ -1,11 +1,25 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.writeExpiringJsonCache = exports.readExpiringJsonCache = exports.deleteCache = exports.getTempLocalCache = exports.ONE_WEEK = exports.compressCache = exports.parseCache = exports.writeCache = exports.readCache = exports.currentVersion = void 0;
6
+ exports.ONE_WEEK = exports.currentVersion = void 0;
7
+ exports.readCache = readCache;
8
+ exports.writeCache = writeCache;
9
+ exports.parseCache = parseCache;
10
+ exports.compressCache = compressCache;
11
+ exports.getTempLocalCache = getTempLocalCache;
12
+ exports.deleteCache = deleteCache;
13
+ exports.readExpiringJsonCache = readExpiringJsonCache;
14
+ exports.writeExpiringJsonCache = writeExpiringJsonCache;
15
+ exports.cachedFetch = cachedFetch;
4
16
  const debugLog_1 = require("./debugLog");
5
17
  const r2_1 = require("./r2");
6
18
  const zlib_1 = require("zlib");
7
19
  const util_1 = require("util");
8
20
  const env_1 = require("./env");
21
+ const common_1 = require("./common");
22
+ const crypto_1 = __importDefault(require("crypto"));
9
23
  const brotliOptions = {
10
24
  [zlib_1.constants.BROTLI_PARAM_MODE]: zlib_1.constants.BROTLI_MODE_TEXT,
11
25
  [zlib_1.constants.BROTLI_PARAM_QUALITY]: zlib_1.constants.BROTLI_MAX_QUALITY,
@@ -78,7 +92,6 @@ async function readCache(file, options = {}) {
78
92
  }
79
93
  }
80
94
  }
81
- exports.readCache = readCache;
82
95
  async function writeCache(file, data, options = {}) {
83
96
  try {
84
97
  const fileData = options.alreadyCompressed ? data : await compressCache(data, options);
@@ -102,7 +115,6 @@ async function writeCache(file, data, options = {}) {
102
115
  (0, debugLog_1.debugLog)('Error writing cache:', error);
103
116
  }
104
117
  }
105
- exports.writeCache = writeCache;
106
118
  async function parseCache(dataString, options = {}) {
107
119
  var _a;
108
120
  let dataBuffer;
@@ -124,7 +136,6 @@ async function parseCache(dataString, options = {}) {
124
136
  }
125
137
  return JSON.parse(decompressed).llamaWrapped;
126
138
  }
127
- exports.parseCache = parseCache;
128
139
  async function compressCache(data, options = {}) {
129
140
  const dataString = JSON.stringify({ version: exports.currentVersion, llamaWrapped: data });
130
141
  if (options.skipCompression)
@@ -132,7 +143,6 @@ async function compressCache(data, options = {}) {
132
143
  const comressedCache = await zipAsync(dataString);
133
144
  return comressedCache;
134
145
  }
135
- exports.compressCache = compressCache;
136
146
  function isSameData(data1, data2) {
137
147
  return JSON.stringify(data1) === JSON.stringify(data2);
138
148
  }
@@ -196,13 +206,11 @@ function getTempLocalCache({ file, defaultData = {}, clearAfter = exports.ONE_WE
196
206
  }
197
207
  }
198
208
  }
199
- exports.getTempLocalCache = getTempLocalCache;
200
209
  // this removes data only from the file cache, not from the R2 cache
201
210
  async function deleteCache(file) {
202
211
  const filePath = getFilePath(file);
203
212
  await fs.unlink(filePath);
204
213
  }
205
- exports.deleteCache = deleteCache;
206
214
  async function readExpiringJsonCache(file) {
207
215
  const options = { readFromR2Cache: false, skipR2Cache: true, skipCompression: true };
208
216
  file = 'expiring/' + file;
@@ -215,7 +223,6 @@ async function readExpiringJsonCache(file) {
215
223
  }
216
224
  return data.data;
217
225
  }
218
- exports.readExpiringJsonCache = readExpiringJsonCache;
219
226
  async function writeExpiringJsonCache(file, data, { expireAfter = 60 * 60 * 24, // cache for 1 day by default
220
227
  expiryTimestamp, }) {
221
228
  file = 'expiring/' + file;
@@ -224,4 +231,41 @@ expiryTimestamp, }) {
224
231
  const options = { skipR2CacheWrite: true, skipCompression: true };
225
232
  await writeCache(file, { data, expiryTimestamp }, options);
226
233
  }
227
- exports.writeExpiringJsonCache = writeExpiringJsonCache;
234
+ async function cachedFetch({ key, endpoint, postData, fetcher, fetchOptions, errorOnNoCache = true, writeCacheOptions = {
235
+ skipCompression: true,
236
+ skipR2CacheWrite: true,
237
+ }, readCacheOptions = {
238
+ skipCompression: true,
239
+ skipR2Cache: true,
240
+ }, }) {
241
+ if (!key) {
242
+ if (!endpoint || postData || fetcher)
243
+ throw new Error('Key is required for cachedFetch');
244
+ key = crypto_1.default.createHash('sha256').update(endpoint).digest('hex').substring(0, 32);
245
+ }
246
+ const fileKey = 'cached-fetch/' + key;
247
+ try {
248
+ let data;
249
+ if (fetcher)
250
+ data = await fetcher();
251
+ else {
252
+ if (!endpoint)
253
+ throw new Error('Either fetcher or endpoint is required for cachedFetch');
254
+ if (postData)
255
+ data = await (0, common_1.postJson)(endpoint, postData, fetchOptions);
256
+ else
257
+ data = await (0, common_1.fetchJson)(endpoint, fetchOptions);
258
+ }
259
+ await writeCache(fileKey, data, writeCacheOptions);
260
+ return data;
261
+ }
262
+ catch (error) {
263
+ const errorMessage = (0, common_1.formError)(error).message;
264
+ (0, debugLog_1.debugLog)('Error in cachedFetch:', errorMessage);
265
+ // if fetch fails, read from cache
266
+ const cachedData = await readCache(fileKey, readCacheOptions);
267
+ if (!cachedData && errorOnNoCache)
268
+ throw new Error('Fetch failed and no cache available');
269
+ return cachedData;
270
+ }
271
+ }
@@ -0,0 +1,33 @@
1
+ import type { Balances, StringNumber, Address } from "../types";
2
+ export declare function convertToBigInt(value: any): bigint;
3
+ export declare function sumMultiBalanceOf(balances: Balances, results: {
4
+ ethCallCount?: number;
5
+ output: {
6
+ output: StringNumber;
7
+ success: boolean;
8
+ input: {
9
+ target: Address;
10
+ params: string[];
11
+ };
12
+ }[];
13
+ }, allCallsMustBeSuccessful?: boolean, transformAddress?: (addr: string) => string): void;
14
+ export declare function sumSingleBalance(balances: Balances, token: string, balance: string | number | BigInt, chain?: string): void;
15
+ export declare function mergeBalances(balances: Balances, balancesToMerge: Balances): void;
16
+ export declare function removeTokenBalance(balances: Balances, token: string, isCaseSensitive?: boolean): Balances;
17
+ type ChainBlocks = {
18
+ [chain: string]: number;
19
+ };
20
+ export declare function sumChainTvls(chainTvls: Array<(timestamp: number, ethBlock: number, chainBlocks: ChainBlocks, params: any) => Promise<Balances>>): (timestamp: number, ethBlock: number, chainBlocks: ChainBlocks, params: any) => Promise<any>;
21
+ export declare function getUniqueAddresses(addresses: string[], chain?: string): string[];
22
+ export declare function getProviderUrl(provider: any): any;
23
+ export declare function formErrorString(e: any, errorParams?: any): any;
24
+ export declare function shortenString(str: string, length?: number): string;
25
+ export declare function formError(e: any, errorParams?: any): Error;
26
+ export declare function fetchJson(url: string, params?: any): Promise<any>;
27
+ export declare function postJson(url: string, data?: any, params?: any): Promise<any>;
28
+ export declare function tronToEvmAddress(address: string): string;
29
+ export declare function evmToTronAddress(address: string): string;
30
+ export declare function sleep(ms: number): Promise<unknown>;
31
+ export declare function sleepRandom(max: number, min?: number): Promise<unknown>;
32
+ export declare function fixTronCallParams(params: any): void;
33
+ export {};