"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.blockExplorerLink = blockExplorerLink;
exports.resolveBlockExplorerDomain = resolveBlockExplorerDomain;
exports.blockExplorerLinks = blockExplorerLinks;
var tslib_1 = require("tslib");
var ethers_1 = require("ethers");
var constants_1 = require("../constants");
var FormattingUtils_1 = require("./FormattingUtils");
var NetworkUtils_1 = require("./NetworkUtils");
var TypeGuards_1 = require("./TypeGuards");
var bs58_1 = tslib_1.__importDefault(require("bs58"));
function blockExplorerLink(txHashOrAddress, chainId) {
    var _a;
    return (_a = _createBlockExplorerLinkMarkdown(txHashOrAddress, Number(chainId))) !== null && _a !== void 0 ? _a : "<>";
}
function resolveBlockExplorerDomain(networkId) {
    var _a;
    return (_a = constants_1.PUBLIC_NETWORKS[networkId]) === null || _a === void 0 ? void 0 : _a.blockExplorer;
}
function constructURL(domain, parts) {
    parts = parts.flatMap(function (p) { return p.split("/"); });
    parts = parts.filter(function (p) { return p !== ""; });
    var path = parts.join("/");
    return "".concat(domain, "/").concat(path).replace(/\/+$/, "");
}
function _createBlockExplorerLinkMarkdown(addr, chainId) {
    if (chainId === void 0) { chainId = 1; }
    var explorerDomain = resolveBlockExplorerDomain(chainId);
    if (!(0, TypeGuards_1.isDefined)(explorerDomain)) {
        return "<unsupported chain/hash ".concat(chainId, ":").concat(addr, ">}");
    }
    if (addr.substring(0, 2) !== "0x" && (0, NetworkUtils_1.chainIsEvm)(chainId)) {
        addr = "0x".concat(addr);
        if (!ethers_1.ethers.utils.isHexString(addr)) {
            return null;
        }
    }
    var shortURLString = (0, FormattingUtils_1.createShortenedString)(addr);
    if ((0, NetworkUtils_1.chainIsEvm)(chainId)) {
        for (var _i = 0, _a = [
            [66, "tx"],
            [42, "address"],
        ]; _i < _a.length; _i++) {
            var _b = _a[_i], length_1 = _b[0], route = _b[1];
            if (addr.length === length_1) {
                return "<".concat(constructURL(explorerDomain, [route, addr]), " | ").concat(shortURLString, ">");
            }
        }
    }
    else {
        var addrLength = bs58_1.default.decode(addr).length;
        var route = addrLength === 32 ? "account" : "tx";
        return "<".concat(constructURL(explorerDomain, [route, addr]), " | ").concat(shortURLString, ">");
    }
    return null;
}
function blockExplorerLinks(txHashesOrAddresses, chainId) {
    return txHashesOrAddresses.map(function (hash) { return "".concat(blockExplorerLink(hash, chainId), "\n"); }).join("");
}
//# sourceMappingURL=BlockExplorerUtils.js.map