"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.redeemOnSui = exports.redeemOnAptos = exports.redeemOnNear = exports.redeemOnAlgorand = exports.redeemOnSolana = exports.redeemAndUnwrapOnSolana = exports.redeemOnXpla = exports.redeemOnInjective = exports.submitVAAOnInjective = exports.redeemOnTerra = exports.redeemOnEthNative = exports.redeemOnEth = void 0;
const spl_token_1 = require("@solana/spl-token");
const web3_js_1 = require("@solana/web3.js");
const terra_js_1 = require("@terra-money/terra.js");
const js_base64_1 = require("js-base64");
const bn_js_1 = __importDefault(require("bn.js"));
const algorand_1 = require("../algorand");
const ethers_contracts_1 = require("../ethers-contracts");
const utils_1 = require("../utils");
const sdk_ts_1 = require("@injectivelabs/sdk-ts");
const tokenBridge_1 = require("../solana/tokenBridge");
const vaa_1 = require("../vaa");
const getForeignAsset_1 = require("./getForeignAsset");
const xpla_js_1 = require("@xpla/xpla.js");
const aptos_1 = require("../aptos");
const sui_js_1 = require("@mysten/sui.js");
const sui_1 = require("../sui");
function redeemOnEth(tokenBridgeAddress, signer, signedVAA, overrides = {}) {
    return __awaiter(this, void 0, void 0, function* () {
        const bridge = ethers_contracts_1.Bridge__factory.connect(tokenBridgeAddress, signer);
        const v = yield bridge.completeTransfer(signedVAA, overrides);
        const receipt = yield v.wait();
        return receipt;
    });
}
exports.redeemOnEth = redeemOnEth;
function redeemOnEthNative(tokenBridgeAddress, signer, signedVAA, overrides = {}) {
    return __awaiter(this, void 0, void 0, function* () {
        const bridge = ethers_contracts_1.Bridge__factory.connect(tokenBridgeAddress, signer);
        const v = yield bridge.completeTransferAndUnwrapETH(signedVAA, overrides);
        const receipt = yield v.wait();
        return receipt;
    });
}
exports.redeemOnEthNative = redeemOnEthNative;
function redeemOnTerra(tokenBridgeAddress, walletAddress, signedVAA) {
    return __awaiter(this, void 0, void 0, function* () {
        return new terra_js_1.MsgExecuteContract(walletAddress, tokenBridgeAddress, {
            submit_vaa: {
                data: js_base64_1.fromUint8Array(signedVAA),
            },
        });
    });
}
exports.redeemOnTerra = redeemOnTerra;
/**
 * Submits the supplied VAA to Injective
 * @param tokenBridgeAddress Address of Inj token bridge contract
 * @param walletAddress Address of wallet in inj format
 * @param signedVAA VAA with the attestation message
 * @returns Message to be broadcast
 */
function submitVAAOnInjective(tokenBridgeAddress, walletAddress, signedVAA) {
    return __awaiter(this, void 0, void 0, function* () {
        return sdk_ts_1.MsgExecuteContractCompat.fromJSON({
            contractAddress: tokenBridgeAddress,
            sender: walletAddress,
            exec: {
                msg: {
                    data: js_base64_1.fromUint8Array(signedVAA),
                },
                action: "submit_vaa",
            },
        });
    });
}
exports.submitVAAOnInjective = submitVAAOnInjective;
exports.redeemOnInjective = submitVAAOnInjective;
function redeemOnXpla(tokenBridgeAddress, walletAddress, signedVAA) {
    return new xpla_js_1.MsgExecuteContract(walletAddress, tokenBridgeAddress, {
        submit_vaa: {
            data: js_base64_1.fromUint8Array(signedVAA),
        },
    });
}
exports.redeemOnXpla = redeemOnXpla;
function redeemAndUnwrapOnSolana(connection, bridgeAddress, tokenBridgeAddress, payerAddress, signedVaa, commitment) {
    return __awaiter(this, void 0, void 0, function* () {
        const parsed = vaa_1.parseTokenTransferVaa(signedVaa);
        const targetPublicKey = new web3_js_1.PublicKey(parsed.to);
        const targetAmount = yield spl_token_1.getMint(connection, spl_token_1.NATIVE_MINT, commitment).then((info) => parsed.amount * BigInt(Math.pow(10, info.decimals - utils_1.MAX_VAA_DECIMALS)));
        const rentBalance = yield spl_token_1.getMinimumBalanceForRentExemptAccount(connection, commitment);
        if (Buffer.compare(parsed.tokenAddress, spl_token_1.NATIVE_MINT.toBuffer()) != 0) {
            return Promise.reject("tokenAddress != NATIVE_MINT");
        }
        const payerPublicKey = new web3_js_1.PublicKey(payerAddress);
        const ancillaryKeypair = web3_js_1.Keypair.generate();
        const completeTransferIx = tokenBridge_1.createCompleteTransferNativeInstruction(tokenBridgeAddress, bridgeAddress, payerPublicKey, signedVaa);
        //This will create a temporary account where the wSOL will be moved
        const createAncillaryAccountIx = web3_js_1.SystemProgram.createAccount({
            fromPubkey: payerPublicKey,
            newAccountPubkey: ancillaryKeypair.publicKey,
            lamports: rentBalance,
            space: spl_token_1.ACCOUNT_SIZE,
            programId: spl_token_1.TOKEN_PROGRAM_ID,
        });
        //Initialize the account as a WSOL account, with the original payerAddress as owner
        const initAccountIx = spl_token_1.createInitializeAccountInstruction(ancillaryKeypair.publicKey, spl_token_1.NATIVE_MINT, payerPublicKey);
        //Send in the amount of wSOL which we want converted to SOL
        const balanceTransferIx = spl_token_1.createTransferInstruction(targetPublicKey, ancillaryKeypair.publicKey, payerPublicKey, targetAmount.valueOf());
        //Close the ancillary account for cleanup. Payer address receives any remaining funds
        const closeAccountIx = spl_token_1.createCloseAccountInstruction(ancillaryKeypair.publicKey, //account to close
        payerPublicKey, //Remaining funds destination
        payerPublicKey //authority
        );
        const { blockhash } = yield connection.getLatestBlockhash(commitment);
        const transaction = new web3_js_1.Transaction();
        transaction.recentBlockhash = blockhash;
        transaction.feePayer = payerPublicKey;
        transaction.add(completeTransferIx, createAncillaryAccountIx, initAccountIx, balanceTransferIx, closeAccountIx);
        transaction.partialSign(ancillaryKeypair);
        return transaction;
    });
}
exports.redeemAndUnwrapOnSolana = redeemAndUnwrapOnSolana;
function redeemOnSolana(connection, bridgeAddress, tokenBridgeAddress, payerAddress, signedVaa, feeRecipientAddress, commitment) {
    return __awaiter(this, void 0, void 0, function* () {
        const parsed = vaa_1.parseTokenTransferVaa(signedVaa);
        const createCompleteTransferInstruction = parsed.tokenChain == utils_1.CHAIN_ID_SOLANA
            ? tokenBridge_1.createCompleteTransferNativeInstruction
            : tokenBridge_1.createCompleteTransferWrappedInstruction;
        const transaction = new web3_js_1.Transaction().add(createCompleteTransferInstruction(tokenBridgeAddress, bridgeAddress, payerAddress, parsed, feeRecipientAddress));
        const { blockhash } = yield connection.getLatestBlockhash(commitment);
        transaction.recentBlockhash = blockhash;
        transaction.feePayer = new web3_js_1.PublicKey(payerAddress);
        return transaction;
    });
}
exports.redeemOnSolana = redeemOnSolana;
/**
 * This basically just submits the VAA to Algorand
 * @param client AlgodV2 client
 * @param tokenBridgeId Token bridge ID
 * @param bridgeId Core bridge ID
 * @param vaa The VAA to be redeemed
 * @param acct Sending account
 * @returns Transaction ID(s)
 */
function redeemOnAlgorand(client, tokenBridgeId, bridgeId, vaa, senderAddr) {
    return __awaiter(this, void 0, void 0, function* () {
        return yield algorand_1._submitVAAAlgorand(client, tokenBridgeId, bridgeId, vaa, senderAddr);
    });
}
exports.redeemOnAlgorand = redeemOnAlgorand;
function redeemOnNear(provider, account, tokenBridge, vaa) {
    return __awaiter(this, void 0, void 0, function* () {
        const options = [];
        const p = algorand_1._parseVAAAlgorand(vaa);
        if (p.ToChain !== utils_1.CHAIN_ID_NEAR) {
            throw new Error("Not destined for NEAR");
        }
        const { found, value: receiver } = yield utils_1.hashLookup(provider, tokenBridge, utils_1.uint8ArrayToHex(p.ToAddress));
        if (!found) {
            throw new Error("Unregistered receiver (receiving account is not registered)");
        }
        const token = yield getForeignAsset_1.getForeignAssetNear(provider, tokenBridge, p.FromChain, p.Contract);
        if (p.Contract !==
            "0000000000000000000000000000000000000000000000000000000000000000") {
            if (token === "" || token === null) {
                throw new Error("Unregistered token (has it been attested?)");
            }
            const bal = yield utils_1.callFunctionNear(provider, token, "storage_balance_of", {
                account_id: receiver,
            });
            if (bal === null) {
                options.push({
                    contractId: token,
                    methodName: "storage_deposit",
                    args: { account_id: receiver, registration_only: true },
                    gas: new bn_js_1.default("100000000000000"),
                    attachedDeposit: new bn_js_1.default("2000000000000000000000"), // 0.002 NEAR
                });
            }
            if (p.Fee !== undefined &&
                Buffer.compare(p.Fee, Buffer.from("0000000000000000000000000000000000000000000000000000000000000000", "hex")) !== 0) {
                const bal = yield utils_1.callFunctionNear(provider, token, "storage_balance_of", {
                    account_id: account,
                });
                if (bal === null) {
                    options.push({
                        contractId: token,
                        methodName: "storage_deposit",
                        args: { account_id: account, registration_only: true },
                        gas: new bn_js_1.default("100000000000000"),
                        attachedDeposit: new bn_js_1.default("2000000000000000000000"), // 0.002 NEAR
                    });
                }
            }
        }
        options.push({
            contractId: tokenBridge,
            methodName: "submit_vaa",
            args: {
                vaa: utils_1.uint8ArrayToHex(vaa),
            },
            attachedDeposit: new bn_js_1.default("100000000000000000000000"),
            gas: new bn_js_1.default("150000000000000"),
        });
        options.push({
            contractId: tokenBridge,
            methodName: "submit_vaa",
            args: {
                vaa: utils_1.uint8ArrayToHex(vaa),
            },
            attachedDeposit: new bn_js_1.default("100000000000000000000000"),
            gas: new bn_js_1.default("150000000000000"),
        });
        return options;
    });
}
exports.redeemOnNear = redeemOnNear;
/**
 * Register the token specified in the given VAA in the transfer recipient's account if necessary
 * and complete the transfer.
 * @param client Client used to transfer data to/from Aptos node
 * @param tokenBridgeAddress Address of token bridge
 * @param transferVAA Bytes of transfer VAA
 * @returns Transaction payload
 */
function redeemOnAptos(client, tokenBridgeAddress, transferVAA) {
    return aptos_1.completeTransferAndRegister(client, tokenBridgeAddress, transferVAA);
}
exports.redeemOnAptos = redeemOnAptos;
function redeemOnSui(provider, coreBridgeStateObjectId, tokenBridgeStateObjectId, transferVAA) {
    return __awaiter(this, void 0, void 0, function* () {
        const { tokenAddress, tokenChain } = vaa_1.parseTokenTransferVaa(transferVAA);
        const coinType = yield sui_1.getTokenCoinType(provider, tokenBridgeStateObjectId, tokenAddress, tokenChain);
        if (!coinType) {
            throw new Error("Unable to fetch token coinType");
        }
        const coreBridgePackageId = yield sui_1.getPackageId(provider, coreBridgeStateObjectId);
        const tokenBridgePackageId = yield sui_1.getPackageId(provider, tokenBridgeStateObjectId);
        const tx = new sui_js_1.TransactionBlock();
        const [verifiedVAA] = tx.moveCall({
            target: `${coreBridgePackageId}::vaa::parse_and_verify`,
            arguments: [
                tx.object(coreBridgeStateObjectId),
                tx.pure([...transferVAA]),
                tx.object(sui_js_1.SUI_CLOCK_OBJECT_ID),
            ],
        });
        const [tokenBridgeMessage] = tx.moveCall({
            target: `${tokenBridgePackageId}::vaa::verify_only_once`,
            arguments: [tx.object(tokenBridgeStateObjectId), verifiedVAA],
        });
        const [relayerReceipt] = tx.moveCall({
            target: `${tokenBridgePackageId}::complete_transfer::authorize_transfer`,
            arguments: [tx.object(tokenBridgeStateObjectId), tokenBridgeMessage],
            typeArguments: [coinType],
        });
        const [coins] = tx.moveCall({
            target: `${tokenBridgePackageId}::complete_transfer::redeem_relayer_payout`,
            arguments: [relayerReceipt],
            typeArguments: [coinType],
        });
        tx.moveCall({
            target: `${tokenBridgePackageId}::coin_utils::return_nonzero`,
            arguments: [coins],
            typeArguments: [coinType],
        });
        return tx;
    });
}
exports.redeemOnSui = redeemOnSui;
