"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.redeemOnSolana = exports.redeemAndUnwrapOnSolana = exports.redeemOnEthNative = exports.redeemOnEth = void 0;
const spl_token_1 = require("@solana/spl-token");
const web3_js_1 = require("@solana/web3.js");
const ethers_contracts_1 = require("../ethers-contracts");
const tokenBridge_1 = require("../solana/tokenBridge");
const utils_1 = require("../utils");
const vaa_1 = require("../vaa");
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 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;
