"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ensureHexPrefix = exports.hex = exports.textToUint8Array = exports.textToHexString = exports.chunks = exports.uint8ArrayToNative = exports.tryNativeToUint8Array = exports.nativeToHexString = exports.tryNativeToHexString = exports.hexToNativeString = exports.tryHexToNativeString = exports.hexToNativeAssetString = exports.tryHexToNativeAssetString = exports.tryHexToNativeStringNear = exports.tryUint8ArrayToNative = exports.hexToUint8Array = exports.uint8ArrayToHex = exports.nativeTerraHexToDenom = exports.isHexNativeTerra = void 0;
var bytes_1 = require("@ethersproject/bytes");
var web3_js_1 = require("@solana/web3.js");
var utils_1 = require("ethers/lib/utils");
var ethers_1 = require("ethers");
var algorand_1 = require("../algorand");
var cosmos_1 = require("../cosmos");
var address_1 = require("../cosmwasm/address");
var terra_1 = require("../terra");
var consts_1 = require("./consts");
var near_1 = require("./near");
var aptos_1 = require("./aptos");
/**
 *
 * Returns true iff the hex string represents a native Terra denom.
 *
 * Native assets on terra don't have an associated smart contract address, just
 * like eth isn't an ERC-20 contract on Ethereum.
 *
 * The difference is that the EVM implementations of Portal don't support eth
 * directly, and instead require swapping to an ERC-20 wrapped eth (WETH)
 * contract first.
 *
 * The Terra implementation instead supports Terra-native denoms without
 * wrapping to CW-20 token first. As these denoms don't have an address, they
 * are encoded in the Portal payloads by the setting the first byte to 1.  This
 * encoding is safe, because the first 12 bytes of the 32-byte wormhole address
 * space are not used on Terra otherwise, as cosmos addresses are 20 bytes wide.
 */
var isHexNativeTerra = function (h) { return h.startsWith("01"); };
exports.isHexNativeTerra = isHexNativeTerra;
var isLikely20ByteTerra = function (h) {
    return h.startsWith("000000000000000000000000");
};
var nativeTerraHexToDenom = function (h) {
    return Buffer.from(utils_1.stripZeros(exports.hexToUint8Array(h.substr(2)))).toString("ascii");
};
exports.nativeTerraHexToDenom = nativeTerraHexToDenom;
var uint8ArrayToHex = function (a) {
    return Buffer.from(a).toString("hex");
};
exports.uint8ArrayToHex = uint8ArrayToHex;
var hexToUint8Array = function (h) {
    return new Uint8Array(Buffer.from(h, "hex"));
};
exports.hexToUint8Array = hexToUint8Array;
/**
 *
 * Convert an address in a wormhole's 32-byte array representation into a chain's
 * native string representation.
 *
 * @throws if address is not the right length for the given chain
 */
var tryUint8ArrayToNative = function (a, chain) {
    var chainId = consts_1.coalesceChainId(chain);
    if (consts_1.isEVMChain(chainId)) {
        return utils_1.hexZeroPad(utils_1.hexValue(a), 20);
    }
    else if (chainId === consts_1.CHAIN_ID_SOLANA || chainId === consts_1.CHAIN_ID_PYTHNET) {
        return new web3_js_1.PublicKey(a).toString();
    }
    else if (consts_1.isTerraChain(chainId)) {
        var h = exports.uint8ArrayToHex(a);
        if (exports.isHexNativeTerra(h)) {
            return exports.nativeTerraHexToDenom(h);
        }
        else {
            if (chainId === consts_1.CHAIN_ID_TERRA2 && !isLikely20ByteTerra(h)) {
                // terra 2 has 32 byte addresses for contracts and 20 for wallets
                return cosmos_1.humanAddress("terra", a);
            }
            return cosmos_1.humanAddress("terra", a.slice(-20));
        }
    }
    else if (chainId === consts_1.CHAIN_ID_INJECTIVE) {
        return cosmos_1.humanAddress("inj", a.slice(-20));
    }
    else if (chainId === consts_1.CHAIN_ID_ALGORAND) {
        return algorand_1.uint8ArrayToNativeStringAlgorand(a);
    }
    else if (chainId == consts_1.CHAIN_ID_WORMCHAIN) {
        // wormchain addresses are always 20 bytes.
        return cosmos_1.humanAddress("wormhole", a.slice(-20));
    }
    else if (chainId === consts_1.CHAIN_ID_XPLA) {
        return cosmos_1.humanAddress("xpla", a.slice(-20));
    }
    else if (chainId === consts_1.CHAIN_ID_NEAR) {
        throw Error("uint8ArrayToNative: Use tryHexToNativeStringNear instead.");
    }
    else if (chainId === consts_1.CHAIN_ID_OSMOSIS) {
        throw Error("uint8ArrayToNative: Osmosis not supported yet.");
    }
    else if (chainId === consts_1.CHAIN_ID_SUI) {
        throw Error("uint8ArrayToNative: Sui not supported yet.");
    }
    else if (chainId === consts_1.CHAIN_ID_APTOS) {
        throw Error("uint8ArrayToNative: Aptos not supported yet.");
    }
    else if (chainId === consts_1.CHAIN_ID_UNSET) {
        throw Error("uint8ArrayToNative: Chain id unset");
    }
    else if (chainId === consts_1.CHAIN_ID_BTC) {
        throw Error("uint8ArrayToNative: Btc not supported");
    }
    else {
        // This case is never reached
        var _1 = chainId;
        throw Error("Don't know how to convert address for chain " + chainId);
    }
};
exports.tryUint8ArrayToNative = tryUint8ArrayToNative;
var tryHexToNativeStringNear = function (provider, tokenBridge, address) { return __awaiter(void 0, void 0, void 0, function () {
    var _a, found, value;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0: return [4 /*yield*/, near_1.hashLookup(provider, tokenBridge, address)];
            case 1:
                _a = _b.sent(), found = _a.found, value = _a.value;
                if (!found) {
                    throw new Error("Address not found");
                }
                return [2 /*return*/, value];
        }
    });
}); };
exports.tryHexToNativeStringNear = tryHexToNativeStringNear;
/**
 *
 * Convert an address in a wormhole's 32-byte hex representation into a chain's native
 * string representation.
 *
 * @throws if address is not the right length for the given chain
 */
var tryHexToNativeAssetString = function (h, c) {
    return c === consts_1.CHAIN_ID_ALGORAND
        ? // Algorand assets are represented by their asset ids, not an address
            algorand_1.hexToNativeAssetStringAlgorand(h)
        : exports.tryHexToNativeString(h, c);
};
exports.tryHexToNativeAssetString = tryHexToNativeAssetString;
/**
 *
 * Convert an address in a wormhole's 32-byte hex representation into a chain's native
 * string representation.
 *
 * @deprecated since 0.3.0, use [[tryHexToNativeString]] instead.
 */
var hexToNativeAssetString = function (h, c) {
    if (!h) {
        return undefined;
    }
    try {
        return exports.tryHexToNativeAssetString(h, c);
    }
    catch (e) {
        return undefined;
    }
};
exports.hexToNativeAssetString = hexToNativeAssetString;
/**
 *
 * Convert an address in a wormhole's 32-byte hex representation into a chain's native
 * string representation.
 *
 * @throws if address is not the right length for the given chain
 */
var tryHexToNativeString = function (h, c) { return exports.tryUint8ArrayToNative(exports.hexToUint8Array(h), c); };
exports.tryHexToNativeString = tryHexToNativeString;
/**
 *
 * Convert an address in a wormhole's 32-byte hex representation into a chain's native
 * string representation.
 *
 * @deprecated since 0.3.0, use [[tryHexToNativeString]] instead.
 */
var hexToNativeString = function (h, c) {
    if (!h) {
        return undefined;
    }
    try {
        return exports.tryHexToNativeString(h, c);
    }
    catch (e) {
        return undefined;
    }
};
exports.hexToNativeString = hexToNativeString;
/**
 *
 * Convert an address in a chain's native representation into a 32-byte hex string
 * understood by wormhole.
 *
 * @throws if address is a malformed string for the given chain id
 */
var tryNativeToHexString = function (address, chain) {
    var chainId = consts_1.coalesceChainId(chain);
    if (consts_1.isEVMChain(chainId)) {
        return exports.uint8ArrayToHex(bytes_1.zeroPad(bytes_1.arrayify(address), 32));
    }
    else if (chainId === consts_1.CHAIN_ID_SOLANA || chainId === consts_1.CHAIN_ID_PYTHNET) {
        return exports.uint8ArrayToHex(bytes_1.zeroPad(new web3_js_1.PublicKey(address).toBytes(), 32));
    }
    else if (chainId === consts_1.CHAIN_ID_TERRA) {
        if (terra_1.isNativeDenom(address)) {
            return ("01" +
                exports.uint8ArrayToHex(bytes_1.zeroPad(new Uint8Array(Buffer.from(address, "ascii")), 31)));
        }
        else {
            return exports.uint8ArrayToHex(bytes_1.zeroPad(cosmos_1.canonicalAddress(address), 32));
        }
    }
    else if (chainId === consts_1.CHAIN_ID_TERRA2 ||
        chainId === consts_1.CHAIN_ID_INJECTIVE ||
        chainId === consts_1.CHAIN_ID_XPLA) {
        return address_1.buildTokenId(chainId, address);
    }
    else if (chainId === consts_1.CHAIN_ID_ALGORAND) {
        return algorand_1.nativeStringToHexAlgorand(address);
    }
    else if (chainId == consts_1.CHAIN_ID_WORMCHAIN) {
        return exports.uint8ArrayToHex(bytes_1.zeroPad(cosmos_1.canonicalAddress(address), 32));
    }
    else if (chainId === consts_1.CHAIN_ID_NEAR) {
        return exports.uint8ArrayToHex(bytes_1.arrayify(utils_1.sha256(Buffer.from(address))));
    }
    else if (chainId === consts_1.CHAIN_ID_OSMOSIS) {
        throw Error("hexToNativeString: Osmosis not supported yet.");
    }
    else if (chainId === consts_1.CHAIN_ID_SUI) {
        throw Error("hexToNativeString: Sui not supported yet.");
    }
    else if (chainId === consts_1.CHAIN_ID_BTC) {
        throw Error("hexToNativeString: Btc not supported yet.");
    }
    else if (chainId === consts_1.CHAIN_ID_APTOS) {
        if (aptos_1.isValidAptosType(address)) {
            return aptos_1.getExternalAddressFromType(address);
        }
        return exports.uint8ArrayToHex(bytes_1.zeroPad(bytes_1.arrayify(address, { allowMissingPrefix: true }), 32));
    }
    else if (chainId === consts_1.CHAIN_ID_UNSET) {
        throw Error("hexToNativeString: Chain id unset");
    }
    else {
        // If this case is reached
        var _2 = chainId;
        throw Error("Don't know how to convert address from chain " + chainId);
    }
};
exports.tryNativeToHexString = tryNativeToHexString;
/**
 *
 * Convert an address in a chain's native representation into a 32-byte hex string
 * understood by wormhole.
 *
 * @deprecated since 0.3.0, use [[tryNativeToHexString]] instead.
 * @throws if address is a malformed string for the given chain id
 */
var nativeToHexString = function (address, chain) {
    if (!address) {
        return null;
    }
    return exports.tryNativeToHexString(address, chain);
};
exports.nativeToHexString = nativeToHexString;
/**
 *
 * Convert an address in a chain's native representation into a 32-byte array
 * understood by wormhole.
 *
 * @throws if address is a malformed string for the given chain id
 */
function tryNativeToUint8Array(address, chain) {
    var chainId = consts_1.coalesceChainId(chain);
    return exports.hexToUint8Array(exports.tryNativeToHexString(address, chainId));
}
exports.tryNativeToUint8Array = tryNativeToUint8Array;
/**
 *
 * Convert an address in a chain's native representation into a 32-byte hex string
 * understood by wormhole.
 *
 * @deprecated since 0.3.0, use [[tryUint8ArrayToNative]] instead.
 * @throws if address is a malformed string for the given chain id
 */
var uint8ArrayToNative = function (a, chainId) {
    return exports.hexToNativeString(exports.uint8ArrayToHex(a), chainId);
};
exports.uint8ArrayToNative = uint8ArrayToNative;
function chunks(array, size) {
    return Array.apply(0, new Array(Math.ceil(array.length / size))).map(function (_, index) { return array.slice(index * size, (index + 1) * size); });
}
exports.chunks = chunks;
function textToHexString(name) {
    return Buffer.from(name, "binary").toString("hex");
}
exports.textToHexString = textToHexString;
function textToUint8Array(name) {
    return new Uint8Array(Buffer.from(name, "binary"));
}
exports.textToUint8Array = textToUint8Array;
function hex(x) {
    return Buffer.from(ethers_1.ethers.utils.hexlify(x, { allowMissingPrefix: true }).substring(2), "hex");
}
exports.hex = hex;
function ensureHexPrefix(x) {
    return x.substring(0, 2) !== "0x" ? "0x" + x : x;
}
exports.ensureHexPrefix = ensureHexPrefix;
