"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContractVerifier = void 0;
/**
 * @notice Contract verifier allows to verify contract using hardhat-etherscan plugin.
 */
class ContractVerifier {
    /**
     * Initialize class properties
     *
     * @param hre - Hardhat runtime environment
     */
    constructor(hre) {
        this.hre = hre;
    }
    /**
     * Verify contract through etherscan
     *
     * @param address - contract address
     * @param constructorArguments - stringified constructor arguments
     * @param contract - contract name
     * @param libraries - stringified libraries which can't be detected automatically
     * @param implementation - proxy implementation address
     * @returns
     */
    async verify(address, constructorArguments, contract, libraries, implementation) {
        const params = {
            address,
            constructorArguments: JSON.parse(constructorArguments),
            contract,
        };
        if (libraries) {
            params.libraries = JSON.parse(libraries);
        }
        const { Etherscan } = await Promise.resolve().then(() => __importStar(require("@nomicfoundation/hardhat-verify/etherscan")));
        const customChain = this.hre.config.etherscan.customChains.find((chain) => chain.network === this.hre.network.name);
        const { apiKey } = this.hre.config.etherscan;
        const etherscanInstance = new Etherscan(typeof apiKey === "string" ? apiKey : apiKey[this.hre.network.name], `https://api.etherscan.io/v2/api?chainid=${this.hre.network.config.chainId}`, customChain?.urls.browserURL ?? "", this.hre.network.config.chainId);
        // Run etherscan task
        const error = await this.hre
            .run("verify:verify", params)
            .then(() => "")
            .catch((err) => {
            if (err.message.includes("already verified")) {
                return "";
            }
            return err.message;
        });
        const isEtherscanVerified = await etherscanInstance.isVerified(params.address);
        if (!isEtherscanVerified) {
            // eslint-disable-next-line no-console
            console.warn(`Contract is not verified ${params.address}\n`, error);
        }
        // Manually check if proxy is verified.
        // Etherscan api doesn't return verification status but it's available in etherscan ui.
        // This is related to clones because deployed bytecode is not available directly.
        const isVerified = implementation && !isEtherscanVerified && customChain
            ? await fetch(`${customChain.urls.browserURL}/address/${params.address}#code`)
                .then((response) => response.text())
                .then((text) => {
                const regex = new RegExp(`Minimal Proxy Contract.*?for\\s+<a[^>]*?>\\s*(${implementation})\\s*</a>`, "i");
                return regex.test(text);
            })
            : isEtherscanVerified;
        return isVerified ? [true, ""] : [!error, error];
    }
}
exports.ContractVerifier = ContractVerifier;
//# sourceMappingURL=ContractVerifier.js.map