@defillama/sdk 5.0.242 → 5.0.245

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.
@@ -14,6 +14,7 @@ const providers_json_1 = __importDefault(require("../providers.json"));
14
14
  const env_1 = require("./env");
15
15
  const debugLog_1 = require("./debugLog");
16
16
  const axios_1 = __importDefault(require("axios"));
17
+ const callStats_1 = require("./callStats");
17
18
  let buildProviders = undefined;
18
19
  if (process.env['TEST_MODE']) {
19
20
  buildProviders = require('../../build/providers.json');
@@ -137,6 +138,7 @@ class LlamaProvider extends ethers_1.FallbackProvider {
137
138
  // }
138
139
  for (const runner of runners) {
139
140
  try {
141
+ (0, callStats_1.recordMethod)(method, this.chainName); // per attempt: call stats count requests, not successes
140
142
  const result = await httpRPC[method](runner.url, params);
141
143
  return result;
142
144
  }
@@ -179,6 +181,7 @@ function createProvider(name, rpcString, chainId = 400069, archivalRPCList = [])
179
181
  // return getProviderObject(rpcList[0], name)
180
182
  rpcList = [rpcList[0]];
181
183
  }
184
+ (0, callStats_1.registerEndpoints)(name, [...rpcList, ...archivalRPCList]); // so http level call stats are attributed to this chain
182
185
  try {
183
186
  const fallbackConfig = { cacheTimeout: 5 * 1000, quorum: 1, eventQuorum: 1, };
184
187
  const getProviderWithURL = (url) => ({ url, provider: getProviderObject(url, name) });
@@ -237,39 +240,42 @@ function toHex(n) {
237
240
  return n;
238
241
  return '0x' + n.toString(16);
239
242
  }
243
+ // A public RPC behind a dead or re-routed domain can answer HTTP 200 with an HTML page, an empty body or a JSON object without `result`
244
+ // (seen on mainnet.telos.net/evm). Reading `data.result` off that gave `undefined`, which the caller treated as a successful
245
+ // call and handed to the ABI decoder, so the error surfaced as "invalid BytesLike value null" / a multicall failure instead of the
246
+ // provider moving on to the next RPC. Anything that is not a JSON-RPC envelope with a `result` is therefore thrown here.
247
+ async function rpcPost(rpc, method, params, timeoutEnvKey, defaultTimeout) {
248
+ const { data } = await axios_1.default.post(rpc, { jsonrpc: '2.0', id: 1, params, method }, {
249
+ timeout: +(0, env_1.getEnvValue)(timeoutEnvKey, defaultTimeout)
250
+ });
251
+ if (!data || typeof data !== 'object' || Array.isArray(data))
252
+ throw new Error(`${method} on ${rpc}: not a JSON-RPC response: ${String(data).slice(0, 120)}`);
253
+ if (data.error)
254
+ throw data.error;
255
+ if (!Object.prototype.hasOwnProperty.call(data, 'result'))
256
+ throw new Error(`${method} on ${rpc}: response has no result field: ${JSON.stringify(data).slice(0, 120)}`);
257
+ return data.result;
258
+ }
240
259
  const httpRPC = {
241
260
  getBlockNumber: async (rpc) => {
242
261
  const getData = async () => {
243
- const data = (await axios_1.default.post(rpc, {
244
- jsonrpc: '2.0', id: 1, params: [],
245
- method: 'eth_blockNumber',
246
- }, {
247
- timeout: +(0, env_1.getEnvValue)('LLAMA_PROVIDER_RPC_GET_BLOCKNUMBER_TIMEOUT', '30000')
248
- })).data;
249
- if (data.error)
250
- throw data.error;
251
- return data.result;
262
+ const result = await rpcPost(rpc, 'eth_blockNumber', [], 'LLAMA_PROVIDER_RPC_GET_BLOCKNUMBER_TIMEOUT', '30000');
263
+ const block = parseInt(result);
264
+ if (isNaN(block))
265
+ throw new Error(`eth_blockNumber on ${rpc}: bad result ${JSON.stringify(result)}`);
266
+ return block;
252
267
  };
253
- let data;
254
268
  try {
255
- data = await getData();
269
+ return await getData();
256
270
  }
257
271
  catch (e) {
258
272
  // try again
259
- data = await getData();
273
+ return await getData();
260
274
  }
261
- return parseInt(data);
262
275
  },
263
276
  getBlock: async (rpc, params) => {
264
277
  params[0] = toHex(params[0]);
265
- const { data: { result, error } } = await axios_1.default.post(rpc, {
266
- jsonrpc: '2.0', id: 1, params,
267
- method: 'eth_getBlockByNumber',
268
- }, {
269
- timeout: +(0, env_1.getEnvValue)('LLAMA_PROVIDER_RPC_GET_BLOCK_TIMEOUT', '60000')
270
- });
271
- if (error)
272
- throw error;
278
+ const result = await rpcPost(rpc, 'eth_getBlockByNumber', params, 'LLAMA_PROVIDER_RPC_GET_BLOCK_TIMEOUT', '60000');
273
279
  if (!result)
274
280
  throw new Error(`block ${params[0]} not found`); // pruned or not yet synced, let callers recognise it
275
281
  result.number = parseInt(result.number);
@@ -278,39 +284,23 @@ const httpRPC = {
278
284
  },
279
285
  getBalance: async (rpc, params) => {
280
286
  params[1] = toHex(params[1]);
281
- const { data: { result, error } } = await axios_1.default.post(rpc, {
282
- jsonrpc: '2.0', id: 1, params,
283
- method: 'eth_getBalance',
284
- }, {
285
- timeout: +(0, env_1.getEnvValue)('LLAMA_PROVIDER_RPC_GET_BALANCE_TIMEOUT', '30000')
286
- });
287
- if (error)
288
- throw error;
287
+ const result = await rpcPost(rpc, 'eth_getBalance', params, 'LLAMA_PROVIDER_RPC_GET_BALANCE_TIMEOUT', '30000');
289
288
  return BigInt(result).toString();
290
289
  },
291
290
  call: async (rpc, params) => {
292
291
  params[1] = toHex(params[1]);
293
- const { data } = await axios_1.default.post(rpc, {
294
- jsonrpc: '2.0', id: 1, params,
295
- method: 'eth_call',
296
- }, {
297
- timeout: +(0, env_1.getEnvValue)('LLAMA_PROVIDER_RPC_CALL_TIMEOUT', '30000')
298
- });
299
- if (data.error)
300
- throw data.error;
301
- return data.result;
292
+ const result = await rpcPost(rpc, 'eth_call', params, 'LLAMA_PROVIDER_RPC_CALL_TIMEOUT', '30000');
293
+ // eth_call always returns hex data (`0x` when the target has no code); a null here is a broken node, not an empty return
294
+ if (typeof result !== 'string')
295
+ throw new Error(`eth_call on ${rpc}: bad result ${JSON.stringify(result)}`);
296
+ return result;
302
297
  },
303
298
  getLogs: async (rpc, params) => {
304
299
  params[0].fromBlock = toHex(params[0].fromBlock);
305
300
  params[0].toBlock = toHex(params[0].toBlock);
306
- const { data: { result, error } } = await axios_1.default.post(rpc, {
307
- jsonrpc: '2.0', id: 1, params,
308
- method: 'eth_getLogs',
309
- }, {
310
- timeout: +(0, env_1.getEnvValue)('LLAMA_PROVIDER_RPC_GET_LOGS_TIMEOUT', '30000')
311
- });
312
- if (error)
313
- throw error;
301
+ const result = await rpcPost(rpc, 'eth_getLogs', params, 'LLAMA_PROVIDER_RPC_GET_LOGS_TIMEOUT', '30000');
302
+ if (!Array.isArray(result))
303
+ throw new Error(`eth_getLogs on ${rpc}: bad result ${JSON.stringify(result)}`);
314
304
  result.forEach((i) => {
315
305
  i.blockNumber = parseInt(i.blockNumber);
316
306
  i.transactionIndex = parseInt(i.transactionIndex);
@@ -320,14 +310,7 @@ const httpRPC = {
320
310
  return result;
321
311
  },
322
312
  getTransaction: async (rpc, params) => {
323
- const { data: { result, error } } = await axios_1.default.post(rpc, {
324
- jsonrpc: '2.0', id: 1, params,
325
- method: 'eth_getTransactionByHash',
326
- }, {
327
- timeout: +(0, env_1.getEnvValue)('LLAMA_PROVIDER_RPC_GET_TRANSACTION_TIMEOUT', '180000')
328
- });
329
- if (error)
330
- throw error;
313
+ const result = await rpcPost(rpc, 'eth_getTransactionByHash', params, 'LLAMA_PROVIDER_RPC_GET_TRANSACTION_TIMEOUT', '180000');
331
314
  if (!result)
332
315
  return null;
333
316
  result.blockNumber = parseInt(result.blockNumber);
@@ -336,14 +319,7 @@ const httpRPC = {
336
319
  return result;
337
320
  },
338
321
  getTransactionReceipt: async (rpc, params) => {
339
- const { data: { result, error } } = await axios_1.default.post(rpc, {
340
- jsonrpc: '2.0', id: 1, params,
341
- method: 'eth_getTransactionReceipt',
342
- }, {
343
- timeout: +(0, env_1.getEnvValue)('LLAMA_PROVIDER_RPC_GET_TXN_RECEIPT_TIMEOUT', '180000')
344
- });
345
- if (error)
346
- throw error;
322
+ const result = await rpcPost(rpc, 'eth_getTransactionReceipt', params, 'LLAMA_PROVIDER_RPC_GET_TXN_RECEIPT_TIMEOUT', '180000');
347
323
  if (!result)
348
324
  return null;
349
325
  result.blockNumber = parseInt(result.blockNumber);
@@ -0,0 +1,123 @@
1
+ /** one doc per (run, chain) */
2
+ export declare const ES_INDEX = "adapter-calls";
3
+ /** one doc per (run, host) */
4
+ export declare const ES_HOST_INDEX = "adapter-call-hosts";
5
+ /** `chain` of the doc counting requests that matched no registered rpc endpoint */
6
+ export declare const OTHER_CHAIN = "_other";
7
+ /** runs with fewer http requests in total are not written at all (env CALL_STATS_MIN_CALLS) */
8
+ export declare const DEFAULT_MIN_CALLS = 1;
9
+ export declare const MAX_HOSTS_PER_RUN = 25;
10
+ export type CallStatsMeta = {
11
+ /** 'tvl' | 'dimensions' | ... */
12
+ application: string;
13
+ /** protocol / module name */
14
+ name: string;
15
+ [key: string]: any;
16
+ };
17
+ export type CallStats = {
18
+ meta: CallStatsMeta;
19
+ startTime: number;
20
+ total: number;
21
+ /** chain -> requests to a registered rpc endpoint of that chain */
22
+ byChain: Record<string, number>;
23
+ /** host -> requests, every request */
24
+ byHost: Record<string, number>;
25
+ /** requests that matched no registered endpoint */
26
+ unattributed: number;
27
+ /**
28
+ * logical rpc method -> chain -> requests, recorded by the SDK at the call site (`recordMethod`):
29
+ * every LlamaProvider attempt (`call`, `getLogs`, `getBlock`, ...), starknet `getLogs`, and `indexerGetLogs`
30
+ */
31
+ byMethod: Record<string, Record<string, number>>;
32
+ /** log rows fetched over the wire: source ('rpc' | 'indexer') -> chain -> rows, recorded by the SDK (`recordLogs`) */
33
+ logs: Record<LogSource, Record<string, number>>;
34
+ /** set once the run's docs were written (by `run` settling, or earlier by `flushActive`) */
35
+ reported?: boolean;
36
+ };
37
+ export type LogSource = 'rpc' | 'indexer';
38
+ export declare const INDEXER_METHOD = "indexer";
39
+ export type CallStatsSnapshot = Pick<CallStats, 'total' | 'byChain' | 'byHost' | 'unattributed' | 'byMethod'> & Partial<Pick<CallStats, 'logs'>>;
40
+ /**
41
+ * Remember that `endpoints` serve `chain`, so requests to them are counted against that chain.
42
+ * Called by the SDK wherever it resolves rpc urls; adapters can call it for endpoints they manage themselves.
43
+ */
44
+ export declare function registerEndpoints(chain: string | undefined, endpoints: string | string[] | undefined): void;
45
+ /** Chain a url is counted against, or undefined when it matches no registered endpoint. */
46
+ export declare function resolveChain(url: string): string | undefined;
47
+ /** Requests to these hosts are not counted (eg. the elasticsearch cluster the stats are written to). */
48
+ export declare function ignoreHost(url: string): void;
49
+ /**
50
+ * Count a logical rpc request (one attempt, so retries count) against `method` and `chain` in the current run.
51
+ * The http layer already counts the request itself; this adds the method breakdown (getLogs being the one that matters).
52
+ */
53
+ export declare function recordMethod(method: string, chain?: string): void;
54
+ /** Count `count` log rows fetched from `source` for `chain` in the current run (rows received, cached reads are not fetched). */
55
+ export declare function recordLogs(source: LogSource, chain: string | undefined, count: number): void;
56
+ /** Patch the node http layer. Idempotent, shared across sdk copies. Called by `run`. */
57
+ export declare function install(): void;
58
+ export type RunOptions = {
59
+ /** nothing is written when the run made fewer http requests in total (default 1, env CALL_STATS_MIN_CALLS) */
60
+ minCalls?: number;
61
+ /** print the summary table to the console (always, not only in debug mode) */
62
+ print?: boolean;
63
+ /** skip the elasticsearch write */
64
+ skipElastic?: boolean;
65
+ };
66
+ /** Stats of the current run context, or the process-wide bucket when called outside `run`. */
67
+ export declare function getCurrent(): CallStats;
68
+ export declare function snapshot(stats?: CallStats): CallStatsSnapshot;
69
+ export declare function mergeSnapshots(snapshots: CallStatsSnapshot[]): CallStatsSnapshot;
70
+ /**
71
+ * Run `fn` with its own counters and report them when it settles (success or failure).
72
+ * Nested calls get their own context; calls made by `fn` through any http client are attributed to it.
73
+ */
74
+ export declare function run<T>(meta: CallStatsMeta, fn: () => Promise<T>, options?: RunOptions): Promise<T>;
75
+ /**
76
+ * Write the docs of the runs still in flight (all of them, or those whose meta passes `filter`) as failed runs
77
+ * with `interrupted: reason`, and mark them so they are not written again when they eventually settle.
78
+ * For a process that is about to be killed, or a job the caller has given up on: without this the heaviest runs,
79
+ * the ones that hit the timeout, would be exactly the ones never recorded. Returns the number of runs written.
80
+ */
81
+ export declare function flushActive(reason: string, { filter, ...options }?: RunOptions & {
82
+ filter?: (meta: CallStatsMeta) => boolean;
83
+ }): Promise<number>;
84
+ export declare function getMinCalls(minCalls?: number): number;
85
+ export type ChainRow = {
86
+ chain: string;
87
+ /** http requests to a registered rpc of the chain (`_other`: requests matching no registered rpc, the indexer included) */
88
+ calls: number;
89
+ /** rpc getLogs attempts */
90
+ getLogs: number;
91
+ /** http requests to the llama indexer for this chain */
92
+ indexerCalls: number;
93
+ /** log rows fetched over the wire, by source and in total */
94
+ logs: number;
95
+ logsRpc: number;
96
+ logsIndexer: number;
97
+ methods: Record<string, number>;
98
+ };
99
+ export type HostRow = {
100
+ host: string;
101
+ calls: number;
102
+ rpc: boolean;
103
+ };
104
+ export type CallStatsDocs = {
105
+ chainDocs: any[];
106
+ hostDocs: any[];
107
+ };
108
+ /**
109
+ * Elasticsearch documents for a run: `chainDocs` for `adapter-calls` (one per chain) and `hostDocs` for
110
+ * `adapter-call-hosts` (one per host). Every doc carries the run meta, totals and the same `runId`, so
111
+ * run-level questions are a `runId` grouping of the same index. Empty when the run is under `minCalls`.
112
+ */
113
+ export type ReportOptions = {
114
+ success?: boolean;
115
+ runtime?: number;
116
+ minCalls?: number; /** why the run was written before it settled ('timeout', 'shutdown'...) */
117
+ interrupted?: string;
118
+ };
119
+ export declare function buildDocs(stats: CallStatsSnapshot, meta: CallStatsMeta, { success, runtime, minCalls, interrupted }?: ReportOptions): CallStatsDocs;
120
+ /** Write the docs for `stats` to elasticsearch (no-op when ELASTICSEARCH_CONFIG is unset) and print the summary in debug mode. */
121
+ export declare function report(stats: CallStats | CallStatsSnapshot, { success, runtime, minCalls, interrupted, print, skipElastic, meta }?: RunOptions & ReportOptions & {
122
+ meta?: CallStatsMeta;
123
+ }): Promise<void>;