"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ethers_1 = require("ethers");
const config_1 = require("hardhat/config");
const child_process_1 = require("child_process");
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
// Regular expression to match custom error definitions in Solidity
// It matches lines like: error InvalidPubKey();
// or with parameters: error PollDoesNotExist(uint256 pollId);
const ERROR_REGEX = /error\s+([A-Za-z0-9_]+)\(([^)]*)\)\s*;/g;
function extractErrors(solContent) {
    const errors = [];
    let match = ERROR_REGEX.exec(solContent);
    while (match !== null) {
        // Build the full signature string.
        // Remove extra spaces from parameters.
        const errorName = match[1];
        const params = match[2].trim().replace(/\s+/g, " ");
        const signature = `${errorName}(${params})`;
        errors.push(signature);
        match = ERROR_REGEX.exec(solContent);
    }
    return errors;
}
/**
 * Extracts custom errors from a Solidity file and prints their selectors.
 * Useful for debugging RPC responses containing errors like:
 * {
      "jsonrpc": "2.0",
      "id": 16,
      "error": {
          "code": 3,
          "message": "execution reverted",
          "data": "0xe0f2d7b1"
      }
    }
  * @params solFilePath Path to the Solidity file
  * @params flattenFile Flag to indicate if the file should be flattened before processing
  *         (useful for contracts with imports that define custom errors)
  * Usage: ts-node scripts/decodeErrorsFromSol.ts <path-to-sol-file> <flatten_file_flag>
  * @example 1: pnpm encode-errors --sol-file-path contracts/VerifyingKeysRegistry.sol --flat
  * @example 2: pnpm encode-errors --sol-file-path contracts/MACI.sol
 */
(0, config_1.task)("encode-errors", "Extracts custom errors from a Solidity file and prints their selectors")
    .addParam("solFilePath", "Path to the Solidity file", undefined, config_1.types.string)
    .addFlag("flat", "Flag to indicate if the file should be flattened before processing")
    .setAction(async ({ solFilePath, flat }) => {
    if (!solFilePath) {
        throw new Error("No .sol file. Usage: ts-node scripts/decodeErrorsFromSol.ts <path-to-sol-file> <flatten_file_flag>");
    }
    const absolutePath = path_1.default.resolve(solFilePath);
    const { promisify } = await Promise.resolve().then(() => __importStar(require("util")));
    const execFilePromisify = promisify(child_process_1.execFile);
    const fileContent = flat
        ? await execFilePromisify("pnpm", ["exec", "hardhat", "flatten", absolutePath]).then(({ stdout }) => stdout)
        : await fs_1.default.promises.readFile(absolutePath, "utf8");
    // Extract custom errors from the file
    const errors = extractErrors(fileContent);
    if (errors.length === 0) {
        throw new Error("No custom errors found in the provided file.");
    }
    errors.forEach((signature) => {
        const selector = (0, ethers_1.id)(signature).slice(0, 10);
        // eslint-disable-next-line no-console
        console.log(`${selector} => ${signature}`);
    });
});
//# sourceMappingURL=encodeErrors.js.map