@defillama/sdk 4.0.81 → 5.0.2

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.
@@ -50,23 +50,24 @@ function getContract(address, chain) {
50
50
  }
51
51
  function info(tokenAddress, chain) {
52
52
  return __awaiter(this, void 0, void 0, function () {
53
- var contract, tokenSymbol, tokenDecimals;
54
- var _a, _b;
55
- return __generator(this, function (_c) {
56
- switch (_c.label) {
53
+ var contract, tokenSymbol, tokenDecimals, _a;
54
+ var _b, _c;
55
+ return __generator(this, function (_d) {
56
+ switch (_d.label) {
57
57
  case 0:
58
58
  contract = getContract(tokenAddress, chain);
59
59
  tokenSymbol = contract.symbol();
60
60
  tokenDecimals = contract.decimals();
61
- _a = {};
62
61
  _b = {};
62
+ _c = {};
63
63
  return [4 /*yield*/, tokenSymbol];
64
64
  case 1:
65
- _b.symbol = _c.sent();
65
+ _c.symbol = _d.sent();
66
+ _a = Number;
66
67
  return [4 /*yield*/, tokenDecimals];
67
- case 2: return [2 /*return*/, (_a.output = (_b.decimals = _c.sent(),
68
- _b),
69
- _a)];
68
+ case 2: return [2 /*return*/, (_b.output = (_c.decimals = _a.apply(void 0, [_d.sent()]),
69
+ _c),
70
+ _b)];
70
71
  }
71
72
  });
72
73
  });
@@ -90,31 +91,32 @@ exports.symbol = symbol;
90
91
  function decimals(tokenAddress, chain) {
91
92
  return __awaiter(this, void 0, void 0, function () {
92
93
  var _a;
93
- return __generator(this, function (_b) {
94
- switch (_b.label) {
94
+ var _b;
95
+ return __generator(this, function (_c) {
96
+ switch (_c.label) {
95
97
  case 0:
96
- _a = {};
98
+ _b = {};
99
+ _a = Number;
97
100
  return [4 /*yield*/, getContract(tokenAddress, chain).decimals()];
98
- case 1: return [2 /*return*/, (_a.output = _b.sent(),
99
- _a)];
101
+ case 1: return [2 /*return*/, (_b.output = _a.apply(void 0, [_c.sent()]),
102
+ _b)];
100
103
  }
101
104
  });
102
105
  });
103
106
  }
104
107
  exports.decimals = decimals;
105
108
  function totalSupply(params) {
106
- var _a;
107
109
  return __awaiter(this, void 0, void 0, function () {
108
110
  var contract, supply;
109
- return __generator(this, function (_b) {
110
- switch (_b.label) {
111
+ return __generator(this, function (_a) {
112
+ switch (_a.label) {
111
113
  case 0:
112
114
  contract = getContract(params.target, params.chain);
113
115
  return [4 /*yield*/, contract.totalSupply({
114
- blockTag: (_a = params.block) !== null && _a !== void 0 ? _a : "latest",
116
+ blockTag: params.block,
115
117
  })];
116
118
  case 1:
117
- supply = _b.sent();
119
+ supply = _a.sent();
118
120
  return [2 /*return*/, {
119
121
  output: (0, general_1.handleDecimals)(supply, params.decimals),
120
122
  }];
@@ -124,16 +126,15 @@ function totalSupply(params) {
124
126
  }
125
127
  exports.totalSupply = totalSupply;
126
128
  function balanceOf(params) {
127
- var _a;
128
129
  return __awaiter(this, void 0, void 0, function () {
129
130
  var balance;
130
- return __generator(this, function (_b) {
131
- switch (_b.label) {
131
+ return __generator(this, function (_a) {
132
+ switch (_a.label) {
132
133
  case 0: return [4 /*yield*/, getContract(params.target, params.chain).balanceOf(params.owner, {
133
- blockTag: (_a = params.block) !== null && _a !== void 0 ? _a : "latest",
134
+ blockTag: params.block,
134
135
  })];
135
136
  case 1:
136
- balance = _b.sent();
137
+ balance = _a.sent();
137
138
  return [2 /*return*/, {
138
139
  output: (0, general_1.handleDecimals)(balance, params.decimals),
139
140
  }];
@@ -1,5 +1,4 @@
1
- import { ethers, BigNumber } from "ethers";
2
- type Provider = ethers.providers.StaticJsonRpcProvider | ethers.providers.FallbackProvider;
1
+ import { Provider } from "ethers";
3
2
  type ProviderWrapped = {
4
3
  rpcList: string;
5
4
  _provider: Provider;
@@ -9,8 +8,8 @@ export declare const providers: {
9
8
  };
10
9
  export type Chain = string;
11
10
  export declare function getProvider(chain?: Chain, getArchivalNode?: boolean): Provider;
12
- export declare const TEN: ethers.BigNumber;
13
- export declare function handleDecimals(num: BigNumber, decimals?: number): string;
11
+ export declare const TEN: bigint;
12
+ export declare function handleDecimals(num: any, decimals?: number): string;
14
13
  export declare const ETHER_ADDRESS = "0x0000000000000000000000000000000000000000";
15
14
  export declare function setProvider(chain: Chain, provider: Provider): void;
16
15
  export {};
package/build/general.js CHANGED
@@ -4,45 +4,86 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.setProvider = exports.ETHER_ADDRESS = exports.handleDecimals = exports.TEN = exports.getProvider = exports.providers = void 0;
7
- var debugLog_1 = require("./util/debugLog");
8
7
  var ethers_1 = require("ethers");
9
8
  var providers_json_1 = __importDefault(require("./providers.json"));
10
9
  function createProvider(name, rpcString, chainId) {
11
10
  if (chainId === void 0) { chainId = 2424242424242422; }
11
+ var networkish = { name: name, chainId: chainId };
12
12
  var rpcList = rpcString.split(',');
13
+ if (process.env["".concat(name.toUpperCase(), "_RPC_CHAIN_ID")])
14
+ chainId = +process.env["".concat(name.toUpperCase(), "_RPC_CHAIN_ID")];
13
15
  if (process.env.HISTORICAL) {
14
16
  if (chainId === 1) {
15
17
  console.log("RPC providers set to historical, only the first RPC provider will be used");
16
18
  }
17
- return new ethers_1.ethers.providers.StaticJsonRpcProvider(rpcList[0], {
18
- name: name,
19
- chainId: chainId,
20
- });
19
+ return getProviderObject(rpcList[0]);
21
20
  }
22
21
  else {
23
22
  try {
24
- return new ethers_1.ethers.providers.FallbackProvider(rpcList.map(function (url, i) { return ({
25
- provider: new ethers_1.ethers.providers.StaticJsonRpcProvider(url, {
26
- name: name,
27
- chainId: chainId,
28
- }),
29
- priority: i
30
- }); }), 1);
23
+ return new ethers_1.ethers.FallbackProvider(rpcList.map(function (url, i) { return ({ provider: getProviderObject(url), priority: i, chainId: chainId, }); }), networkish, { cacheTimeout: 5 * 1000 });
31
24
  }
32
25
  catch (e) {
33
- (0, debugLog_1.debugLog)("Error creating provider for ".concat(name, " with RPCs: ").concat(rpcList.join(', ')));
26
+ // debugLog(`Error creating provider for ${name} with RPCs: ${rpcList.join(', ')}`)
34
27
  // we dont throw errors for chains not present in providers.json, these can be non-evm chains like solana
35
28
  if (providers_json_1.default[name])
36
29
  throw e;
37
30
  return null;
38
31
  }
39
32
  }
33
+ function getProviderObject(url) {
34
+ /**
35
+ * Options for configuring a [[JsonRpcApiProvider]]. Much of this
36
+ * is targetted towards sub-classes, which often will not expose
37
+ * any of these options to their consumers.
38
+ *
39
+ * **``polling``** - use the polling strategy is used immediately
40
+ * for events; otherwise, attempt to use filters and fall back onto
41
+ * polling (default: ``false``)
42
+ *
43
+ * **``staticNetwork``** - do not request chain ID on requests to
44
+ * validate the underlying chain has not changed (default: ``null``)
45
+ *
46
+ * This should **ONLY** be used if it is **certain** that the network
47
+ * cannot change, such as when using INFURA (since the URL dictates the
48
+ * network). If the network is assumed static and it does change, this
49
+ * can have tragic consequences. For example, this **CANNOT** be used
50
+ * with MetaMask, since the used can select a new network from the
51
+ * drop-down at any time.
52
+ *
53
+ * **``batchStallTime``** - how long (ms) to aggregate requests into a
54
+ * single batch. ``0`` indicates batching will only encompass the current
55
+ * event loop. If ``batchMaxCount = 1``, this is ignored. (default: ``10``)
56
+ *
57
+ * **``batchMaxSize``** - target maximum size (bytes) to allow per batch
58
+ * request (default: 1Mb)
59
+ *
60
+ * **``batchMaxCount``** - maximum number of requests to allow in a batch.
61
+ * If ``batchMaxCount = 1``, then batching is disabled. (default: ``100``)
62
+ *
63
+ * **``cacheTimeout``** - passed as [[AbstractProviderOptions]].
64
+ * **``cacheTimeout``** - how long to cache a low-level ``_perform``
65
+ * for, based on input parameters. This reduces the number of calls
66
+ * to getChainId and getBlockNumber, but may break test chains which
67
+ * can perform operations (internally) synchronously. Use ``-1`` to
68
+ * disable, ``0`` will only buffer within the same event loop and
69
+ * any other value is in ms. (default: ``250``)
70
+ */
71
+ var batchMaxSize = 10 * (1024 * 1024); // 10Mb
72
+ var jsonRpcApiProviderOptions = { staticNetwork: true, batchStallTime: 42, batchMaxSize: batchMaxSize, batchMaxCount: 1000, cacheTimeout: 5 * 1000 };
73
+ if (url.startsWith('wss://')) {
74
+ delete jsonRpcApiProviderOptions.batchMaxCount;
75
+ return new ethers_1.ethers.WebSocketProvider(url, networkish, jsonRpcApiProviderOptions);
76
+ }
77
+ return new ethers_1.ethers.JsonRpcProvider(url, networkish, jsonRpcApiProviderOptions);
78
+ }
40
79
  }
41
80
  exports.providers = {};
42
81
  function getProvider(chain, getArchivalNode) {
43
82
  var _a, _b, _c;
44
83
  if (chain === void 0) { chain = "ethereum"; }
45
84
  if (getArchivalNode === void 0) { getArchivalNode = false; }
85
+ if (exports.providers[chain] && !getArchivalNode)
86
+ return exports.providers[chain]._provider;
46
87
  var chainArchivalpcEnv = process.env[chain.toUpperCase() + "_ARCHIVAL_RPC"];
47
88
  if (getArchivalNode && typeof chainArchivalpcEnv === 'string' && chainArchivalpcEnv.length > 0) {
48
89
  var rpcList_1 = chainArchivalpcEnv === null || chainArchivalpcEnv === void 0 ? void 0 : chainArchivalpcEnv.split(',');
@@ -70,13 +111,15 @@ function getProvider(chain, getArchivalNode) {
70
111
  return exports.providers[chain]._provider;
71
112
  }
72
113
  exports.getProvider = getProvider;
73
- exports.TEN = ethers_1.BigNumber.from(10);
114
+ exports.TEN = BigInt(10);
74
115
  function handleDecimals(num, decimals) {
116
+ if (typeof num !== 'number')
117
+ num = num.toString();
75
118
  if (decimals === undefined) {
76
119
  return num.toString();
77
120
  }
78
121
  else {
79
- return num.div(exports.TEN.pow(decimals)).toString();
122
+ return Number(num / (Math.pow(10, decimals))).toString();
80
123
  }
81
124
  }
82
125
  exports.handleDecimals = handleDecimals;
@@ -1,4 +1,3 @@
1
- import { BigNumber } from "ethers";
2
1
  import * as blocks from "./computeTVL/blocks";
3
2
  import * as humanizeNumber from "./computeTVL/humanizeNumber";
4
3
  import type { Balances, StringNumber, Address } from "./types";
@@ -13,7 +12,7 @@ export declare function sumMultiBalanceOf(balances: Balances, results: {
13
12
  };
14
13
  }[];
15
14
  }, allCallsMustBeSuccessful?: boolean, transformAddress?: (addr: string) => string): void;
16
- export declare function sumSingleBalance(balances: Balances, token: string, balance: string | number | BigNumber, chain?: string): void;
15
+ export declare function sumSingleBalance(balances: Balances, token: string, balance: string | number | BigInt, chain?: string): void;
17
16
  export declare function mergeBalances(balances: Balances, balancesToMerge: Balances): void;
18
17
  export declare function removeTokenBalance(balances: Balances, token: string, isCaseSensitive?: boolean): Balances;
19
18
  type ChainBlocks = {
@@ -22,5 +21,6 @@ type ChainBlocks = {
22
21
  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>;
23
22
  export { blocks, humanizeNumber, };
24
23
  export declare function getUniqueAddresses(addresses: string[], chain?: string): string[];
24
+ export declare function getProviderUrl(provider: any): string;
25
25
  export declare function formErrorString(e: any, errorParams?: any): any;
26
26
  export declare function formError(e: any, errorParams?: any): Error;
@@ -59,12 +59,12 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
59
59
  }
60
60
  };
61
61
  Object.defineProperty(exports, "__esModule", { value: true });
62
- exports.formError = exports.formErrorString = exports.getUniqueAddresses = exports.humanizeNumber = exports.blocks = exports.sumChainTvls = exports.removeTokenBalance = exports.mergeBalances = exports.sumSingleBalance = exports.sumMultiBalanceOf = void 0;
63
- var ethers_1 = require("ethers");
62
+ exports.formError = exports.formErrorString = exports.getProviderUrl = exports.getUniqueAddresses = exports.humanizeNumber = exports.blocks = exports.sumChainTvls = exports.removeTokenBalance = exports.mergeBalances = exports.sumSingleBalance = exports.sumMultiBalanceOf = void 0;
64
63
  var blocks = __importStar(require("./computeTVL/blocks"));
65
64
  exports.blocks = blocks;
66
65
  var humanizeNumber = __importStar(require("./computeTVL/humanizeNumber"));
67
66
  exports.humanizeNumber = humanizeNumber;
67
+ var ethers = __importStar(require("ethers"));
68
68
  // We ignore `sum` as it's never used (only in some SDK wrapper code)
69
69
  function sumMultiBalanceOf(balances, results, allCallsMustBeSuccessful, transformAddress) {
70
70
  if (allCallsMustBeSuccessful === void 0) { allCallsMustBeSuccessful = true; }
@@ -74,12 +74,10 @@ function sumMultiBalanceOf(balances, results, allCallsMustBeSuccessful, transfor
74
74
  if (result.success) {
75
75
  var address = transformAddress(result.input.target);
76
76
  var balance = result.output;
77
- if (ethers_1.BigNumber.from(balance).lte(0)) {
77
+ if (BigInt(balance) <= 0) {
78
78
  return;
79
79
  }
80
- balances[address] = ethers_1.BigNumber.from((_a = balances[address]) !== null && _a !== void 0 ? _a : 0)
81
- .add(balance)
82
- .toString();
80
+ balances[address] = (BigInt((_a = balances[address]) !== null && _a !== void 0 ? _a : 0) + BigInt(balance)).toString();
83
81
  }
84
82
  else if (allCallsMustBeSuccessful) {
85
83
  console.error(result);
@@ -89,6 +87,8 @@ function sumMultiBalanceOf(balances, results, allCallsMustBeSuccessful, transfor
89
87
  }
90
88
  exports.sumMultiBalanceOf = sumMultiBalanceOf;
91
89
  function sumSingleBalance(balances, token, balance, chain) {
90
+ if (typeof balance === 'bigint')
91
+ balance = balance.toString();
92
92
  isValidNumber(balance);
93
93
  if (+balance === 0)
94
94
  return;
@@ -109,12 +109,44 @@ function sumSingleBalance(balances, token, balance, chain) {
109
109
  balances[token] = value;
110
110
  }
111
111
  else {
112
- var prevBalance = ethers_1.BigNumber.from(balances.hasOwnProperty(token) ? balances[token] : '0');
113
- var value = prevBalance.add(ethers_1.BigNumber.from(balance)).toString();
114
- isValidNumber(+value);
115
- balances[token] = value;
112
+ var prevBalance = getBigInt(balances[token]);
113
+ var value = (prevBalance + getBigInt(balance));
114
+ isValidNumber(Number(value));
115
+ balances[token] = Number(value).toString();
116
+ }
117
+ function getBigInt(value) {
118
+ var balance = value;
119
+ if (!value)
120
+ return BigInt(0);
121
+ if (typeof value === 'bigint')
122
+ return value;
123
+ if (typeof value === 'number')
124
+ value = value.toString();
125
+ if (typeof value === 'string') {
126
+ if (value.includes('e')) { // Convert scientific notation to standard notation
127
+ var _a = value.split('e'), base = _a[0], e = _a[1];
128
+ var _b = base.split('.'), lead = _b[0], decimal = _b[1];
129
+ var final = void 0;
130
+ var exponent = +e;
131
+ if (exponent >= 0) {
132
+ final = lead + (decimal || '') + '0'.repeat(exponent - (decimal || '').length);
133
+ }
134
+ else {
135
+ // NOTE: unforutenately BigInt doesn't support negative exponents, so this ends up being 0
136
+ exponent = exponent * -1;
137
+ final = BigInt(lead) / BigInt('1' + Array(exponent).fill(0).join(''));
138
+ }
139
+ return BigInt(final);
140
+ }
141
+ return BigInt(value);
142
+ }
143
+ if (typeof value === 'string')
144
+ return BigInt(value);
145
+ throw new Error("Invalid balance: ".concat(balance));
116
146
  }
117
147
  function isValidNumber(value) {
148
+ if (typeof value === 'bigint')
149
+ return;
118
150
  if ([null, undefined].includes(value) || isNaN(+value))
119
151
  throw new Error("Invalid balance: ".concat(balance));
120
152
  }
@@ -177,8 +209,16 @@ function getUniqueAddresses(addresses, chain) {
177
209
  return Object.keys(set);
178
210
  }
179
211
  exports.getUniqueAddresses = getUniqueAddresses;
212
+ function getProviderUrl(provider) {
213
+ if (provider instanceof ethers.FallbackProvider)
214
+ provider = provider.providerConfigs[0].provider;
215
+ if (provider instanceof ethers.JsonRpcProvider)
216
+ return provider._getConnection().url;
217
+ return '';
218
+ }
219
+ exports.getProviderUrl = getProviderUrl;
180
220
  function formErrorString(e, errorParams) {
181
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
221
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
182
222
  if (errorParams === void 0) { errorParams = {}; }
183
223
  if (!e) {
184
224
  if (errorParams.promisePoolErrors) {
@@ -202,14 +242,14 @@ function formErrorString(e, errorParams) {
202
242
  var errorString = e.toString();
203
243
  if (typeof e !== 'object')
204
244
  return errorString;
205
- if ((e.reason || e.method) && e.code) { // ethers.js error
206
- var method = e.method;
245
+ if (((e.reason || e.method) && e.code) || errorParams.result === '0x') { // ethers.js error
246
+ var method = (_d = e.method) !== null && _d !== void 0 ? _d : errorParams.abi;
207
247
  if (e.body) {
208
248
  try {
209
249
  e.body = JSON.parse(e.body);
210
250
  }
211
251
  catch (e) { }
212
- if ((_e = (_d = e.body) === null || _d === void 0 ? void 0 : _d.error) === null || _e === void 0 ? void 0 : _e.message)
252
+ if ((_f = (_e = e.body) === null || _e === void 0 ? void 0 : _e.error) === null || _f === void 0 ? void 0 : _f.message)
213
253
  return e.body.error.message;
214
254
  }
215
255
  if (!method && e.requestBody) {
@@ -217,13 +257,11 @@ function formErrorString(e, errorParams) {
217
257
  e.requestBody = JSON.parse(e.requestBody);
218
258
  }
219
259
  catch (e) { }
220
- method = (_f = e.requestBody) === null || _f === void 0 ? void 0 : _f.method;
260
+ method = (_g = e.requestBody) === null || _g === void 0 ? void 0 : _g.method;
221
261
  }
222
262
  if (!e.provider && errorParams.provider)
223
263
  e.provider = errorParams.provider;
224
- var providerUrl = (_g = e === null || e === void 0 ? void 0 : e.url) !== null && _g !== void 0 ? _g : (_m = (_l = (_k = ((_j = (_h = e.provider) === null || _h === void 0 ? void 0 : _h.providerConfigs) !== null && _j !== void 0 ? _j : [])[0]) === null || _k === void 0 ? void 0 : _k.provider) === null || _l === void 0 ? void 0 : _l.connection) === null || _m === void 0 ? void 0 : _m.url;
225
- if (!providerUrl) // in case of historical queries against archive nodes
226
- providerUrl = (_p = (_o = e.provider) === null || _o === void 0 ? void 0 : _o.connection) === null || _p === void 0 ? void 0 : _p.url;
264
+ var providerUrl = getProviderUrl((_h = e.provider) !== null && _h !== void 0 ? _h : errorParams.provider);
227
265
  if (e.serverError)
228
266
  return "host: ".concat(providerUrl, " ").concat(e.serverError.toString());
229
267
  if (e.results) {
@@ -233,11 +271,11 @@ function formErrorString(e, errorParams) {
233
271
  return "Failed to call method: ".concat(method, " provider: ").concat(providerUrl, "\n ").concat(eStrings.join('\n'));
234
272
  }
235
273
  }
236
- else if (e.code === 'CALL_EXCEPTION' && errorParams.isCallError) {
274
+ else if (e.code === 'CALL_EXCEPTION' || errorParams.isCallError) {
237
275
  var extraInfo = 'target: ' + errorParams.target;
238
276
  if (errorParams.params && errorParams.params.length)
239
277
  extraInfo += shortenString(' params: ' + errorParams.params.join(', '));
240
- return "Failed to call ".concat(method, " ").concat(extraInfo, " on chain: [").concat(errorParams.chain, "] rpc: ").concat(providerUrl, " call reverted ").concat((_q = e.errorName) !== null && _q !== void 0 ? _q : '', " ").concat((_r = e.errorArgs) !== null && _r !== void 0 ? _r : '');
278
+ return "Failed to call ".concat(method, " ").concat(extraInfo, " on chain: [").concat(errorParams.chain, "] rpc: ").concat(providerUrl, " call reverted ").concat((_j = e.errorName) !== null && _j !== void 0 ? _j : '', " ").concat((_k = e.errorArgs) !== null && _k !== void 0 ? _k : '');
241
279
  }
242
280
  if (method === 'eth_blockNumber')
243
281
  return "host: ".concat(providerUrl, " reason: ").concat(e.reason, " code: ").concat(e.code);