"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.getForeignAssetSui = exports.getForeignAssetAptos = exports.getForeignAssetNear = exports.getForeignAssetAlgorand = exports.getForeignAssetSolana = exports.getForeignAssetXpla = exports.getForeignAssetInjective = exports.getForeignAssetTerra = exports.getForeignAssetEth = void 0;
const js_base64_1 = require("js-base64");
const algorand_1 = require("../algorand");
const ethers_contracts_1 = require("../ethers-contracts");
const tokenBridge_1 = require("../solana/tokenBridge");
const utils_1 = require("../utils");
const sui_1 = require("../sui");
/**
 * Returns a foreign asset address on Ethereum for a provided native chain and asset address, AddressZero if it does not exist
 * @param tokenBridgeAddress
 * @param provider
 * @param originChain
 * @param originAsset zero pad to 32 bytes
 * @returns
 */
function getForeignAssetEth(tokenBridgeAddress, provider, originChain, originAsset) {
    return __awaiter(this, void 0, void 0, function* () {
        const tokenBridge = ethers_contracts_1.Bridge__factory.connect(tokenBridgeAddress, provider);
        try {
            return yield tokenBridge.wrappedAsset(utils_1.coalesceChainId(originChain), originAsset);
        }
        catch (e) {
            return null;
        }
    });
}
exports.getForeignAssetEth = getForeignAssetEth;
function getForeignAssetTerra(tokenBridgeAddress, client, originChain, originAsset) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const result = yield client.wasm.contractQuery(tokenBridgeAddress, {
                wrapped_registry: {
                    chain: utils_1.coalesceChainId(originChain),
                    address: js_base64_1.fromUint8Array(originAsset),
                },
            });
            return result.address;
        }
        catch (e) {
            return null;
        }
    });
}
exports.getForeignAssetTerra = getForeignAssetTerra;
/**
 * Returns the address of the foreign asset
 * @param tokenBridgeAddress Address of token bridge contact
 * @param client Holds the wallet and signing information
 * @param originChain The chainId of the origin of the asset
 * @param originAsset The address of the origin asset
 * @returns The foreign asset address or null
 */
function getForeignAssetInjective(tokenBridgeAddress, client, originChain, originAsset) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const queryResult = yield client.fetchSmartContractState(tokenBridgeAddress, Buffer.from(JSON.stringify({
                wrapped_registry: {
                    chain: utils_1.coalesceChainId(originChain),
                    address: js_base64_1.fromUint8Array(originAsset),
                },
            })).toString("base64"));
            const parsed = utils_1.parseSmartContractStateResponse(queryResult);
            return parsed.address;
        }
        catch (e) {
            return null;
        }
    });
}
exports.getForeignAssetInjective = getForeignAssetInjective;
function getForeignAssetXpla(tokenBridgeAddress, client, originChain, originAsset) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const result = yield client.wasm.contractQuery(tokenBridgeAddress, {
                wrapped_registry: {
                    chain: utils_1.coalesceChainId(originChain),
                    address: js_base64_1.fromUint8Array(originAsset),
                },
            });
            return result.address;
        }
        catch (e) {
            return null;
        }
    });
}
exports.getForeignAssetXpla = getForeignAssetXpla;
/**
 * Returns a foreign asset address on Solana for a provided native chain and asset address
 * @param connection
 * @param tokenBridgeAddress
 * @param originChain
 * @param originAsset zero pad to 32 bytes
 * @param [commitment]
 * @returns
 */
function getForeignAssetSolana(connection, tokenBridgeAddress, originChain, originAsset, commitment) {
    return __awaiter(this, void 0, void 0, function* () {
        const mint = tokenBridge_1.deriveWrappedMintKey(tokenBridgeAddress, utils_1.coalesceChainId(originChain), originAsset);
        return tokenBridge_1.getWrappedMeta(connection, tokenBridgeAddress, mint, commitment)
            .catch((_) => null)
            .then((meta) => (meta === null ? null : mint.toString()));
    });
}
exports.getForeignAssetSolana = getForeignAssetSolana;
function getForeignAssetAlgorand(client, tokenBridgeId, chain, contract) {
    return __awaiter(this, void 0, void 0, function* () {
        const chainId = utils_1.coalesceChainId(chain);
        if (chainId === utils_1.CHAIN_ID_ALGORAND) {
            return algorand_1.hexToNativeAssetBigIntAlgorand(contract);
        }
        else {
            let { lsa, doesExist } = yield algorand_1.calcLogicSigAccount(client, tokenBridgeId, BigInt(chainId), contract);
            if (!doesExist) {
                return null;
            }
            let asset = yield algorand_1.decodeLocalState(client, tokenBridgeId, lsa.address());
            if (asset.length > 8) {
                const tmp = Buffer.from(asset.slice(0, 8));
                return tmp.readBigUInt64BE(0);
            }
            else
                return null;
        }
    });
}
exports.getForeignAssetAlgorand = getForeignAssetAlgorand;
function getForeignAssetNear(provider, tokenAccount, chain, contract) {
    return __awaiter(this, void 0, void 0, function* () {
        const ret = yield utils_1.callFunctionNear(provider, tokenAccount, "get_foreign_asset", {
            chain: utils_1.coalesceChainId(chain),
            address: contract,
        });
        return ret !== "" ? ret : null;
    });
}
exports.getForeignAssetNear = getForeignAssetNear;
/**
 * Get qualified type of asset on Aptos given its origin info.
 * @param client Client used to transfer data to/from Aptos node
 * @param tokenBridgeAddress Address of token bridge
 * @param originChain Chain ID of chain asset is originally from
 * @param originAddress Asset address on origin chain
 * @returns Fully qualified type of asset on Aptos
 */
function getForeignAssetAptos(client, tokenBridgeAddress, originChain, originAddress) {
    return __awaiter(this, void 0, void 0, function* () {
        const originChainId = utils_1.coalesceChainId(originChain);
        const assetFullyQualifiedType = utils_1.getAssetFullyQualifiedType(tokenBridgeAddress, originChainId, originAddress);
        if (!assetFullyQualifiedType) {
            return null;
        }
        try {
            // check if asset exists and throw if it doesn't
            yield client.getAccountResource(utils_1.coalesceModuleAddress(assetFullyQualifiedType), `0x1::coin::CoinInfo<${assetFullyQualifiedType}>`);
            return assetFullyQualifiedType;
        }
        catch (e) {
            return null;
        }
    });
}
exports.getForeignAssetAptos = getForeignAssetAptos;
function getForeignAssetSui(provider, tokenBridgeStateObjectId, originChain, originAddress) {
    return __awaiter(this, void 0, void 0, function* () {
        const originChainId = utils_1.coalesceChainId(originChain);
        return yield sui_1.getTokenCoinType(provider, tokenBridgeStateObjectId, originAddress, originChainId);
    });
}
exports.getForeignAssetSui = getForeignAssetSui;
