@defillama/sdk 5.0.240 → 5.0.244

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 (133) hide show
  1. package/build/Balances.d.ts +139 -0
  2. package/build/Balances.js +363 -0
  3. package/build/ChainApi.d.ts +142 -0
  4. package/build/ChainApi.js +310 -0
  5. package/build/abi/abi2.d.ts +5 -0
  6. package/build/abi/abi2.js +215 -0
  7. package/build/abi/cachedABIs.d.ts +4 -0
  8. package/build/abi/cachedABIs.js +8 -0
  9. package/build/abi/convertResults.d.ts +5 -0
  10. package/build/abi/convertResults.js +60 -0
  11. package/build/abi/index.d.ts +31 -0
  12. package/build/abi/index.js +327 -0
  13. package/build/abi/multicall.d.ts +23 -0
  14. package/build/abi/multicall.js +383 -0
  15. package/build/abi/multicall3.d.ts +7 -0
  16. package/build/abi/multicall3.js +405 -0
  17. package/build/abi/rpcCall.d.ts +4 -0
  18. package/build/abi/rpcCall.js +62 -0
  19. package/build/abi/tron.d.ts +33 -0
  20. package/build/abi/tron.js +118 -0
  21. package/build/api.d.ts +10 -0
  22. package/build/api.js +45 -0
  23. package/build/api2.d.ts +5 -0
  24. package/build/api2.js +41 -0
  25. package/build/chains/algorand.d.ts +277 -0
  26. package/build/chains/algorand.js +618 -0
  27. package/build/chains/aptos.d.ts +269 -0
  28. package/build/chains/aptos.js +700 -0
  29. package/build/chains/cardano.d.ts +242 -0
  30. package/build/chains/cardano.js +407 -0
  31. package/build/chains/cosmos.d.ts +252 -0
  32. package/build/chains/cosmos.js +623 -0
  33. package/build/chains/icp.d.ts +235 -0
  34. package/build/chains/icp.js +1040 -0
  35. package/build/chains/index.d.ts +23 -0
  36. package/build/chains/index.js +59 -0
  37. package/build/chains/near.d.ts +192 -0
  38. package/build/chains/near.js +446 -0
  39. package/build/chains/rpc.d.ts +125 -0
  40. package/build/chains/rpc.js +332 -0
  41. package/build/chains/starknet.d.ts +205 -0
  42. package/build/chains/starknet.js +886 -0
  43. package/build/chains/stellar.d.ts +410 -0
  44. package/build/chains/stellar.js +1082 -0
  45. package/build/chains/substrate.d.ts +333 -0
  46. package/build/chains/substrate.js +1042 -0
  47. package/build/chains/sui.d.ts +392 -0
  48. package/build/chains/sui.js +1213 -0
  49. package/build/chains/svm.d.ts +340 -0
  50. package/build/chains/svm.js +764 -0
  51. package/build/chains/tezos.d.ts +225 -0
  52. package/build/chains/tezos.js +412 -0
  53. package/build/chains/ton.d.ts +353 -0
  54. package/build/chains/ton.js +788 -0
  55. package/build/chains/tron.d.ts +45 -0
  56. package/build/chains/tron.js +110 -0
  57. package/build/chains/utxo.d.ts +210 -0
  58. package/build/chains/utxo.js +678 -0
  59. package/build/chains/xrpl.d.ts +179 -0
  60. package/build/chains/xrpl.js +467 -0
  61. package/build/computeTVL/blocks.d.ts +1 -0
  62. package/build/computeTVL/blocks.js +12 -0
  63. package/build/computeTVL/humanizeNumber.d.ts +1 -0
  64. package/build/computeTVL/humanizeNumber.js +19 -0
  65. package/build/erc20/index.d.ts +31 -0
  66. package/build/erc20/index.js +56 -0
  67. package/build/eth/index.d.ts +22 -0
  68. package/build/eth/index.js +118 -0
  69. package/build/general.d.ts +5 -0
  70. package/build/general.js +20 -0
  71. package/build/generalUtil.d.ts +8 -0
  72. package/build/generalUtil.js +73 -0
  73. package/build/index.d.ts +33 -0
  74. package/build/index.js +75 -0
  75. package/build/providers.json +1 -0
  76. package/build/types.d.ts +76 -0
  77. package/build/types.js +2 -0
  78. package/build/util/LlamaProvider.d.ts +46 -0
  79. package/build/util/LlamaProvider.js +343 -0
  80. package/build/util/blocks.d.ts +36 -0
  81. package/build/util/blocks.js +500 -0
  82. package/build/util/cache.d.ts +45 -0
  83. package/build/util/cache.js +309 -0
  84. package/build/util/callStats.d.ts +74 -0
  85. package/build/util/callStats.js +385 -0
  86. package/build/util/chainUtils/data.json +1459 -0
  87. package/build/util/chainUtils/index.d.ts +11 -0
  88. package/build/util/chainUtils/index.js +136 -0
  89. package/build/util/coins.d.ts +19 -0
  90. package/build/util/coins.js +124 -0
  91. package/build/util/common.d.ts +34 -0
  92. package/build/util/common.js +376 -0
  93. package/build/util/computeTVL.d.ts +19 -0
  94. package/build/util/computeTVL.js +102 -0
  95. package/build/util/cosmos.d.ts +1 -0
  96. package/build/util/cosmos.js +8 -0
  97. package/build/util/debugLog.d.ts +4 -0
  98. package/build/util/debugLog.js +18 -0
  99. package/build/util/discord.d.ts +1 -0
  100. package/build/util/discord.js +33 -0
  101. package/build/util/elastic.d.ts +43 -0
  102. package/build/util/elastic.js +113 -0
  103. package/build/util/env.d.ts +20 -0
  104. package/build/util/env.js +176 -0
  105. package/build/util/graph.d.ts +8 -0
  106. package/build/util/graph.js +50 -0
  107. package/build/util/index.d.ts +32 -0
  108. package/build/util/index.js +227 -0
  109. package/build/util/indexer.compatibility.d.ts +6 -0
  110. package/build/util/indexer.compatibility.js +64 -0
  111. package/build/util/indexer.d.ts +92 -0
  112. package/build/util/indexer.js +854 -0
  113. package/build/util/indexerSql.d.ts +9 -0
  114. package/build/util/indexerSql.js +102 -0
  115. package/build/util/internal-cache.d.ts +11 -0
  116. package/build/util/internal-cache.js +77 -0
  117. package/build/util/logs.d.ts +58 -0
  118. package/build/util/logs.decode.shared.d.ts +8 -0
  119. package/build/util/logs.decode.shared.js +289 -0
  120. package/build/util/logs.js +432 -0
  121. package/build/util/promisePool.d.ts +8 -0
  122. package/build/util/promisePool.js +31 -0
  123. package/build/util/r2.d.ts +4 -0
  124. package/build/util/r2.js +52 -0
  125. package/build/util/removeRedundantRPCs.d.ts +1 -0
  126. package/build/util/removeRedundantRPCs.js +49 -0
  127. package/build/util/transactions.d.ts +35 -0
  128. package/build/util/transactions.js +22 -0
  129. package/build/util/updateChainLabels.d.ts +1 -0
  130. package/build/util/updateChainLabels.js +5 -0
  131. package/build/util/updateProviderList.d.ts +1 -0
  132. package/build/util/updateProviderList.js +275 -0
  133. package/package.json +3 -2
@@ -0,0 +1,9 @@
1
+ export type IndexerSqlOptions = {
2
+ /** Accepted for compatibility with dimension-adapters; all chains use the same gateway. */
3
+ chain?: string;
4
+ signal?: AbortSignal;
5
+ };
6
+ export declare function isIndexerSqlEnabled(): boolean;
7
+ export declare function queryClickhouse<T = any>(sql: string, params?: Record<string, unknown>, settings?: Record<string, string | number>, options?: IndexerSqlOptions): Promise<T[]>;
8
+ /** Gateway-oriented name; queryClickhouse remains available for existing consumers. */
9
+ export declare const queryIndexerSql: typeof queryClickhouse;
@@ -0,0 +1,102 @@
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.queryIndexerSql = void 0;
7
+ exports.isIndexerSqlEnabled = isIndexerSqlEnabled;
8
+ exports.queryClickhouse = queryClickhouse;
9
+ const axios_1 = __importDefault(require("axios"));
10
+ const http_1 = __importDefault(require("http"));
11
+ const https_1 = __importDefault(require("https"));
12
+ const env_1 = require("./env");
13
+ const httpAgent = new http_1.default.Agent({ keepAlive: true, maxSockets: 64, maxFreeSockets: 16 });
14
+ const httpsAgent = new https_1.default.Agent({ keepAlive: true, maxSockets: 64, maxFreeSockets: 16 });
15
+ function getSqlConfig() {
16
+ const v4Endpoint = (0, env_1.getEnvValue)("LLAMA_INDEXER_V4_ENDPOINT");
17
+ return {
18
+ endpoint: (0, env_1.getEnvValue)("LLAMA_INDEXER_SQL_ENDPOINT") || (v4Endpoint ? `${v4Endpoint.replace(/\/+$/, "")}/sql` : undefined),
19
+ user: (0, env_1.getEnvValue)("LLAMA_INDEXER_SQL_USER"),
20
+ password: (0, env_1.getEnvValue)("LLAMA_INDEXER_SQL_PASSWORD"),
21
+ };
22
+ }
23
+ // ClickHouse HTTP query parameters use escaped text, not JSON. Nested strings
24
+ // must be quoted, and UInt64/UInt256 values must never pass through Number().
25
+ function serializeQueryParameter(value, nested = false) {
26
+ if (value === null || value === undefined)
27
+ return nested ? "NULL" : "\\N";
28
+ if (typeof value === "string") {
29
+ const escaped = value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")
30
+ .replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
31
+ return nested ? `'${escaped}'` : escaped;
32
+ }
33
+ if (typeof value === "boolean")
34
+ return nested ? (value ? "TRUE" : "FALSE") : (value ? "1" : "0");
35
+ if (typeof value === "number") {
36
+ if (Number.isNaN(value))
37
+ return "nan";
38
+ if (!Number.isFinite(value))
39
+ return value > 0 ? "+inf" : "-inf";
40
+ return String(value);
41
+ }
42
+ if (typeof value === "bigint")
43
+ return String(value);
44
+ if (Array.isArray(value))
45
+ return `[${value.map((v) => serializeQueryParameter(v, true)).join(",")}]`;
46
+ if (value instanceof Date) {
47
+ const seconds = String(Math.floor(value.getTime() / 1000)).padStart(10, "0");
48
+ return value.getUTCMilliseconds() ? `${seconds}.${String(value.getUTCMilliseconds()).padStart(3, "0")}` : seconds;
49
+ }
50
+ if (typeof value === "object") {
51
+ const entries = value instanceof Map ? [...value.entries()] : Object.entries(value);
52
+ return `{${entries.map(([k, v]) => `${serializeQueryParameter(k, true)}:${serializeQueryParameter(v, true)}`).join(",")}}`;
53
+ }
54
+ throw new Error("Unsupported SQL query parameter type");
55
+ }
56
+ function isIndexerSqlEnabled() {
57
+ const c = getSqlConfig();
58
+ return !!(c.endpoint && c.user && c.password);
59
+ }
60
+ async function queryClickhouse(sql, params, settings, options = {}) {
61
+ var _a, _b;
62
+ const { endpoint, user, password } = getSqlConfig();
63
+ if (!endpoint || !user || !password) {
64
+ throw new Error("Llama indexer SQL gateway not configured (LLAMA_INDEXER_SQL_ENDPOINT/USER/PASSWORD)");
65
+ }
66
+ const url = new URL(endpoint);
67
+ const search = url.searchParams;
68
+ search.set("default_format", "JSONEachRow");
69
+ for (const [name, value] of Object.entries(params !== null && params !== void 0 ? params : {})) {
70
+ search.set(`param_${name}`, serializeQueryParameter(value));
71
+ }
72
+ for (const [name, value] of Object.entries(settings !== null && settings !== void 0 ? settings : {})) {
73
+ search.set(name, String(value));
74
+ }
75
+ let res;
76
+ try {
77
+ res = await axios_1.default.post(url.toString(), sql, {
78
+ auth: { username: user, password },
79
+ headers: { "Content-Type": "text/plain; charset=utf-8" },
80
+ responseType: "text",
81
+ transformResponse: (d) => d,
82
+ // The gateway owns execution deadlines. Callers can still cancel a request.
83
+ timeout: 0,
84
+ signal: options.signal,
85
+ maxBodyLength: Infinity,
86
+ maxContentLength: Infinity,
87
+ httpAgent,
88
+ httpsAgent,
89
+ });
90
+ }
91
+ catch (e) {
92
+ const status = (_a = e === null || e === void 0 ? void 0 : e.response) === null || _a === void 0 ? void 0 : _a.status;
93
+ const body = typeof ((_b = e === null || e === void 0 ? void 0 : e.response) === null || _b === void 0 ? void 0 : _b.data) === "string" ? e.response.data.slice(0, 500) : "";
94
+ throw new Error(`indexer /sql query failed${status ? ` (HTTP ${status})` : ""}: ${body || (e === null || e === void 0 ? void 0 : e.message) || e}`);
95
+ }
96
+ return parseJsonEachRow(res.data);
97
+ }
98
+ function parseJsonEachRow(text) {
99
+ return text.split("\n").filter(line => line.trim()).map(line => JSON.parse(line));
100
+ }
101
+ /** Gateway-oriented name; queryClickhouse remains available for existing consumers. */
102
+ exports.queryIndexerSql = queryClickhouse;
@@ -0,0 +1,11 @@
1
+ export declare function getCache(options: CacheOptions): any;
2
+ export declare function setCache(options: CacheOptions): void;
3
+ export declare function saveCache(): void;
4
+ export declare function startCache(_cache?: {}): void;
5
+ export declare function retriveCache(): any;
6
+ export type CacheOptions = {
7
+ address: string;
8
+ abi: string;
9
+ chain?: string;
10
+ value?: any;
11
+ };
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.getCache = getCache;
37
+ exports.setCache = setCache;
38
+ exports.saveCache = saveCache;
39
+ exports.startCache = startCache;
40
+ exports.retriveCache = retriveCache;
41
+ const fs = __importStar(require("fs"));
42
+ const env_1 = require("./env");
43
+ // const cacheFile = __dirname + '/../../../sc-cache1.json'
44
+ const cacheFile = env_1.ENV_CONSTANTS.INTERNAL_SDK_CACHE_FILE;
45
+ let cache = {};
46
+ // if (cacheFile) cache = require(cacheFile) // disabled for now
47
+ function getCache(options) {
48
+ let { address, abi, chain = "ethereum" } = options;
49
+ if (!address)
50
+ return;
51
+ address = address.slice(2).toLowerCase();
52
+ if (!cache[chain])
53
+ cache[chain] = {};
54
+ if (!cache[chain][abi])
55
+ cache[chain][abi] = {};
56
+ return cache[chain][abi][address];
57
+ }
58
+ function setCache(options) {
59
+ let { address, abi, chain = "ethereum", value } = options;
60
+ if (!address)
61
+ return;
62
+ address = address.slice(2).toLowerCase();
63
+ if (!cache[chain])
64
+ cache[chain] = {};
65
+ if (!cache[chain][abi])
66
+ cache[chain][abi] = {};
67
+ cache[chain][abi][address] = value;
68
+ }
69
+ function saveCache() {
70
+ fs.writeFileSync(cacheFile || './cache.json', JSON.stringify(cache));
71
+ }
72
+ function startCache(_cache = {}) {
73
+ cache = _cache;
74
+ }
75
+ function retriveCache() {
76
+ return cache;
77
+ }
@@ -0,0 +1,58 @@
1
+ import { EventLog, Interface } from "ethers";
2
+ import { Address } from "../types";
3
+ import { IndexerGetLogsOptions } from "./indexer";
4
+ export declare function getBufferedToBlock(toBlock: number, head?: number, buffer?: number): number;
5
+ export type GetLogsOptions = {
6
+ target?: Address;
7
+ topic?: string;
8
+ keys?: string[];
9
+ fromBlock?: number;
10
+ toBlock?: number;
11
+ topics?: (string | null)[];
12
+ extraTopics?: string[];
13
+ chain?: string;
14
+ eventAbi?: string | any;
15
+ fromTimestamp?: number;
16
+ toTimestamp?: number;
17
+ skipCache?: boolean;
18
+ skipCacheRead?: boolean;
19
+ entireLog?: boolean;
20
+ cacheInCloud?: boolean;
21
+ onlyArgs?: boolean;
22
+ targets?: Address[];
23
+ flatten?: boolean;
24
+ skipIndexer?: boolean;
25
+ onlyIndexer?: boolean;
26
+ debugMode?: boolean;
27
+ noTarget?: boolean;
28
+ parseLog?: boolean;
29
+ processor?: (logs: any[]) => Promise<void> | void;
30
+ maxBlockRange?: number;
31
+ allowParseFailure?: boolean;
32
+ };
33
+ export declare function getLogs(options: GetLogsOptions): Promise<EventLog[] | EventLog[][] | any[]>;
34
+ export declare function maxLogsForStorage(bytesPerLog: number, cap?: number, budgetMB?: number): number;
35
+ export declare function trimCachesForStorage(caches: logCache[], maxLogs?: number): logCache[];
36
+ export declare function toFilterTopic(topic: string): string;
37
+ export type logCache = {
38
+ logs: EventLog[];
39
+ metadata: {
40
+ fromBlock: number;
41
+ toBlock: number;
42
+ };
43
+ };
44
+ export default getLogs;
45
+ type GetLogsParamsResponse = {
46
+ chain: string;
47
+ fromBlock: number;
48
+ toBlock: number;
49
+ target?: Address;
50
+ topic: string;
51
+ iface?: Interface;
52
+ transformLog: (log: any) => any;
53
+ topics?: (string | null)[];
54
+ topic1?: string;
55
+ topic2?: string;
56
+ topic3?: string;
57
+ };
58
+ export declare function getLogParams(options: GetLogsOptions | IndexerGetLogsOptions, isIndexerCall?: boolean): Promise<GetLogsParamsResponse>;
@@ -0,0 +1,8 @@
1
+ import { ethers, Interface } from "ethers";
2
+ export declare function padTopic32(t: string): `0x${string}`;
3
+ export declare function normalizeLog(log: any, isIndexerCall?: boolean): boolean;
4
+ export declare function normalizeValueByType(value: any, type: string): any;
5
+ export declare function convertTopicsToViemFormat(topics: any[]): [`0x${string}`, ...(`0x${string}`[] | [])] | [];
6
+ export declare function enrichEthersArgsWithNamedProperties(ethersArgs: any, event: ethers.EventFragment | null, iface: Interface): any;
7
+ export declare function buildEthersCompatibleArgs(decodedArgs: any, eventInputs: readonly ethers.ParamType[], normalizeFn?: (value: any, type: string) => any): any;
8
+ export declare function createViemFastPathBatchDecoder(eventAbi: string | any): ((logs: any[]) => Promise<any[]>) | null;
@@ -0,0 +1,289 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.padTopic32 = padTopic32;
4
+ exports.normalizeLog = normalizeLog;
5
+ exports.normalizeValueByType = normalizeValueByType;
6
+ exports.convertTopicsToViemFormat = convertTopicsToViemFormat;
7
+ exports.enrichEthersArgsWithNamedProperties = enrichEthersArgsWithNamedProperties;
8
+ exports.buildEthersCompatibleArgs = buildEthersCompatibleArgs;
9
+ exports.createViemFastPathBatchDecoder = createViemFastPathBatchDecoder;
10
+ const ethers_1 = require("ethers");
11
+ const viem_1 = require("viem");
12
+ function padTopic32(t) {
13
+ if (!t)
14
+ return '0x';
15
+ // Early return if already 32 bytes (0x + 64 hex chars)
16
+ if (t.startsWith('0x') && t.length === 66)
17
+ return t;
18
+ const hex = t.startsWith('0x') ? t.slice(2) : t;
19
+ return ('0x' + hex.padStart(64, '0'));
20
+ }
21
+ function normalizeLog(log, isIndexerCall = false) {
22
+ var _a, _b, _c, _d;
23
+ if (isIndexerCall || log.source) {
24
+ log.address = (_a = log.source) !== null && _a !== void 0 ? _a : log.address;
25
+ log.logIndex = (_c = (_b = log.log_index) !== null && _b !== void 0 ? _b : log.logIndex) !== null && _c !== void 0 ? _c : log.index;
26
+ log.index = log.logIndex;
27
+ log.transactionHash = (_d = log.transaction_hash) !== null && _d !== void 0 ? _d : log.transactionHash;
28
+ log.blockNumber = parseInt(log.block_number || log.blockNumber || 0);
29
+ const topics = [log.topic0, log.topic1, log.topic2, log.topic3]
30
+ .filter(Boolean)
31
+ .map(padTopic32);
32
+ if (!topics[0])
33
+ return false;
34
+ log.topics = topics;
35
+ log._originalTopics = {
36
+ topic0: log.topic0,
37
+ topic1: log.topic1,
38
+ topic2: log.topic2,
39
+ topic3: log.topic3
40
+ };
41
+ log._originalTransactionHash = log.transaction_hash;
42
+ // Only delete fields that are not needed for parsing
43
+ [
44
+ "chain",
45
+ "log_index",
46
+ ].forEach((k) => delete log[k]);
47
+ }
48
+ if (log.blockNumber === undefined && log.block_number !== undefined)
49
+ log.blockNumber = parseInt(log.block_number);
50
+ // Restore topics if they were lost
51
+ if (!log.topics && log._originalTopics) {
52
+ log.topics = [log._originalTopics.topic0, log._originalTopics.topic1, log._originalTopics.topic2, log._originalTopics.topic3]
53
+ .filter(Boolean)
54
+ .map(padTopic32);
55
+ }
56
+ // Restore transaction hash if it was lost
57
+ if (!log.transactionHash && log._originalTransactionHash) {
58
+ log.transactionHash = log._originalTransactionHash;
59
+ }
60
+ return true;
61
+ }
62
+ /**
63
+ * Normalize value type according to Solidity type to match Ethers format
64
+ * Ethers returns small int types (int24, uint24, uint16, etc.) as strings to avoid JS precision issues
65
+ */
66
+ const smallIntPattern = /^u?int(8|16|24)$/;
67
+ function normalizeValueByType(value, type) {
68
+ if (value === null || value === undefined)
69
+ return value;
70
+ // Ethers formats small integer types as strings
71
+ if (smallIntPattern.test(type)) {
72
+ if (typeof value === 'number') {
73
+ return value.toString();
74
+ }
75
+ else if (typeof value === 'bigint') {
76
+ return value.toString();
77
+ }
78
+ return value;
79
+ }
80
+ return value;
81
+ }
82
+ function convertTopicsToViemFormat(topics) {
83
+ if (!topics || topics.length === 0 || topics[0] === null) {
84
+ return [];
85
+ }
86
+ const filteredTopics = [];
87
+ for (let t = 0; t < topics.length; t++) {
88
+ if (topics[t] !== null) {
89
+ filteredTopics.push(topics[t]);
90
+ }
91
+ }
92
+ // Create tuple type for Viem (required format)
93
+ return filteredTopics.length > 0
94
+ ? [filteredTopics[0], ...filteredTopics.slice(1)]
95
+ : [];
96
+ }
97
+ // Enrich Ethers args with named properties to match Viem output structure
98
+ function enrichEthersArgsWithNamedProperties(ethersArgs, event, iface) {
99
+ if (!ethersArgs || !event || !event.inputs) {
100
+ return ethersArgs;
101
+ }
102
+ const inputs = event.inputs;
103
+ const length = typeof ethersArgs.length === 'number' ? ethersArgs.length : inputs.length;
104
+ const enrichedArgs = new Array(length);
105
+ for (let i = 0; i < length; i++) {
106
+ if (i in ethersArgs) {
107
+ enrichedArgs[i] = ethersArgs[i];
108
+ }
109
+ }
110
+ for (const key in ethersArgs) {
111
+ if (!Object.prototype.hasOwnProperty.call(ethersArgs, key))
112
+ continue;
113
+ if (!/^\d+$/.test(key)) {
114
+ enrichedArgs[key] = ethersArgs[key];
115
+ }
116
+ }
117
+ for (let i = 0; i < inputs.length; i++) {
118
+ const input = inputs[i];
119
+ const value = ethersArgs[i];
120
+ if (value !== undefined && value !== null) {
121
+ if (input.name && !(input.name in enrichedArgs)) {
122
+ enrichedArgs[input.name] = value;
123
+ }
124
+ if (!(i in enrichedArgs)) {
125
+ enrichedArgs[i] = value;
126
+ }
127
+ }
128
+ }
129
+ return enrichedArgs;
130
+ }
131
+ function buildEthersCompatibleArgs(decodedArgs, eventInputs, normalizeFn = normalizeValueByType) {
132
+ var _a, _b;
133
+ if (!decodedArgs) {
134
+ const args = new Array(eventInputs.length);
135
+ return args;
136
+ }
137
+ const args = new Array(eventInputs.length);
138
+ try {
139
+ if (Array.isArray(decodedArgs)) {
140
+ const len = Math.min(decodedArgs.length, eventInputs.length);
141
+ for (let i = 0; i < len; i++) {
142
+ const input = eventInputs[i];
143
+ const value = decodedArgs[i];
144
+ if (value !== undefined && value !== null) {
145
+ const normalizedValue = normalizeFn(value, input.type);
146
+ if (input.name)
147
+ args[input.name] = normalizedValue;
148
+ args[i] = normalizedValue;
149
+ }
150
+ }
151
+ return args;
152
+ }
153
+ if (typeof decodedArgs === 'object') {
154
+ const inputCount = eventInputs.length;
155
+ for (let i = 0; i < inputCount; i++) {
156
+ const input = eventInputs[i];
157
+ const value = (_b = (_a = decodedArgs[input.name]) !== null && _a !== void 0 ? _a : decodedArgs[i]) !== null && _b !== void 0 ? _b : null;
158
+ if (value !== undefined && value !== null) {
159
+ const normalizedValue = normalizeFn(value, input.type);
160
+ if (input.name)
161
+ args[input.name] = normalizedValue;
162
+ args[i] = normalizedValue;
163
+ }
164
+ }
165
+ return args;
166
+ }
167
+ }
168
+ catch (e) {
169
+ // Fallback: minimal object creation
170
+ if (Array.isArray(decodedArgs)) {
171
+ const len = decodedArgs.length;
172
+ for (let i = 0; i < len; i++) {
173
+ args[i] = decodedArgs[i];
174
+ }
175
+ args.length = len;
176
+ }
177
+ else if (typeof decodedArgs === 'object') {
178
+ Object.assign(args, decodedArgs);
179
+ }
180
+ }
181
+ return args;
182
+ }
183
+ function createViemFastPathBatchDecoder(eventAbi) {
184
+ try {
185
+ // Parse ABI once
186
+ const ev = (0, viem_1.parseAbiItem)(eventAbi);
187
+ if (!ev || ev.type !== 'event')
188
+ return null;
189
+ const inputs = ev.inputs || [];
190
+ const indexed = [];
191
+ const nonIndexed = [];
192
+ for (const inp of inputs) {
193
+ if (inp.indexed) {
194
+ indexed.push(inp);
195
+ }
196
+ else {
197
+ nonIndexed.push(inp);
198
+ }
199
+ }
200
+ const nonIndexedTypes = nonIndexed.map(i => ({ type: i.type }));
201
+ return async function decodeBatchViemFast(logs) {
202
+ var _a, _b;
203
+ const out = new Array(logs.length);
204
+ for (let i = 0; i < logs.length; i++) {
205
+ const l = logs[i];
206
+ try {
207
+ const logData = l.data || l.data_field || '0x';
208
+ const decodedNon = nonIndexed.length && logData && logData !== '0x'
209
+ ? (0, viem_1.decodeAbiParameters)(nonIndexedTypes, logData)
210
+ : [];
211
+ const args = new Array(inputs.length);
212
+ let topicIdx = 1; // topics[0] = event signature
213
+ let nonIndexedIdx = 0;
214
+ for (let j = 0; j < inputs.length; j++) {
215
+ const inp = inputs[j];
216
+ let value;
217
+ if (inp.indexed) {
218
+ if (topicIdx < (((_a = l.topics) === null || _a === void 0 ? void 0 : _a.length) || 0)) {
219
+ value = l.topics[topicIdx];
220
+ topicIdx++;
221
+ }
222
+ else {
223
+ value = null;
224
+ }
225
+ }
226
+ else {
227
+ value = (_b = decodedNon[nonIndexedIdx]) !== null && _b !== void 0 ? _b : null;
228
+ nonIndexedIdx++;
229
+ }
230
+ let normalizedValue = null;
231
+ if (value !== null && value !== undefined) {
232
+ // For indexed addresses, Ethers extracts the address from the padded topic
233
+ // Topics are 32 bytes padded, but Ethers returns addresses as normal 20-byte addresses
234
+ // Ethers uses getAddress() which converts to checksum format
235
+ if (inp.type === 'address' && inp.indexed && typeof value === 'string') {
236
+ let addressStr;
237
+ if (value.startsWith('0x') && value.length === 66) {
238
+ // Topic is 32 bytes padded, extract the address (last 20 bytes = 40 hex chars)
239
+ addressStr = '0x' + value.slice(-40);
240
+ }
241
+ else if (value.startsWith('0x') && value.length === 42) {
242
+ addressStr = value;
243
+ }
244
+ else {
245
+ // Fallback: try to extract address from topic
246
+ const hex = value.startsWith('0x') ? value.slice(2) : value;
247
+ if (hex.length >= 40) {
248
+ addressStr = '0x' + hex.slice(-40);
249
+ }
250
+ else {
251
+ addressStr = value;
252
+ }
253
+ }
254
+ // Use ethers.getAddress to convert to checksum format (like Ethers does)
255
+ try {
256
+ normalizedValue = ethers_1.ethers.getAddress(addressStr);
257
+ }
258
+ catch {
259
+ // Fallback if getAddress fails
260
+ normalizedValue = addressStr.toLowerCase();
261
+ }
262
+ }
263
+ else {
264
+ // For other types, use normal normalization
265
+ normalizedValue = normalizeValueByType(value, inp.type);
266
+ }
267
+ }
268
+ // Always assign both numeric index and named property (even if value is null/undefined)
269
+ // This matches Ethers behavior where all args are present in the args object
270
+ args[j] = normalizedValue;
271
+ if (inp.name) {
272
+ args[inp.name] = normalizedValue;
273
+ }
274
+ }
275
+ out[i] = args;
276
+ }
277
+ catch (e) {
278
+ // Fallback: return empty args on decode error
279
+ const args = new Array(inputs.length);
280
+ out[i] = args;
281
+ }
282
+ }
283
+ return out;
284
+ };
285
+ }
286
+ catch (e) {
287
+ return null;
288
+ }
289
+ }