"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.queryExternalId = exports.buildTokenId = exports.isNativeCosmWasmDenom = exports.isNativeDenomXpla = exports.isNativeDenomInjective = void 0;
const utils_1 = require("ethers/lib/utils");
const terra_1 = require("../terra");
const utils_2 = require("../utils");
const isNativeDenomInjective = (denom) => denom === "inj";
exports.isNativeDenomInjective = isNativeDenomInjective;
const isNativeDenomXpla = (denom) => denom === "axpla";
exports.isNativeDenomXpla = isNativeDenomXpla;
function isNativeCosmWasmDenom(chainId, address) {
    return ((utils_2.isTerraChain(chainId) && terra_1.isNativeDenom(address)) ||
        (chainId === utils_2.CHAIN_ID_INJECTIVE && exports.isNativeDenomInjective(address)) ||
        (chainId === utils_2.CHAIN_ID_XPLA && exports.isNativeDenomXpla(address)));
}
exports.isNativeCosmWasmDenom = isNativeCosmWasmDenom;
function buildTokenId(chain, address) {
    const chainId = utils_2.coalesceCosmWasmChainId(chain);
    return ((isNativeCosmWasmDenom(chainId, address) ? "01" : "00") +
        utils_1.keccak256(Buffer.from(address, "utf-8")).substring(4));
}
exports.buildTokenId = buildTokenId;
// returns the TokenId corresponding to the ExternalTokenId
// see cosmwasm token_addresses.rs
const queryExternalId = (client, tokenBridgeAddress, externalTokenId) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b, _c, _d, _e;
    try {
        const response = yield client.wasm.contractQuery(tokenBridgeAddress, {
            external_id: {
                external_id: Buffer.from(externalTokenId, "hex").toString("base64"),
            },
        });
        return (
        // response depends on the token type
        ((_a = response.token_id.Bank) === null || _a === void 0 ? void 0 : _a.denom) ||
            ((_c = (_b = response.token_id.Contract) === null || _b === void 0 ? void 0 : _b.NativeCW20) === null || _c === void 0 ? void 0 : _c.contract_address) ||
            ((_e = (_d = response.token_id.Contract) === null || _d === void 0 ? void 0 : _d.ForeignToken) === null || _e === void 0 ? void 0 : _e.foreign_address));
    }
    catch (_f) {
        return null;
    }
});
exports.queryExternalId = queryExternalId;
