"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());
    });
};
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;
const bytes_1 = require("@ethersproject/bytes");
const web3_js_1 = require("@solana/web3.js");
const utils_1 = require("ethers/lib/utils");
const ethers_1 = require("ethers");
const algorand_1 = require("../algorand");
const cosmos_1 = require("../cosmos");
const address_1 = require("../cosmwasm/address");
const terra_1 = require("../terra");
const consts_1 = require("./consts");
const near_1 = require("./near");
const aptos_1 = require("./aptos");
const sui_js_1 = require("@mysten/sui.js");
const sui_1 = require("../sui");
/**
 *
 * 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.
 */
const isHexNativeTerra = (h) => h.startsWith("01");
exports.isHexNativeTerra = isHexNativeTerra;
const isLikely20ByteTerra = (h) => h.startsWith("000000000000000000000000");
const nativeTerraHexToDenom = (h) => Buffer.from(utils_1.stripZeros(exports.hexToUint8Array(h.substr(2)))).toString("ascii");
exports.nativeTerraHexToDenom = nativeTerraHexToDenom;
const uint8ArrayToHex = (a) => Buffer.from(a).toString("hex");
exports.uint8ArrayToHex = uint8ArrayToHex;
const hexToUint8Array = (h) => {
    if (h.startsWith("0x"))
        h = h.slice(2);
    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
 */
const tryUint8ArrayToNative = (a, chain) => {
    const 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)) {
        const 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_SEI) {
        return cosmos_1.humanAddress("sei", 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
        const _ = chainId;
        throw Error("Don't know how to convert address for chain " + chainId);
    }
};
exports.tryUint8ArrayToNative = tryUint8ArrayToNative;
const tryHexToNativeStringNear = (provider, tokenBridge, address) => __awaiter(void 0, void 0, void 0, function* () {
    const { found, value } = yield near_1.hashLookup(provider, tokenBridge, address);
    if (!found) {
        throw new Error("Address not found");
    }
    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
 */
const tryHexToNativeAssetString = (h, c) => 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.
 */
const hexToNativeAssetString = (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
 */
const tryHexToNativeString = (h, c) => 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.
 */
const hexToNativeString = (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
 */
const tryNativeToHexString = (address, chain) => {
    const 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 ||
        chainId === consts_1.CHAIN_ID_SEI) {
        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) {
        if (!sui_1.isValidSuiType(address) && sui_js_1.isValidSuiAddress(address)) {
            return exports.uint8ArrayToHex(bytes_1.zeroPad(bytes_1.arrayify(address, { allowMissingPrefix: true }), 32));
        }
        throw Error("hexToNativeString: Sui types 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
        const _ = 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
 */
const nativeToHexString = (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) {
    const 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
 */
const uint8ArrayToNative = (a, chainId) => 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((_, index) => 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;
