"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.getOriginalAssetAlgorand = exports.getOriginalAssetSol = exports.getOriginalAssetTerra = exports.getOriginalAssetEth = void 0;
const web3_js_1 = require("@solana/web3.js");
const ethers_1 = require("ethers");
const utils_1 = require("ethers/lib/utils");
const algorand_1 = require("../algorand");
const ethers_contracts_1 = require("../ethers-contracts");
const wasm_1 = require("../solana/wasm");
const terra_1 = require("../terra");
const utils_2 = require("../utils");
const bigint_1 = require("../utils/bigint");
const getIsWrappedAsset_1 = require("./getIsWrappedAsset");
/**
 * Returns a origin chain and asset address on {originChain} for a provided Wormhole wrapped address
 * @param tokenBridgeAddress
 * @param provider
 * @param wrappedAddress
 * @returns
 */
function getOriginalAssetEth(tokenBridgeAddress, provider, wrappedAddress, lookupChain) {
    return __awaiter(this, void 0, void 0, function* () {
        const isWrapped = yield getIsWrappedAsset_1.getIsWrappedAssetEth(tokenBridgeAddress, provider, wrappedAddress);
        if (isWrapped) {
            const token = ethers_contracts_1.TokenImplementation__factory.connect(wrappedAddress, provider);
            const chainId = (yield token.chainId()); // origin chain
            const assetAddress = yield token.nativeContract(); // origin address
            return {
                isWrapped: true,
                chainId,
                assetAddress: utils_1.arrayify(assetAddress),
            };
        }
        return {
            isWrapped: false,
            chainId: utils_2.coalesceChainId(lookupChain),
            assetAddress: utils_1.zeroPad(utils_1.arrayify(wrappedAddress), 32),
        };
    });
}
exports.getOriginalAssetEth = getOriginalAssetEth;
function getOriginalAssetTerra(client, wrappedAddress) {
    return __awaiter(this, void 0, void 0, function* () {
        if (terra_1.isNativeDenom(wrappedAddress)) {
            return {
                isWrapped: false,
                chainId: utils_2.CHAIN_ID_TERRA,
                assetAddress: terra_1.buildNativeId(wrappedAddress),
            };
        }
        try {
            const result = yield client.wasm.contractQuery(wrappedAddress, {
                wrapped_asset_info: {},
            });
            if (result) {
                return {
                    isWrapped: true,
                    chainId: result.asset_chain,
                    assetAddress: new Uint8Array(Buffer.from(result.asset_address, "base64")),
                };
            }
        }
        catch (e) { }
        return {
            isWrapped: false,
            chainId: utils_2.CHAIN_ID_TERRA,
            assetAddress: utils_1.zeroPad(terra_1.canonicalAddress(wrappedAddress), 32),
        };
    });
}
exports.getOriginalAssetTerra = getOriginalAssetTerra;
/**
 * Returns a origin chain and asset address on {originChain} for a provided Wormhole wrapped address
 * @param connection
 * @param tokenBridgeAddress
 * @param mintAddress
 * @returns
 */
function getOriginalAssetSol(connection, tokenBridgeAddress, mintAddress) {
    return __awaiter(this, void 0, void 0, function* () {
        if (mintAddress) {
            // TODO: share some of this with getIsWrappedAssetSol, like a getWrappedMetaAccountAddress or something
            const { parse_wrapped_meta, wrapped_meta_address } = yield wasm_1.importTokenWasm();
            const wrappedMetaAddress = wrapped_meta_address(tokenBridgeAddress, new web3_js_1.PublicKey(mintAddress).toBytes());
            const wrappedMetaAddressPK = new web3_js_1.PublicKey(wrappedMetaAddress);
            const wrappedMetaAccountInfo = yield connection.getAccountInfo(wrappedMetaAddressPK);
            if (wrappedMetaAccountInfo) {
                const parsed = parse_wrapped_meta(wrappedMetaAccountInfo.data);
                return {
                    isWrapped: true,
                    chainId: parsed.chain,
                    assetAddress: parsed.token_address,
                };
            }
        }
        try {
            return {
                isWrapped: false,
                chainId: utils_2.CHAIN_ID_SOLANA,
                assetAddress: new web3_js_1.PublicKey(mintAddress).toBytes(),
            };
        }
        catch (e) { }
        return {
            isWrapped: false,
            chainId: utils_2.CHAIN_ID_SOLANA,
            assetAddress: new Uint8Array(32),
        };
    });
}
exports.getOriginalAssetSol = getOriginalAssetSol;
/**
 * Returns an origin chain and asset address on {originChain} for a provided Wormhole wrapped address
 * @param client Algodv2 client
 * @param tokenBridgeId Application ID of the token bridge
 * @param assetId Algorand asset index
 * @returns wrapped wormhole information structure
 */
function getOriginalAssetAlgorand(client, tokenBridgeId, assetId) {
    return __awaiter(this, void 0, void 0, function* () {
        let retVal = {
            isWrapped: false,
            chainId: utils_2.CHAIN_ID_ALGORAND,
            assetAddress: new Uint8Array(),
        };
        retVal.isWrapped = yield getIsWrappedAsset_1.getIsWrappedAssetAlgorand(client, tokenBridgeId, assetId);
        if (!retVal.isWrapped) {
            retVal.assetAddress = utils_1.zeroPad(utils_1.arrayify(ethers_1.ethers.BigNumber.from(assetId)), 32);
            return retVal;
        }
        const assetInfo = yield client.getAssetByID(bigint_1.safeBigIntToNumber(assetId)).do();
        const lsa = assetInfo.params.creator;
        const dls = yield algorand_1.decodeLocalState(client, tokenBridgeId, lsa);
        const dlsBuffer = Buffer.from(dls);
        retVal.chainId = dlsBuffer.readInt16BE(92);
        retVal.assetAddress = new Uint8Array(dlsBuffer.slice(60, 60 + 32));
        return retVal;
    });
}
exports.getOriginalAssetAlgorand = getOriginalAssetAlgorand;
