@defillama/sdk 5.0.142 → 5.0.144

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.
@@ -183,8 +183,11 @@ exports.setProvider = setProvider;
183
183
  function getProvider(chain = "ethereum", _getArchivalNode = false) {
184
184
  var _a, _b;
185
185
  const rpcKey = chain === 'tron' ? 'tron_evm' : chain;
186
- if (exports.providers[chain])
187
- return exports.providers[chain];
186
+ let chainKey = chain;
187
+ if ((0, env_1.getEnvValue)('HISTORICAL'))
188
+ chainKey = chain + '_historical';
189
+ if (exports.providers[chainKey])
190
+ return exports.providers[chainKey];
188
191
  const pList = buildProviders !== null && buildProviders !== void 0 ? buildProviders : providers_json_1.default;
189
192
  // use RPC from env variable if set else use RPC from providers.json
190
193
  let rpcList = (0, env_1.getChainRPCs)(rpcKey, (_a = pList[chain]) === null || _a === void 0 ? void 0 : _a.rpc);
@@ -193,9 +196,9 @@ function getProvider(chain = "ethereum", _getArchivalNode = false) {
193
196
  // @ts-ignore (throwing error here would alter function behavior and have side effects)
194
197
  return null;
195
198
  }
196
- if (!exports.providers[chain])
197
- exports.providers[chain] = createProvider(chain, rpcList, (_b = providers_json_1.default[chain]) === null || _b === void 0 ? void 0 : _b.chainId, archivalRPCList);
198
- return exports.providers[chain];
199
+ if (!exports.providers[chainKey])
200
+ exports.providers[chainKey] = createProvider(chain, rpcList, (_b = providers_json_1.default[chain]) === null || _b === void 0 ? void 0 : _b.chainId, archivalRPCList);
201
+ return exports.providers[chainKey];
199
202
  }
200
203
  exports.getProvider = getProvider;
201
204
  function toHex(n) {
@@ -65,7 +65,7 @@ async function getBlockNumber(chain, timestamp) {
65
65
  return (await getBlock(chain, timestamp)).block;
66
66
  }
67
67
  exports.getBlockNumber = getBlockNumber;
68
- const refreshInterval = 1000 * 60 * 1; // 5 minutes
68
+ const refreshInterval = 1000 * 60 * 1; // 1 minute
69
69
  function getCurrentChainBlock(chain = 'ethereum') {
70
70
  const { timestamp, } = currentChainBlockCache[chain] || {};
71
71
  const currentTimestamp = Date.now();
@@ -131,7 +131,9 @@ const intialBlocks = {
131
131
  terra: 4724001,
132
132
  crab: 4969901
133
133
  };
134
- const blockTimeCache = (0, cache_1.getTempLocalCache)({ file: 'BlockCache.json', defaultData: {} });
134
+ let lastBlockCacheSave = Date.now();
135
+ const blockCacheSaveInterval = 1000 * 60 * 5; // 5 minutes
136
+ const { data: blockTimeCache, saveCacheFile: saveBlockCacheFile } = (0, cache_1.getTempLocalCache)({ file: 'BlockCache.json', defaultData: {}, clearAfter: cache_1.ONE_WEEK, returnWithSaveFunction: true });
135
137
  function validateCurrentBlock(block, chain = 'ethereum') {
136
138
  const provider = getExtraProvider(chain);
137
139
  const now = Math.floor(Date.now() / 1000);
@@ -158,6 +160,10 @@ async function _lookupBlock(timestamp, extraParams) {
158
160
  var _a, _b;
159
161
  const { allowedTimeRange = 5 * 60, acceptableBlockImprecision = 10 } = extraParams !== null && extraParams !== void 0 ? extraParams : {};
160
162
  const chain = (_a = extraParams === null || extraParams === void 0 ? void 0 : extraParams.chain) !== null && _a !== void 0 ? _a : "ethereum";
163
+ let time = Date.now();
164
+ if (timestamp > time / 1000) {
165
+ throw new Error(`Requesting for block in the future ${timestamp} is in the future, current time is ${Math.floor(time / 1000)}`);
166
+ }
161
167
  if (chain === 'waves') {
162
168
  const api = `https://nodes.wavesnodes.com/blocks/heightByTimestamp/${timestamp}`;
163
169
  const { data } = await (0, axios_1.default)(api);
@@ -177,29 +183,29 @@ async function _lookupBlock(timestamp, extraParams) {
177
183
  lowBlock = undefined;
178
184
  let block;
179
185
  let i = 0;
180
- let time = Date.now();
181
186
  let blockImprecision;
182
187
  let imprecision;
183
188
  try {
184
189
  let firstBlock, lastBlock;
185
- if (['evmos'].includes(chain)) {
190
+ if (['evmos', 'nibiru'].includes(chain)) {
186
191
  lastBlock = await (0, exports.getLatestBlock)(chain);
187
192
  let firstBlockNum = lastBlock.number;
188
193
  switch (chain) {
189
- default: firstBlockNum -= 2 * 1e5; // evmos hold only the last 200k block data
194
+ case 'nibiru': firstBlockNum -= 4 * 1e5; // nibiru hold only the last 400k block data
195
+ case 'evmos': firstBlockNum -= 2 * 1e5; // evmos hold only the last 200k block data
190
196
  }
191
197
  firstBlock = await fetchBlockFromProvider(firstBlockNum, chain);
192
198
  }
193
199
  else {
194
200
  [lastBlock, firstBlock] = await Promise.all([
195
- (0, exports.getLatestBlock)(chain),
201
+ highBlock ? highBlock : (0, exports.getLatestBlock)(chain),
196
202
  lowBlock ? lowBlock : fetchBlockFromProvider(low, chain),
197
203
  ]);
198
204
  }
199
205
  lowBlock = firstBlock;
200
206
  if (!highBlock)
201
207
  highBlock = lastBlock;
202
- if (Math.abs(highBlock.timestamp - timestamp) < 60 * 30) {
208
+ if (Math.abs(highBlock.timestamp - timestamp) < 60 * 5) {
203
209
  // Short-circuit in case we are trying to get the current block
204
210
  return {
205
211
  block: highBlock.number,
@@ -208,7 +214,7 @@ async function _lookupBlock(timestamp, extraParams) {
208
214
  };
209
215
  }
210
216
  updateBlock();
211
- while (imprecision > allowedTimeRange && blockImprecision > acceptableBlockImprecision) { // We lose some precision (max ~15 minutes) but reduce #calls needed
217
+ while (imprecision > allowedTimeRange && blockImprecision > acceptableBlockImprecision && i < 50) { // We lose some precision (max ~15 minutes) but reduce #calls needed
212
218
  ++i;
213
219
  const blockDiff = highBlock.number - lowBlock.number;
214
220
  const timeDiff = highBlock.timestamp - lowBlock.timestamp;
@@ -244,8 +250,8 @@ async function _lookupBlock(timestamp, extraParams) {
244
250
  blocks.sort((a, b) => getPrecision(a) - getPrecision(b));
245
251
  block = blocks[0];
246
252
  // find the closest upper and lower bound between 4 points
247
- lowBlock = blocks.filter(i => i.timestamp < timestamp).reduce((lowestBlock, block) => (timestamp - lowestBlock.timestamp) < (timestamp - block.timestamp) ? lowestBlock : block);
248
- highBlock = blocks.filter(i => i.timestamp > timestamp).reduce((highestBlock, block) => (highestBlock.timestamp - timestamp) < (block.timestamp - timestamp) ? highestBlock : block);
253
+ lowBlock = blocks.filter(i => i.timestamp < timestamp).reduce((lowestBlock, block) => (timestamp - lowestBlock.timestamp) < (timestamp - block.timestamp) ? lowestBlock : block, lowBlock);
254
+ highBlock = blocks.filter(i => i.timestamp > timestamp).reduce((highestBlock, block) => (highestBlock.timestamp - timestamp) < (block.timestamp - timestamp) ? highestBlock : block, highBlock);
249
255
  imprecision = getPrecision(block);
250
256
  blockImprecision = highBlock.number - lowBlock.number;
251
257
  // debugLog(`chain: ${chain} block: ${block.number} #calls: ${i} imprecision: ${Number((imprecision)/60).toFixed(2)} (min) block diff: ${blockImprecision} Time Taken: ${Number((Date.now()-time)/1000).toFixed(2)} (in sec)`)
@@ -258,6 +264,11 @@ async function _lookupBlock(timestamp, extraParams) {
258
264
  function addBlockToCache(block) {
259
265
  const { number, timestamp } = block;
260
266
  getChainBlockTimeCache(chain)[block.number] = { number, timestamp, };
267
+ // save the block cache every 5 minutes
268
+ if (Date.now() - lastBlockCacheSave > blockCacheSaveInterval) {
269
+ lastBlockCacheSave = Date.now();
270
+ saveBlockCacheFile();
271
+ }
261
272
  }
262
273
  function getLowBlock() {
263
274
  return Object.values(getChainBlockTimeCache(chain))
@@ -276,4 +287,4 @@ async function getTimestamp(height, chain) {
276
287
  return block.timestamp;
277
288
  }
278
289
  exports.getTimestamp = getTimestamp;
279
- const currentChainBlockCache = (0, cache_1.getTempLocalCache)({ file: 'currentChainBlockCache.json', defaultData: {} });
290
+ const currentChainBlockCache = {};
@@ -13,11 +13,16 @@ interface ReadCacheOptions {
13
13
  export declare function writeCache(file: string, data: any, options?: WriteCacheOptions): Promise<string | undefined>;
14
14
  export declare function parseCache(dataString: string | Buffer): Promise<any>;
15
15
  export declare function compressCache(data: any): Promise<Buffer>;
16
- export declare function getTempLocalCache({ file, defaultData, clearAfter }: {
16
+ export declare const ONE_WEEK: number;
17
+ export declare function getTempLocalCache({ file, defaultData, clearAfter, returnWithSaveFunction }: {
17
18
  file: string;
18
19
  defaultData?: any;
19
20
  clearAfter?: number;
20
- }): any;
21
+ returnWithSaveFunction?: boolean;
22
+ }): any | ({
23
+ data: any;
24
+ saveCacheFile: () => void;
25
+ });
21
26
  export declare function deleteCache(file: string): Promise<void>;
22
27
  export declare function readExpiringJsonCache(file: string): Promise<any>;
23
28
  export declare function writeExpiringJsonCache(file: string, data: any, { expireAfter, // cache for 1 day by default
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.writeExpiringJsonCache = exports.readExpiringJsonCache = exports.deleteCache = exports.getTempLocalCache = exports.compressCache = exports.parseCache = exports.writeCache = exports.readCache = exports.currentVersion = void 0;
3
+ exports.writeExpiringJsonCache = exports.readExpiringJsonCache = exports.deleteCache = exports.getTempLocalCache = exports.ONE_WEEK = exports.compressCache = exports.parseCache = exports.writeCache = exports.readCache = exports.currentVersion = void 0;
4
4
  const debugLog_1 = require("./debugLog");
5
5
  const r2_1 = require("./r2");
6
6
  const zlib_1 = require("zlib");
@@ -122,14 +122,13 @@ exports.compressCache = compressCache;
122
122
  function isSameData(data1, data2) {
123
123
  return JSON.stringify(data1) === JSON.stringify(data2);
124
124
  }
125
- const ONE_WEEK = 1000 * 60 * 60 * 24 * 7;
126
- function getTempLocalCache({ file, defaultData = {}, clearAfter = ONE_WEEK }) {
127
- let cache = defaultData;
125
+ exports.ONE_WEEK = 1000 * 60 * 60 * 24 * 7;
126
+ function getTempLocalCache({ file, defaultData = {}, clearAfter = exports.ONE_WEEK, returnWithSaveFunction = false }) {
128
127
  const now = Math.floor(Date.now() / 1e3);
129
128
  let emptyFile = { created: now, data: defaultData };
130
129
  let fileData = emptyFile;
131
130
  const filePath = getFilePath(file);
132
- let saveCacheFlag = false;
131
+ let saveCacheFlag = false; // to ensure that we save only once on exit
133
132
  createSubPath(path.dirname(filePath)); // create folder if not exists, this is async but we don't care
134
133
  try {
135
134
  const data = _fs.readFileSync(filePath);
@@ -139,15 +138,28 @@ function getTempLocalCache({ file, defaultData = {}, clearAfter = ONE_WEEK }) {
139
138
  }
140
139
  catch (error) { }
141
140
  // save cache on exit
142
- process.on('exit', saveCache);
143
- process.on('SIGTERM', saveCache);
144
- process.on('SIGINT', saveCache);
141
+ process.on('exit', _save);
142
+ process.on('SIGTERM', _save);
143
+ process.on('SIGINT', _save);
144
+ if (returnWithSaveFunction) {
145
+ return {
146
+ data: fileData.data,
147
+ saveCacheFile: () => saveCache(true)
148
+ };
149
+ }
145
150
  return fileData.data;
146
- function saveCache() {
147
- if (saveCacheFlag)
148
- return;
149
- saveCacheFlag = true;
151
+ function _save() {
152
+ saveCache();
153
+ }
154
+ function saveCache(skipCacheFlagCheck = false) {
155
+ if (!skipCacheFlagCheck) {
156
+ if (saveCacheFlag)
157
+ return;
158
+ saveCacheFlag = true;
159
+ }
150
160
  try {
161
+ if (!skipCacheFlagCheck)
162
+ (0, debugLog_1.debugLog)('Saving cache to file:', filePath);
151
163
  removePromisesAndFunctions(fileData);
152
164
  _fs.writeFileSync(filePath, JSON.stringify(fileData));
153
165
  }
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.addErrorLog = exports.addRuntimeLog = exports.addDebugLog = exports.writeLog = exports.getClient = void 0;
4
4
  const elasticsearch_1 = require("@elastic/elasticsearch");
5
5
  const env_1 = require("./env");
6
+ const debugLog_1 = require("./debugLog");
6
7
  let _client;
7
8
  function getClient() {
8
9
  if (_client)
@@ -41,7 +42,7 @@ async function writeLog(index, log) {
41
42
  await client.index({ index, body: log });
42
43
  }
43
44
  catch (error) {
44
- console.error(error);
45
+ (0, debugLog_1.debugLog)((error === null || error === void 0 ? void 0 : error.message) || 'Error writing log to Elasticsearch');
45
46
  }
46
47
  }
47
48
  exports.writeLog = writeLog;
@@ -5,7 +5,7 @@ export interface GetTransactionOptions {
5
5
  transaction_hashes?: string[];
6
6
  limit?: number | 'all';
7
7
  offset?: number;
8
- chain: string;
8
+ chain?: string;
9
9
  all?: boolean;
10
10
  debugMode?: boolean;
11
11
  transactionType?: 'from' | 'to' | 'all';
@@ -115,6 +115,7 @@ const chainShortNameMapping = {
115
115
  ontology: 'OntologyMainnet',
116
116
  occ: 'edu_chain',
117
117
  hyperliquid: 'hyper_evm',
118
+ nibiru: 'cataclysm_1',
118
119
  elsm: 'ely',
119
120
  };
120
121
  async function filterForWorkingRPCs(rpc, chain, chainId) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defillama/sdk",
3
- "version": "5.0.142",
3
+ "version": "5.0.144",
4
4
  "description": "SDK for calculating TVL",
5
5
  "main": "build/index.js",
6
6
  "scripts": {