@defillama/sdk 5.0.236 → 5.0.240

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 (131) hide show
  1. package/package.json +3 -3
  2. package/build/Balances.d.ts +0 -139
  3. package/build/Balances.js +0 -363
  4. package/build/ChainApi.d.ts +0 -142
  5. package/build/ChainApi.js +0 -297
  6. package/build/abi/abi2.d.ts +0 -5
  7. package/build/abi/abi2.js +0 -215
  8. package/build/abi/cachedABIs.d.ts +0 -4
  9. package/build/abi/cachedABIs.js +0 -8
  10. package/build/abi/convertResults.d.ts +0 -5
  11. package/build/abi/convertResults.js +0 -60
  12. package/build/abi/index.d.ts +0 -31
  13. package/build/abi/index.js +0 -327
  14. package/build/abi/multicall.d.ts +0 -23
  15. package/build/abi/multicall.js +0 -382
  16. package/build/abi/multicall3.d.ts +0 -7
  17. package/build/abi/multicall3.js +0 -397
  18. package/build/abi/rpcCall.d.ts +0 -4
  19. package/build/abi/rpcCall.js +0 -62
  20. package/build/abi/tron.d.ts +0 -33
  21. package/build/abi/tron.js +0 -110
  22. package/build/api.d.ts +0 -10
  23. package/build/api.js +0 -45
  24. package/build/api2.d.ts +0 -5
  25. package/build/api2.js +0 -41
  26. package/build/chains/algorand.d.ts +0 -277
  27. package/build/chains/algorand.js +0 -618
  28. package/build/chains/aptos.d.ts +0 -230
  29. package/build/chains/aptos.js +0 -612
  30. package/build/chains/cardano.d.ts +0 -242
  31. package/build/chains/cardano.js +0 -407
  32. package/build/chains/cosmos.d.ts +0 -252
  33. package/build/chains/cosmos.js +0 -618
  34. package/build/chains/icp.d.ts +0 -235
  35. package/build/chains/icp.js +0 -1040
  36. package/build/chains/index.d.ts +0 -23
  37. package/build/chains/index.js +0 -59
  38. package/build/chains/near.d.ts +0 -192
  39. package/build/chains/near.js +0 -446
  40. package/build/chains/rpc.d.ts +0 -125
  41. package/build/chains/rpc.js +0 -326
  42. package/build/chains/starknet.d.ts +0 -205
  43. package/build/chains/starknet.js +0 -884
  44. package/build/chains/stellar.d.ts +0 -410
  45. package/build/chains/stellar.js +0 -1082
  46. package/build/chains/substrate.d.ts +0 -333
  47. package/build/chains/substrate.js +0 -1042
  48. package/build/chains/sui.d.ts +0 -365
  49. package/build/chains/sui.js +0 -1135
  50. package/build/chains/svm.d.ts +0 -340
  51. package/build/chains/svm.js +0 -760
  52. package/build/chains/tezos.d.ts +0 -225
  53. package/build/chains/tezos.js +0 -412
  54. package/build/chains/ton.d.ts +0 -353
  55. package/build/chains/ton.js +0 -788
  56. package/build/chains/tron.d.ts +0 -45
  57. package/build/chains/tron.js +0 -110
  58. package/build/chains/utxo.d.ts +0 -202
  59. package/build/chains/utxo.js +0 -592
  60. package/build/chains/xrpl.d.ts +0 -179
  61. package/build/chains/xrpl.js +0 -467
  62. package/build/computeTVL/blocks.d.ts +0 -1
  63. package/build/computeTVL/blocks.js +0 -12
  64. package/build/computeTVL/humanizeNumber.d.ts +0 -1
  65. package/build/computeTVL/humanizeNumber.js +0 -19
  66. package/build/erc20/index.d.ts +0 -31
  67. package/build/erc20/index.js +0 -56
  68. package/build/eth/index.d.ts +0 -22
  69. package/build/eth/index.js +0 -118
  70. package/build/general.d.ts +0 -5
  71. package/build/general.js +0 -20
  72. package/build/generalUtil.d.ts +0 -8
  73. package/build/generalUtil.js +0 -73
  74. package/build/index.d.ts +0 -32
  75. package/build/index.js +0 -74
  76. package/build/providers.json +0 -1
  77. package/build/types.d.ts +0 -76
  78. package/build/types.js +0 -2
  79. package/build/util/LlamaProvider.d.ts +0 -46
  80. package/build/util/LlamaProvider.js +0 -365
  81. package/build/util/blocks.d.ts +0 -36
  82. package/build/util/blocks.js +0 -292
  83. package/build/util/cache.d.ts +0 -45
  84. package/build/util/cache.js +0 -309
  85. package/build/util/chainUtils/data.json +0 -1356
  86. package/build/util/chainUtils/index.d.ts +0 -11
  87. package/build/util/chainUtils/index.js +0 -136
  88. package/build/util/coins.d.ts +0 -19
  89. package/build/util/coins.js +0 -113
  90. package/build/util/common.d.ts +0 -34
  91. package/build/util/common.js +0 -373
  92. package/build/util/computeTVL.d.ts +0 -19
  93. package/build/util/computeTVL.js +0 -102
  94. package/build/util/cosmos.d.ts +0 -1
  95. package/build/util/cosmos.js +0 -8
  96. package/build/util/debugLog.d.ts +0 -4
  97. package/build/util/debugLog.js +0 -18
  98. package/build/util/discord.d.ts +0 -1
  99. package/build/util/discord.js +0 -33
  100. package/build/util/elastic.d.ts +0 -43
  101. package/build/util/elastic.js +0 -113
  102. package/build/util/env.d.ts +0 -19
  103. package/build/util/env.js +0 -158
  104. package/build/util/graph.d.ts +0 -8
  105. package/build/util/graph.js +0 -50
  106. package/build/util/index.d.ts +0 -32
  107. package/build/util/index.js +0 -227
  108. package/build/util/indexer.compatibility.d.ts +0 -6
  109. package/build/util/indexer.compatibility.js +0 -64
  110. package/build/util/indexer.d.ts +0 -92
  111. package/build/util/indexer.js +0 -744
  112. package/build/util/indexerSql.d.ts +0 -9
  113. package/build/util/indexerSql.js +0 -102
  114. package/build/util/internal-cache.d.ts +0 -11
  115. package/build/util/internal-cache.js +0 -77
  116. package/build/util/logs.d.ts +0 -55
  117. package/build/util/logs.decode.shared.d.ts +0 -8
  118. package/build/util/logs.decode.shared.js +0 -289
  119. package/build/util/logs.js +0 -401
  120. package/build/util/promisePool.d.ts +0 -8
  121. package/build/util/promisePool.js +0 -31
  122. package/build/util/r2.d.ts +0 -4
  123. package/build/util/r2.js +0 -52
  124. package/build/util/removeRedundantRPCs.d.ts +0 -1
  125. package/build/util/removeRedundantRPCs.js +0 -49
  126. package/build/util/transactions.d.ts +0 -35
  127. package/build/util/transactions.js +0 -22
  128. package/build/util/updateChainLabels.d.ts +0 -1
  129. package/build/util/updateChainLabels.js +0 -5
  130. package/build/util/updateProviderList.d.ts +0 -1
  131. package/build/util/updateProviderList.js +0 -274
@@ -1,373 +0,0 @@
1
- "use strict";
2
- // keep no dependency here else it will create circular dependencies
3
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
- if (k2 === undefined) k2 = k;
5
- var desc = Object.getOwnPropertyDescriptor(m, k);
6
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
- desc = { enumerable: true, get: function() { return m[k]; } };
8
- }
9
- Object.defineProperty(o, k2, desc);
10
- }) : (function(o, m, k, k2) {
11
- if (k2 === undefined) k2 = k;
12
- o[k2] = m[k];
13
- }));
14
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
- Object.defineProperty(o, "default", { enumerable: true, value: v });
16
- }) : function(o, v) {
17
- o["default"] = v;
18
- });
19
- var __importStar = (this && this.__importStar) || (function () {
20
- var ownKeys = function(o) {
21
- ownKeys = Object.getOwnPropertyNames || function (o) {
22
- var ar = [];
23
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
- return ar;
25
- };
26
- return ownKeys(o);
27
- };
28
- return function (mod) {
29
- if (mod && mod.__esModule) return mod;
30
- var result = {};
31
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
- __setModuleDefault(result, mod);
33
- return result;
34
- };
35
- })();
36
- var __importDefault = (this && this.__importDefault) || function (mod) {
37
- return (mod && mod.__esModule) ? mod : { "default": mod };
38
- };
39
- Object.defineProperty(exports, "__esModule", { value: true });
40
- exports.convertToBigInt = convertToBigInt;
41
- exports.sumMultiBalanceOf = sumMultiBalanceOf;
42
- exports.sumSingleBalance = sumSingleBalance;
43
- exports.mergeBalances = mergeBalances;
44
- exports.removeTokenBalance = removeTokenBalance;
45
- exports.sumChainTvls = sumChainTvls;
46
- exports.getUniqueAddresses = getUniqueAddresses;
47
- exports.getProviderUrl = getProviderUrl;
48
- exports.formErrorString = formErrorString;
49
- exports.shortenString = shortenString;
50
- exports.formError = formError;
51
- exports.fetchJson = fetchJson;
52
- exports.postJson = postJson;
53
- exports.tronToEvmAddress = tronToEvmAddress;
54
- exports.evmToTronAddress = evmToTronAddress;
55
- exports.sleep = sleep;
56
- exports.sleepRandom = sleepRandom;
57
- exports.fixTronCallParams = fixTronCallParams;
58
- exports.getHash = getHash;
59
- const axios_1 = __importStar(require("axios"));
60
- const ethers = __importStar(require("ethers"));
61
- const TronAddressFormatter = __importStar(require("tron-format-address"));
62
- const env_1 = require("./env");
63
- const crypto_1 = __importDefault(require("crypto"));
64
- function convertToBigInt(value) {
65
- const balance = value;
66
- if (!value)
67
- return BigInt(0);
68
- if (typeof value === 'bigint')
69
- return value;
70
- if (typeof value === 'number')
71
- value = value.toString();
72
- if (typeof value === 'string') {
73
- if (!value.startsWith('0x') && value.includes('e')) { // Convert scientific notation to standard notation
74
- let [base, e] = value.split('e');
75
- const [lead, decimal] = base.split('.');
76
- let final;
77
- let exponent = +e;
78
- if (exponent >= 0) {
79
- final = lead + (decimal || '') + '0'.repeat(exponent - (decimal || '').length);
80
- }
81
- else {
82
- // NOTE: unforutenately BigInt doesn't support negative exponents, so this ends up being 0
83
- exponent = exponent * -1;
84
- final = BigInt(lead) / BigInt('1' + Array(exponent).fill(0).join(''));
85
- }
86
- return BigInt(final);
87
- }
88
- return BigInt(value);
89
- }
90
- if (typeof value === 'string')
91
- return BigInt(value);
92
- throw new Error(`Invalid balance: ${balance}`);
93
- }
94
- function sumMultiBalanceOf(balances, results, allCallsMustBeSuccessful = true, transformAddress = (addr) => addr) {
95
- results.output.map((result) => {
96
- var _a;
97
- if (result.success) {
98
- const address = transformAddress(result.input.target);
99
- const balance = result.output;
100
- if (BigInt(balance) <= 0) {
101
- return;
102
- }
103
- balances[address] = (BigInt((_a = balances[address]) !== null && _a !== void 0 ? _a : 0) + BigInt(balance)).toString();
104
- }
105
- else if (allCallsMustBeSuccessful) {
106
- console.error(result);
107
- throw new Error(`balanceOf multicall failed`);
108
- }
109
- });
110
- }
111
- function sumSingleBalance(balances, token, balance, chain) {
112
- if (typeof balance === 'bigint')
113
- balance = balance.toString();
114
- isValidNumber(balance);
115
- if (+balance === 0)
116
- return;
117
- if (chain)
118
- token = `${chain}:${token}`;
119
- if (typeof balance === 'object') {
120
- if (typeof balance.toString === 'function')
121
- balance = balance.toString();
122
- else
123
- throw new Error('Invalid balance value:' + balance + ' ' + token);
124
- }
125
- if (!token || token.trim() === '') {
126
- throw new Error('Missing token address/symbol');
127
- }
128
- if (typeof balance === 'number' || (balances[token] && typeof balances[token] === 'number')) {
129
- const prevBalance = +(balances.hasOwnProperty(token) ? balances[token] : 0);
130
- if (typeof prevBalance !== 'number' || isNaN(prevBalance))
131
- throw new Error(`Trying to merge token balance and coingecko amount for ${token} current balance: ${balance} previous balance: ${balances[token]}`);
132
- const value = prevBalance + +balance;
133
- isValidNumber(value);
134
- balances[token] = value;
135
- }
136
- else {
137
- const prevBalance = convertToBigInt(balances[token]);
138
- const value = (prevBalance + convertToBigInt(balance));
139
- isValidNumber(value);
140
- balances[token] = value.toString();
141
- }
142
- function isValidNumber(value) {
143
- if (typeof value === 'bigint')
144
- return;
145
- if ([null, undefined].includes(value) || isNaN(+value))
146
- throw new Error(`Invalid balance: ${balance} - ${token}`);
147
- }
148
- }
149
- function mergeBalances(balances, balancesToMerge) {
150
- if (balances === balancesToMerge)
151
- return;
152
- Object.entries(balancesToMerge).forEach((balance) => {
153
- sumSingleBalance(balances, balance[0], balance[1]);
154
- });
155
- }
156
- function removeTokenBalance(balances, token, isCaseSensitive = false) {
157
- const re = new RegExp(token, isCaseSensitive ? undefined : 'i');
158
- Object.keys(balances).forEach(key => {
159
- if (re.test(key))
160
- delete balances[key];
161
- });
162
- return balances;
163
- }
164
- function sumChainTvls(chainTvls) {
165
- return async (timestamp, ethBlock, chainBlocks, params) => {
166
- const api = params.api;
167
- await Promise.all(chainTvls.map(async (chainTvl) => {
168
- const chainBalances = await chainTvl(timestamp, ethBlock, chainBlocks, params);
169
- api.addBalances(chainBalances);
170
- }));
171
- return api.getBalances();
172
- };
173
- }
174
- function getUniqueAddresses(addresses, chain) {
175
- if (!addresses.length)
176
- return [];
177
- const isTronChain = chain === 'tron';
178
- const set = {};
179
- addresses.forEach(i => set[isTronChain && i.includes('T') ? i : i.toLowerCase()] = true);
180
- return Object.keys(set);
181
- }
182
- function getProviderUrl(provider) {
183
- if (provider === null || provider === void 0 ? void 0 : provider.isCustomLlamaProvider)
184
- return provider.rpcs.map((i) => i.url).join(', ');
185
- if (provider instanceof ethers.FallbackProvider)
186
- provider = provider.providerConfigs[0].provider;
187
- if (provider instanceof ethers.JsonRpcProvider)
188
- return provider._getConnection().url;
189
- return '';
190
- }
191
- function formErrorString(e, errorParams = {}) {
192
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4;
193
- if (e instanceof axios_1.AxiosError) {
194
- let message = `[host: ${shortenString((_b = (_a = e === null || e === void 0 ? void 0 : e.config) === null || _a === void 0 ? void 0 : _a.url) !== null && _b !== void 0 ? _b : '', 120)}] `;
195
- // if (e?.config?.method === 'post' && e?.config?.data)
196
- // message += shortenString(`method: POST data: ${e?.config?.data} `)
197
- if ((_c = e === null || e === void 0 ? void 0 : e.response) === null || _c === void 0 ? void 0 : _c.data) {
198
- if (e.response.status)
199
- message += `[${e.response.status}] `;
200
- let dataString = shortenString(JSON.stringify(e.response.data));
201
- if (typeof e.response.data === 'object') {
202
- if ((_d = e.response.data.error) === null || _d === void 0 ? void 0 : _d.message)
203
- dataString = shortenString('' + e.response.data.error.message);
204
- else if (e.response.data.message)
205
- dataString = shortenString('' + e.response.data.message);
206
- }
207
- if (dataString.startsWith('"<!DOCTYPE html>') || dataString.startsWith('"<html'))
208
- dataString = 'HTML error page';
209
- message += dataString;
210
- return message;
211
- }
212
- if (e === null || e === void 0 ? void 0 : e.message)
213
- return shortenString(message + e.message);
214
- }
215
- const isGraphError = typeof e === 'object' && ((_e = e === null || e === void 0 ? void 0 : e.stack) === null || _e === void 0 ? void 0 : _e.includes('graphql-request')) && ((_g = (_f = e.response) === null || _f === void 0 ? void 0 : _f.errors) === null || _g === void 0 ? void 0 : _g.length);
216
- if (isGraphError)
217
- return shortenString(`GraphQL request failed! ${e.response.errors.map((i) => i.message).join(', ')}`);
218
- if (!e) {
219
- if (errorParams.promisePoolErrors) {
220
- const errors = errorParams.promisePoolErrors.map((i) => formErrorString(i));
221
- return `Promise pool failed! \n ${errors.join('\n')}`;
222
- }
223
- if (errorParams.isMultiCallError) {
224
- const targetStr = errorParams.target ? `[target: ${errorParams.target}]` : '';
225
- let errorString = `Multicall failed! \n [chain: ${(_h = errorParams.chain) !== null && _h !== void 0 ? _h : "ethereum"}] [fail count: ${(_j = errorParams.failedQueries) === null || _j === void 0 ? void 0 : _j.length}] [abi: ${errorParams.abi}] ${targetStr} `;
226
- (_k = errorParams.failedQueries) === null || _k === void 0 ? void 0 : _k.forEach((i) => {
227
- i = i.input;
228
- let target = !targetStr ? ` target: ${i.target}` : '';
229
- let params = i.params && i.params.length ? `params: ${i.params.length === 1 ? i.params[0] : i.params.join(', ')}]` : '';
230
- errorString += `\n ${target} ${params}`;
231
- });
232
- // truncate error string to 310 chars
233
- return errorString.length > 310 ? errorString.slice(0, 310).concat('...') : errorString;
234
- }
235
- return '';
236
- }
237
- if (e.llamaRPCError) {
238
- const errorString = `Llama RPC error! method: ${e.method} `;
239
- const errors = e.errors.map((i) => { var _a; return `- host: ${i === null || i === void 0 ? void 0 : i.host} error: ${typeof (i === null || i === void 0 ? void 0 : i.error) === 'string' ? i === null || i === void 0 ? void 0 : i.error : (_a = i === null || i === void 0 ? void 0 : i.error) === null || _a === void 0 ? void 0 : _a.message}`; });
240
- return errorString + '\n' + errors.join('\n');
241
- }
242
- let errorString = e.toString();
243
- if (typeof e !== 'object')
244
- return errorString;
245
- if (((e.reason || e.method || e.shortMessage) && e.code) || errorParams.result === '0x') { // ethers.js error
246
- const errorMessage = (_s = (_r = (_q = (_p = (_o = (_m = (_l = e.info) === null || _l === void 0 ? void 0 : _l.error) === null || _m === void 0 ? void 0 : _m.message) !== null && _o !== void 0 ? _o : e.message) !== null && _p !== void 0 ? _p : e.shortMessage) !== null && _q !== void 0 ? _q : e.errorName) !== null && _r !== void 0 ? _r : e.reason) !== null && _s !== void 0 ? _s : '';
247
- let method = (_w = (_t = e.method) !== null && _t !== void 0 ? _t : (_v = (_u = e.info) === null || _u === void 0 ? void 0 : _u.request) === null || _v === void 0 ? void 0 : _v.method) !== null && _w !== void 0 ? _w : errorParams.abi;
248
- if (e.body) {
249
- try {
250
- e.body = JSON.parse(e.body);
251
- }
252
- catch (e) { }
253
- if ((_y = (_x = e.body) === null || _x === void 0 ? void 0 : _x.error) === null || _y === void 0 ? void 0 : _y.message)
254
- return e.body.error.message;
255
- }
256
- if (!method && e.requestBody) {
257
- try {
258
- e.requestBody = JSON.parse(e.requestBody);
259
- }
260
- catch (e) { }
261
- method = (_z = e.requestBody) === null || _z === void 0 ? void 0 : _z.method;
262
- }
263
- else if (!e.provider && errorParams.provider)
264
- e.provider = errorParams.provider;
265
- let providerUrl = getProviderUrl((_0 = e.provider) !== null && _0 !== void 0 ? _0 : errorParams.provider);
266
- if (e.serverError)
267
- return `host: ${providerUrl} ${e.serverError.toString()}`;
268
- if (e.results) {
269
- let errors = e.results.filter((i) => i.error).map((i) => i.error);
270
- if (errors.length) {
271
- const eStrings = errors.map((i) => formError(i));
272
- return `Failed to call method: ${method} provider: ${providerUrl}
273
- ${eStrings.join('\n')}`;
274
- }
275
- }
276
- else if (e.code === 'CALL_EXCEPTION' || errorParams.isCallError) {
277
- let extraInfo = 'target: ' + errorParams.target;
278
- if (errorParams.params && Array.isArray(errorParams.params) && errorParams.params.length)
279
- extraInfo += shortenString(' params: ' + errorParams.params.join(', '));
280
- return `Failed to call: ${method} ${extraInfo} on chain: [${errorParams.chain}] rpc: ${providerUrl} call reverted, reason: ${errorMessage} ${(_1 = e.errorArgs) !== null && _1 !== void 0 ? _1 : ''}`;
281
- }
282
- else if (e.code === 'BAD_DATA') {
283
- if (!method)
284
- method = (_3 = (_2 = e === null || e === void 0 ? void 0 : e.info) === null || _2 === void 0 ? void 0 : _2.payload) === null || _3 === void 0 ? void 0 : _3.method;
285
- let extraInfo = 'target: ' + errorParams.target;
286
- return `Failed method: ${method} ${shortenString(extraInfo)} on chain: [${errorParams.chain}] rpc: ${providerUrl} reason: ${errorMessage} ${(_4 = e.errorArgs) !== null && _4 !== void 0 ? _4 : ''}`;
287
- }
288
- if (method === 'eth_blockNumber')
289
- return `host: ${providerUrl} reason: ${e.reason} code: ${e.code}`;
290
- if (method === 'getBlockNumber')
291
- return `Failed to call ${method} ${providerUrl} reason: ${e.reason} code: ${e.code}`;
292
- return `Failed to call ${method} on ${providerUrl} reason: ${e.reason} code: ${e.code}`;
293
- }
294
- return errorString;
295
- }
296
- function shortenString(str, length) {
297
- if (!length) {
298
- if (!isNaN(+env_1.ENV_CONSTANTS.DEFAULT_SHORTEN_STRING_LENGTH))
299
- length = +env_1.ENV_CONSTANTS.DEFAULT_SHORTEN_STRING_LENGTH;
300
- if (!length || isNaN(length))
301
- length = 120;
302
- }
303
- return str.length > length ? str.slice(0, length).concat('...') : str;
304
- }
305
- function formError(e, errorParams = {}) {
306
- var _a;
307
- if (e instanceof Error && (0, env_1.getBoolEnvValue)('DEBUG_ERROR_STACK')) {
308
- console.error(e);
309
- }
310
- const errorParamsSet = Object.keys(errorParams).length;
311
- if ((e === null || e === void 0 ? void 0 : e._isCustomError) || (!errorParamsSet && typeof e === 'object' && !Object.keys(e).length))
312
- return e; // already formatted or vannila error
313
- const error = new Error(formErrorString(e, errorParams));
314
- try {
315
- if (errorParams.isMultiCallError)
316
- error._underlyingErrors = (_a = errorParams === null || errorParams === void 0 ? void 0 : errorParams.failedQueries) === null || _a === void 0 ? void 0 : _a.map((i) => shortenString(i.error.toString()));
317
- else
318
- error._underlyingError = shortenString(e.toString());
319
- }
320
- catch (e) { }
321
- error._isCustomError = true;
322
- error.message = shortenString(error.message, 2999);
323
- error.stack = '';
324
- return error;
325
- }
326
- async function fetchJson(url, params = {}) {
327
- const res = await (0, axios_1.default)(url, params).catch(e => { throw formError(e); });
328
- return res.data;
329
- }
330
- async function postJson(url, data = {}, params = {}) {
331
- const res = await axios_1.default.post(url, data, params).catch(e => { throw formError(e); });
332
- return res.data;
333
- }
334
- function tronToEvmAddress(address) {
335
- if (!address.startsWith('0x'))
336
- return TronAddressFormatter.toHex(address);
337
- return address;
338
- }
339
- function evmToTronAddress(address) {
340
- if (address.startsWith('0x'))
341
- return TronAddressFormatter.fromHex(address);
342
- return address;
343
- }
344
- function sleep(ms) {
345
- return new Promise((resolve) => setTimeout(resolve, ms));
346
- }
347
- async function sleepRandom(max, min = 0) {
348
- const ms = Math.floor(Math.random() * (max - min + 1)) + min;
349
- return sleep(ms);
350
- }
351
- // convert all the tron addresses in the params to evm addresses (from Txxx to 0x...)
352
- function fixTronCallParams(params) {
353
- const wrappedHexify = (v) => {
354
- if (typeof v === 'string' && v.startsWith('T'))
355
- return tronToEvmAddress(v);
356
- return v;
357
- };
358
- if (typeof params === 'object') {
359
- if (params.target)
360
- params.target = tronToEvmAddress(params.target);
361
- if (Array.isArray(params.params))
362
- params.params = params.params.map(wrappedHexify);
363
- if (typeof params.params === 'string')
364
- params.params = wrappedHexify(params.params);
365
- }
366
- if (Array.isArray(params.calls))
367
- params.calls.forEach(fixTronCallParams);
368
- }
369
- function getHash(str) {
370
- if (Array.isArray(str))
371
- str = str.join('-');
372
- return crypto_1.default.createHash('sha256').update(str).digest('hex').substring(0, 32);
373
- }
@@ -1,19 +0,0 @@
1
- import { Balances } from "../types";
2
- export default function computeTVL(balances: Balances, timestamp?: number, { debug }?: {
3
- debug?: boolean;
4
- }): Promise<{
5
- usdTvl: number;
6
- usdTokenBalances: Balances;
7
- debugData: {
8
- tokenData: {
9
- balance: string | number;
10
- price: number;
11
- decimals: number;
12
- value: number;
13
- confidence: number;
14
- token: string;
15
- symbol: string;
16
- }[];
17
- };
18
- }>;
19
- export declare function getUnique(addresses: string[]): string[];
@@ -1,102 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.default = computeTVL;
4
- exports.getUnique = getUnique;
5
- const generalUtil_1 = require("../generalUtil");
6
- const coins_1 = require("./coins");
7
- const currentPriceCache = {};
8
- const priceCaches = {};
9
- let lastPriceUpdate = 0;
10
- const confidenceThreshold = 0.5;
11
- const priceUpdateTime = 1000 * 60 * 30; // 30 minutes
12
- async function computeTVL(balances, timestamp, { debug = false } = {}) {
13
- const usdTokenBalances = {};
14
- const debugData = {
15
- tokenData: []
16
- };
17
- let usdTvl = 0;
18
- const keys = Object.keys(balances)
19
- // .filter(i => +balances[i] > 0)
20
- .filter(i => +balances[i] !== 0)
21
- .map(tokenToKey);
22
- await updatePriceCache(keys, timestamp);
23
- const priceCache = getPriceCache(timestamp);
24
- Object.entries(balances).forEach(([token, balance]) => {
25
- var _a;
26
- // if (+balance <= 0) return;
27
- if (+balance === 0)
28
- return;
29
- if (!token || token.trim() === '') {
30
- return;
31
- }
32
- const key = tokenToKey(token).toLowerCase();
33
- let { price, confidence, decimals = 0, symbol = token } = (_a = priceCache[key]) !== null && _a !== void 0 ? _a : {};
34
- if (!price || confidence < confidenceThreshold)
35
- return;
36
- const value = +balance * price / (10 ** decimals);
37
- usdTvl += value;
38
- if (symbol === 'ETH')
39
- symbol = 'WETH';
40
- if (!symbol || symbol.trim() === '')
41
- symbol = '-';
42
- (0, generalUtil_1.sumSingleBalance)(usdTokenBalances, symbol, value);
43
- if (debug && !isNaN(+value))
44
- debugData.tokenData.push({ symbol, value, token, price, confidence, balance, decimals, });
45
- });
46
- return { usdTvl, usdTokenBalances, debugData, };
47
- }
48
- function tokenToKey(token) {
49
- if (token.startsWith("0x"))
50
- token = `ethereum:${token}`;
51
- else if (!token.includes(':'))
52
- token = `coingecko:${token}`;
53
- return token;
54
- }
55
- async function updatePriceCache(keys, timestamp) {
56
- keys = getUnique(keys);
57
- const pricesCache = getPriceCache(timestamp);
58
- if (isNearlyNow(timestamp))
59
- timestamp = undefined; // if timestamp is close to now, pull current token prices
60
- if (!timestamp && lastPriceUpdate && +Date.now() > lastPriceUpdate + priceUpdateTime) {
61
- lastPriceUpdate = +Date.now();
62
- Object.keys(pricesCache).forEach(key => delete pricesCache[key]); // clear cache
63
- }
64
- // hardcode cache for USDT
65
- pricesCache['coingecko:tether'] = {
66
- "price": 1,
67
- "symbol": "USDT",
68
- "confidence": 1
69
- };
70
- pricesCache['ethereum:0xdac17f958d2ee523a2206206994597c13d831ec7'] = {
71
- "price": 1,
72
- "symbol": "USDT",
73
- "decimals": 6,
74
- "confidence": 1
75
- };
76
- const missingKeys = keys.filter(key => !pricesCache[key.toLowerCase()]);
77
- const coins = await (0, coins_1.getPrices)(missingKeys, timestamp !== null && timestamp !== void 0 ? timestamp : "now");
78
- for (const [token, data] of Object.entries(coins)) {
79
- pricesCache[token.toLowerCase()] = data;
80
- }
81
- missingKeys.map(i => i.toLowerCase()).filter(i => !pricesCache[i]).forEach(i => pricesCache[i] = {});
82
- }
83
- function getPriceCache(timestamp) {
84
- if (timestamp)
85
- timestamp = getClosestHourlyTimestamp(timestamp);
86
- if (timestamp && !priceCaches[timestamp])
87
- priceCaches[timestamp] = {};
88
- return timestamp ? priceCaches[timestamp] : currentPriceCache;
89
- }
90
- function getUnique(addresses) {
91
- const set = {};
92
- addresses.forEach(i => set[i] = true);
93
- return Object.keys(set);
94
- }
95
- function isNearlyNow(timestamp) {
96
- if (!timestamp)
97
- return true;
98
- return Math.abs(timestamp - +Date.now() / 1000) < 60 * 60;
99
- }
100
- function getClosestHourlyTimestamp(timestamp) {
101
- return Math.floor(timestamp / 3600) * 3600;
102
- }
@@ -1 +0,0 @@
1
- export { isCosmosChain, getCosmosBlock, getCosmosProvider } from "../chains/cosmos";
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getCosmosProvider = exports.getCosmosBlock = exports.isCosmosChain = void 0;
4
- // Kept for backwards compatibility, the implementation lives in ../chains/cosmos
5
- var cosmos_1 = require("../chains/cosmos");
6
- Object.defineProperty(exports, "isCosmosChain", { enumerable: true, get: function () { return cosmos_1.isCosmosChain; } });
7
- Object.defineProperty(exports, "getCosmosBlock", { enumerable: true, get: function () { return cosmos_1.getCosmosBlock; } });
8
- Object.defineProperty(exports, "getCosmosProvider", { enumerable: true, get: function () { return cosmos_1.getCosmosProvider; } });
@@ -1,4 +0,0 @@
1
- export declare const DEBUG_ENABLED: boolean;
2
- export declare const DEBUG_LEVEL2: boolean;
3
- export declare function debugLog(...args: any): void;
4
- export declare function debugTable(...args: any): void;
@@ -1,18 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DEBUG_LEVEL2 = exports.DEBUG_ENABLED = void 0;
4
- exports.debugLog = debugLog;
5
- exports.debugTable = debugTable;
6
- const env_1 = require("./env");
7
- exports.DEBUG_ENABLED = env_1.ENV_CONSTANTS.DEBUG_ENABLED === "true";
8
- exports.DEBUG_LEVEL2 = env_1.ENV_CONSTANTS.DEBUG_LEVEL2 === "true";
9
- function debugLog(...args) {
10
- if (!exports.DEBUG_ENABLED && !exports.DEBUG_LEVEL2)
11
- return;
12
- console.log(...args);
13
- }
14
- function debugTable(...args) {
15
- if (!exports.DEBUG_ENABLED && !exports.DEBUG_LEVEL2)
16
- return;
17
- console.table(...args);
18
- }
@@ -1 +0,0 @@
1
- export declare function sendMessage(message: string, webhookUrl: string | undefined, formatted?: boolean): Promise<void>;
@@ -1,33 +0,0 @@
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.sendMessage = sendMessage;
7
- const axios_1 = __importDefault(require("axios"));
8
- async function sendMessage(message, webhookUrl, formatted = true) {
9
- if (webhookUrl === undefined) {
10
- throw new Error(`You are missing an env variable for discord hooks (eg TEAM_WEBHOOK, OUTDATED_WEBHOOK, SPIKE_WEBHOOK...) and this makes it impossible to send the following error message: "${message}"`);
11
- }
12
- const formattedMessage = formatted ? "```\n" + message + "\n```" : message; // Put it into a code block to prevent the format from getting messed up
13
- if (formattedMessage.length >= 2000) {
14
- const lines = message.split('\n');
15
- if (lines.length <= 2) {
16
- throw new Error("Lines are too long, reaching infinite recursivity");
17
- }
18
- const mid = Math.round(lines.length / 2);
19
- await sendMessage(lines.slice(0, mid).join('\n'), webhookUrl);
20
- await sendMessage(lines.slice(mid).join('\n'), webhookUrl);
21
- return;
22
- }
23
- // Example: https://gist.github.com/dragonwocky/ea61c8d21db17913a43da92efe0de634
24
- // Docs: https://gist.github.com/dragonwocky/ea61c8d21db17913a43da92efe0de634
25
- await axios_1.default.post(`${webhookUrl}?wait=true`, {
26
- content: formattedMessage
27
- }, {
28
- headers: {
29
- 'Content-Type': 'application/json',
30
- }
31
- }).then((body) => body.data);
32
- // console.log("discord", response)
33
- }
@@ -1,43 +0,0 @@
1
- import { Client } from '@elastic/elasticsearch';
2
- export declare function getClient(): Client | undefined;
3
- export declare function writeLog(index: string, log: {
4
- [key: string]: any;
5
- }): Promise<void>;
6
- type Metadata = {
7
- application: string;
8
- tags?: string[];
9
- [key: string]: any;
10
- };
11
- export declare function addDebugLog(body: {
12
- data: object;
13
- metadata: Metadata;
14
- }): Promise<void>;
15
- export declare function addRuntimeLog(body: {
16
- metadata: Metadata;
17
- runtime: number;
18
- success: boolean;
19
- }): Promise<void>;
20
- export declare function addErrorLog(body: {
21
- error: object;
22
- metadata: Metadata;
23
- }): Promise<void>;
24
- /**
25
- * Performs a search operation using the Elasticsearch client
26
- *
27
- * This is a wrapper around the Elasticsearch client's search method.
28
- * See the Elasticsearch documentation for details:
29
- * https://www.elastic.co/guide/en/elasticsearch/reference/8.13/search-search.html
30
- *
31
- * @returns The search results as returned by Elasticsearch
32
- * @throws Error if Elasticsearch client is not configured
33
- *
34
- * @see {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#_search | Elasticsearch Node.js client search API}
35
- */
36
- export declare function search(...options: Parameters<Client['search']>): Promise<ReturnType<Client['search']>>;
37
- export declare function getAllLogs({ index, scrollTime, size, query }: {
38
- index: string;
39
- scrollTime?: string;
40
- size?: number;
41
- query?: object;
42
- }): Promise<any[]>;
43
- export {};